Exemplo n.º 1
0
    def demo(self, args):
        from omero.util.temp_files import create_path
        t = create_path("Demo_Script", ".py")

        try:
            from hashlib import sha1 as sha_new
        except ImportError:
            from sha import new as sha_new

        digest = sha_new()
        digest.update(DEMO_SCRIPT)
        sha1 = digest.hexdigest()

        self.ctx.out("\nExample script writing session")
        self.ctx.out("=" * 80)

        def msg(title, method=None, *arguments):
            self.ctx.out("\n")
            self.ctx.out("\t+" + ("-" * 68) + "+")
            title = "\t| %-66.66s | " % title
            self.ctx.out(title)
            if method:
                cmd = "%s %s" % (method.__name__, " ".join(arguments))
                cmd = "\t| COMMAND: bin/omero script %-40.40s | " % cmd
                self.ctx.out(cmd)
            self.ctx.out("\t+" + ("-" * 68) + "+")
            self.ctx.out(" ")
            if method:
                try:
                    self.ctx.invoke(['script', method.__name__] +
                                    list(arguments))
                except Exception, e:
                    import traceback
                    self.ctx.out("\nEXECUTION FAILED: %s" % e)
                    self.ctx.dbg(traceback.format_exc())
Exemplo n.º 2
0
    def demo(self, args):
        from omero.util.temp_files import create_path
        t = create_path("Demo_Script", ".py")

        try:
            from hashlib import sha1 as sha_new
        except ImportError:
            from sha import new as sha_new

        digest = sha_new()
        digest.update(DEMO_SCRIPT)
        sha1 = digest.hexdigest()

        self.ctx.out("\nExample script writing session")
        self.ctx.out("="*80)

        def msg(title, method=None, *arguments):
            self.ctx.out("\n")
            self.ctx.out("\t+" + ("-"*68) + "+")
            title = "\t| %-66.66s | " % title
            self.ctx.out(title)
            if method:
                cmd = "%s %s" % (method.__name__, " ".join(arguments))
                cmd = "\t| COMMAND: bin/omero script %-40.40s | " % cmd
                self.ctx.out(cmd)
            self.ctx.out("\t+" + ("-"*68) + "+")
            self.ctx.out(" ")
            if method:
                try:
                    self.ctx.invoke(['script', method.__name__] +
                                    list(arguments))
                except Exception, e:
                    import traceback
                    self.ctx.out("\nEXECUTION FAILED: %s" % e)
                    self.ctx.dbg(traceback.format_exc())
    def test_expireUser(self):
        # http://www.dataflake.org/tracker/issue_00617 etc.
        try:
            from hashlib import sha1 as sha_new
        except ImportError:
            from sha import new as sha_new

        acl = self.folder.acl_users

        # Retrieving an invalid user should return None
        nonexisting = acl.getUserById('invalid')
        self.failUnless(nonexisting is None)

        # The retrieval above will add the invalid user to the negative cache
        negative_cache_key = '%s:%s:%s' % (acl._uid_attr, 'invalid',
                                           sha_new('').hexdigest())
        self.failIf(acl._cache('negative').get(negative_cache_key) is None)

        # Expiring the user must remove it from the negative cache
        acl._expireUser('invalid')
        self.failUnless(acl._cache('negative').get(negative_cache_key) is None)

        # User IDs that come in as unicode should not break anything.
        # https://bugs.launchpad.net/bugs/700071
        acl._expireUser(u'invalid')
Exemplo n.º 4
0
    def test_expireUser(self):
        # http://www.dataflake.org/tracker/issue_00617 etc.
        try:
            from hashlib import sha1 as sha_new
        except ImportError:
            from sha import new as sha_new

        acl = self.folder.acl_users
    
        # Retrieving an invalid user should return None
        nonexisting = acl.getUserById('invalid')
        self.failUnless(nonexisting is None)
    
        # The retrieval above will add the invalid user to the negative cache
        negative_cache_key = '%s:%s:%s' % ( acl._uid_attr
                                          , 'invalid'
                                          , sha_new('').hexdigest()
                                          )
        self.failIf(acl._cache('negative').get(negative_cache_key) is None)
    
        # Expiring the user must remove it from the negative cache
        acl._expireUser('invalid')
        self.failUnless(acl._cache('negative').get(negative_cache_key) is None)

        # User IDs that come in as unicode should not break anything.
        # https://bugs.launchpad.net/bugs/700071
        acl._expireUser(u'invalid')
Exemplo n.º 5
0
 def getOrderValidationText(self, message):
   # Return an identifier of validators related to ordering.
   order_validation_item_list = []
   key_list = message.activity_kw.keys()
   key_list.sort()
   for key in key_list:
     method_id = "_validate_%s" % key
     if getattr(self, method_id, None) is not None:
       order_validation_item_list.append((key, message.activity_kw[key]))
   if len(order_validation_item_list) == 0:
     # When no order validation argument is specified, skip the computation
     # of the checksum for speed. Here, 'none' is used, because this never be
     # identical to SHA1 hexdigest (which is always 40 characters), and 'none'
     # is true in Python. This is important, because dtml-if assumes that an empty
     # string is false, so we must use a non-empty string for this.
     return 'none'
   return sha_new(repr(order_validation_item_list)).hexdigest()
Exemplo n.º 6
0
 def sha1(self, filename):
     """
     Calculates the local sha1 for a file.
     """
     try:
         from hashlib import sha1 as sha_new
     except ImportError:
         from sha import new as sha_new
     digest = sha_new()
     file = open(filename, 'rb')
     try:
         while True:
             block = file.read(1024)
             if not block:
                 break
             digest.update(block)
     finally:
         file.close()
     return digest.hexdigest()
Exemplo n.º 7
0
 def sha1(self, filename):
     """
     Calculates the local sha1 for a file.
     """
     try:
         from hashlib import sha1 as sha_new
     except ImportError:
         from sha import new as sha_new
     digest = sha_new()
     file = open(filename, 'rb')
     try:
         while True:
             block = file.read(1024)
             if not block:
                 break
             digest.update(block)
     finally:
         file.close()
     return digest.hexdigest()
Exemplo n.º 8
0
    def demo(self, args):
        from omero.util.temp_files import create_path
        t = create_path("Demo_Script", ".py")

        try:
            from hashlib import sha1 as sha_new
        except ImportError:
            from sha import new as sha_new

        digest = sha_new()
        digest.update(DEMO_SCRIPT.encode('utf-8'))
        sha1 = digest.hexdigest()

        self.ctx.out("\nExample script writing session")
        self.ctx.out("=" * 80)

        def msg(title, method=None, *arguments):
            self.ctx.out("\n")
            self.ctx.out("\t+" + ("-" * 68) + "+")
            title = "\t| %-66.66s | " % title
            self.ctx.out(title)
            if method:
                cmd = "%s %s" % (method.__name__, " ".join(arguments))
                cmd = "\t| COMMAND: omero script %-40.40s | " % cmd
                self.ctx.out(cmd)
            self.ctx.out("\t+" + ("-" * 68) + "+")
            self.ctx.out(" ")
            if method:
                try:
                    self.ctx.invoke(['script', method.__name__] +
                                    list(arguments))
                except Exception as e:
                    import traceback
                    self.ctx.out("\nEXECUTION FAILED: %s" % e)
                    self.ctx.dbg(traceback.format_exc())

        client = self.ctx.conn(args)
        current_user = self.ctx.get_event_context().userId
        query = "select o from OriginalFile o where o.hash = '%s' and" \
            " o.details.owner.id = %s" % (sha1, current_user)
        files = client.sf.getQueryService().findAllByQuery(query, None)
        if len(files) == 0:
            msg("Saving demo script to %s" % t)
            t.write_text(DEMO_SCRIPT)

            msg("Uploading script", self.upload, str(t))
            id = self.ctx.get("script.file.id")
        else:
            id = files[0].id.val
            msg("Reusing demo script %s" % id)

        msg("Listing available scripts for user", self.list, "user")
        msg("Printing script content for file %s" % id, self.cat, str(id))
        msg("Serving file %s in background" % id, self.serve, "user",
            "--background")
        msg("Printing script params for file %s" % id, self.params,
            "file=%s" % id)
        msg("Launching script with parameters: a=bad-string (fails)",
            self.launch, "file=%s" % id, "a=bad-string")
        msg("Launching script with parameters: a=bad-string opt=6 (fails)",
            self.launch, "file=%s" % id, "a=bad-string", "opt=6")
        msg("Launching script with parameters: a=foo opt=1 (passes)",
            self.launch, "file=%s" % id, "a=foo", "opt=1")
        try:
            for p in list(getattr(self, "_processors", [])):
                p.cleanup()
                self._processors.remove(p)
        except Exception as e:
            self.ctx.err("Failed to clean processors: %s" % e)

        self.ctx.out("\nDeleting script from server...")
        args.id = int(id)
        self.delete(args)
Exemplo n.º 9
0
def getUserByAttr(self, name, value, pwd=None, cache=0):
    """
        Get a user based on a name/value pair representing an
        LDAP attribute provided to the user.  If cache is True,
        try to cache the result using 'value' as the key
    """
    if not value:
        return None

    cache_type = pwd and 'authenticated' or 'anonymous'
    negative_cache_key = '%s:%s:%s' % (name, value, sha_new(pwd
                                                            or '').hexdigest())
    if cache:
        if self._cache('negative').get(negative_cache_key) is not None:
            return None

        cached_user = self._cache(cache_type).get(value, pwd)

        if cached_user:
            msg = 'getUserByAttr: "%s" cached in %s cache' % (value,
                                                              cache_type)
            logger.debug(msg)
            return cached_user

    user_roles, user_dn, user_attrs, ldap_groups = self._lookupuserbyattr(
        name=name, value=value, pwd=pwd)

    if user_dn is None:
        logger.debug('getUserByAttr: "%s=%s" not found' % (name, value))
        self._cache('negative').set(negative_cache_key, NonexistingUser())
        return None

    if user_attrs is None:
        msg = 'getUserByAttr: "%s=%s" has no properties, bailing' % (name,
                                                                     value)
        logger.debug(msg)
        self._cache('negative').set(negative_cache_key, NonexistingUser())
        return None

    if user_roles is None or user_roles == self._roles:
        msg = 'getUserByAttr: "%s=%s" only has roles %s' % (name, value,
                                                            str(user_roles))
        logger.debug(msg)

    login_name = user_attrs.get(self._login_attr, '')
    uid = user_attrs.get(self._uid_attr, '')

    if self._login_attr != 'dn' and len(login_name) > 0:
        try:
            if name == self._login_attr:
                logins = [
                    x for x in login_name
                    if value.strip().lower() == x.lower()
                ]
                login_name = logins[0]
            else:
                login_name = login_name[0]
        except:
            msg = ('****getUserByAttr: logins %s and login_name %s' %
                   (logins, login_name))
            logger.error(msg)
            pass

    elif len(login_name) == 0:
        msg = 'getUserByAttr: "%s" has no "%s" (Login) value!' % (
            user_dn, self._login_attr)
        logger.debug(msg)
        self._cache('negative').set(negative_cache_key, NonexistingUser())
        return None

    if self._uid_attr != 'dn' and len(uid) > 0:
        uid = uid[0]
    elif len(uid) == 0:
        msg = 'getUserByAttr: "%s" has no "%s" (UID Attribute) value!' % (
            user_dn, self._uid_attr)
        logger.debug(msg)
        self._cache('negative').set(negative_cache_key, NonexistingUser())
        return None

    # BEGIN PATCH
    login_name = login_name.lower()
    uid = uid.lower()
    # END PATCH

    user_obj = LDAPUser(uid,
                        login_name,
                        pwd or 'undef',
                        user_roles or [], [],
                        user_dn,
                        user_attrs,
                        self.getMappedUserAttrs(),
                        self.getMultivaluedUserAttrs(),
                        ldap_groups=ldap_groups)

    if cache:
        self._cache(cache_type).set(value, user_obj)

    return user_obj
Exemplo n.º 10
0
def hash_pwd(pwd_str):
    if isinstance(pwd_str, six.text_type):
        pwd_str = pwd_str.encode('utf-8')
    sha_digest = sha_new(pwd_str).digest()
    return b'{SHA}%s' % b64encode(sha_digest).strip()
Exemplo n.º 11
0
def getUserByAttr(self, name, value, pwd=None, cache=0):
    """
        Get a user based on a name/value pair representing an
        LDAP attribute provided to the user.  If cache is True,
        try to cache the result using 'value' as the key
    """
    if not value:
        return None

    cache_type = pwd and 'authenticated' or 'anonymous'
    negative_cache_key = '%s:%s:%s' % (name,
                                       value,
                                       sha_new(pwd or '').hexdigest())
    if cache:
        if self._cache('negative').get(negative_cache_key) is not None:
            return None

        cached_user = self._cache(cache_type).get(value, pwd)

        if cached_user:
            msg = 'getUserByAttr: "%s" cached in %s cache' % (value, cache_type)
            logger.debug(msg)
            return cached_user

    user_roles, user_dn, user_attrs, ldap_groups = self._lookupuserbyattr(name=name, value=value, pwd=pwd)

    if user_dn is None:
        logger.debug('getUserByAttr: "%s=%s" not found' % (name, value))
        self._cache('negative').set(negative_cache_key, NonexistingUser())
        return None

    if user_attrs is None:
        msg = 'getUserByAttr: "%s=%s" has no properties, bailing' % (name, value)
        logger.debug(msg)
        self._cache('negative').set(negative_cache_key, NonexistingUser())
        return None

    if user_roles is None or user_roles == self._roles:
        msg = 'getUserByAttr: "%s=%s" only has roles %s' % (name, value, str(user_roles))
        logger.debug(msg)

    login_name = user_attrs.get(self._login_attr, '')
    uid = user_attrs.get(self._uid_attr, '')

    if self._login_attr != 'dn' and len(login_name) > 0:
        try:
            if name == self._login_attr:
                logins = [x for x in login_name
                          if value.strip().lower() == x.lower()]
                login_name = logins[0]
            else:
                login_name = login_name[0]
        except:
            msg = ('****getUserByAttr: logins %s and login_name %s' % (logins, login_name))
            logger.error(msg)
            pass

    elif len(login_name) == 0:
        msg = 'getUserByAttr: "%s" has no "%s" (Login) value!' % (user_dn, self._login_attr)
        logger.debug(msg)
        self._cache('negative').set(negative_cache_key, NonexistingUser())
        return None

    if self._uid_attr != 'dn' and len(uid) > 0:
        uid = uid[0]
    elif len(uid) == 0:
        msg = 'getUserByAttr: "%s" has no "%s" (UID Attribute) value!' % (user_dn, self._uid_attr)
        logger.debug(msg)
        self._cache('negative').set(negative_cache_key, NonexistingUser())
        return None

    # BEGIN PATCH
    login_name = login_name.lower()
    uid = uid.lower()
    # END PATCH

    user_obj = LDAPUser(uid,
                        login_name,
                        pwd or 'undef',
                        user_roles or [],
                        [],
                        user_dn,
                        user_attrs,
                        self.getMappedUserAttrs(),
                        self.getMultivaluedUserAttrs(),
                        ldap_groups=ldap_groups)

    if cache:
        self._cache(cache_type).set(value, user_obj)

    return user_obj
Exemplo n.º 12
0
def hash_pwd(string):
    if isinstance(string, unicode):
        string = string.encode('utf-8')
    sha_digest = sha_new(string).digest()
    return '{SHA}%s' % base64.encodestring(sha_digest).strip()