def getAssociation(self, server_url, handle=None):
        stored_assocs = OpenIDStoreModel.objects.filter(
            server_url=server_url
        )
        if handle:
            stored_assocs = stored_assocs.filter(handle=handle)

        stored_assocs.order_by('-issued')

        if stored_assocs.count() == 0:
            return None

        return_val = None

        for stored_assoc in stored_assocs:
            assoc = OIDAssociation(
                stored_assoc.handle, base64.decodestring(stored_assoc.secret),
                stored_assoc.issued, stored_assoc.lifetime, stored_assoc.assoc_type
            )

            if assoc.getExpiresIn() == 0:
                stored_assoc.delete()
            else:
                if return_val is None:
                    return_val = assoc

        return return_val
예제 #2
0
 def getAssociation(self, server_url, handle=None):
     log_debug = self.log_debug
     
     if log_debug:
         log.debug('Association requested for server_url: %s, with handle: %s', server_url, handle)
     
     if handle is None:
         # Retrieve all the keys for this server connection
         key_name = self.getAssociationFilename(server_url, '')
         assocs = self._conn.keys('%s*' % key_name)
         
         if not assocs:
             if log_debug:
                 log.debug('No association found for: %s', server_url)
             return None
         
         # Now use the one that was issued most recently
         associations = []
         for assoc in self._conn.mget(assocs):
             associations.append(Association.deserialize(assoc))
         associations.sort(cmp=lambda x,y: cmp(x.issued, y.issued))
         if log_debug:
             log.debug('getAssociation found, returns most recently issued')
         return associations[-1]
     else:
         key_name = self.getAssociationFilename(server_url, handle)
         association_s = self._conn.get(key_name)
         if association_s:
             if log_debug:
                 log.debug('getAssociation found, returning association')
             return Association.deserialize(association_s)
         else:
             if log_debug:
                 log.debug('No association found for getAssociation')
             return None
예제 #3
0
 def getAssociation(self, server_url, handle=None):
     assocs = []
     if handle is not None:
         assocs = Association.objects.filter(
             server_url = server_url, handle = handle
         )
     else:
         assocs = Association.objects.filter(
             server_url = server_url
         )
     if not assocs:
         return None
     associations = []
     for assoc in assocs:
         association = OIDAssociation(
             assoc.handle, base64.decodestring(assoc.secret), assoc.issued,
             assoc.lifetime, assoc.assoc_type
         )
         if association.getExpiresIn() == 0:
             self.removeAssociation(server_url, assoc.handle)
         else:
             associations.append((association.issued, association))
     if not associations:
         return None
     return associations[-1][1]
예제 #4
0
 def getAssociation(self, server_url, handle=None):
     assocs = []
     if handle is not None:
         assocs = Association.view('%s/url_handle_view' %
                                   Association._meta.app_label,
                                   key=[server_url, handle],
                                   include_docs=True).all()
     else:
         assocs = Association.view('%s/url_view' %
                                   Association._meta.app_label,
                                   key=server_url,
                                   include_docs=True).all()
     associations = []
     try:
         for assoc in assocs:
             association = OIDAssociation(
                 assoc['handle'], base64.decodestring(assoc['secret']),
                 assoc['issued'], assoc['lifetime'], assoc['assoc_type'])
             if association.getExpiresIn() == 0:
                 self.removeAssociation(server_url, assoc.handle)
             else:
                 associations.append((association.issued, association))
     except ResourceNotFound:
         pass
     if not associations:
         return None
     return associations[-1][1]
예제 #5
0
    def getAssociation(self, server_url, handle=None):
        assocs = []
        if handle is not None:
            assocs = Association.query.filter_by(server_url=server_url,
                                                 handle=handle)
        else:
            assocs = Association.query.filter_by(server_url=server_url)

        if assocs.count() == 0:
            return None
        else:
            associations = []
            for assoc in assocs:
                association = OIDAssociation(assoc.handle,
                                             base64.decodestring(assoc.secret),
                                             assoc.issued, assoc.lifetime,
                                             assoc.assoc_type)
                if association.getExpiresIn() == 0:
                    assoc.delete()
                else:
                    associations.append((association.issued, association))

            if not associations:
                return None
            associations.sort()
            return associations[-1][1]
예제 #6
0
 def getAssociation(self, server_url, handle=None):
     assocs = []
     if handle is not None:
         assocs = Association.objects.filter(
             server_url = server_url, handle = handle
         )
     else:
         assocs = Association.objects.filter(
             server_url = server_url
         )
     if not assocs:
         return None
     associations = []
     for assoc in assocs:
         association = OIDAssociation(
             assoc.handle, base64.decodestring(assoc.secret), assoc.issued,
             assoc.lifetime, assoc.assoc_type
         )
         if association.getExpiresIn() == 0:
             self.removeAssociation(server_url, assoc.handle)
         else:
             associations.append((association.issued, association))
     if not associations:
         return None
     return associations[-1][1]
예제 #7
0
    def getAssociation(self, server_url, handle=None):
        if handle is None:
            return None

        server_url_hash = hashlib.sha256(server_url).hexdigest()
        handle_hash = hashlib.sha256(handle).hexdigest()
        rowkey = "%s_%s" % (server_url_hash, handle_hash)
        
        try:
            assoc_rec = cass.getRecord(self._cf, rowkey)
        except cass.NotFoundError:
            return None
        except cass.DatabaseError:
            raise
        
        server_url = assoc_rec['server_url']
        handle = assoc_rec['handle']
        secret = assoc_rec['secret']
        issued = assoc_rec['issued']
        lifetime = assoc_rec['lifetime']
        assoc_type = assoc_rec['assoc_type']
        
        association = Association(handle, secret, issued, lifetime, assoc_type)
        
        if association.getExpiresIn() == 0:
            return None
        
        return association
예제 #8
0
    def txn_getAssociation(self, server_url, handle=None):
        """Get the most recent association that has been set for this
        server URL and handle.

        str -> NoneType or Association
        """
        if handle is not None:
            self.db_get_assoc(server_url, handle)
        else:
            self.db_get_assocs(server_url)

        rows = self.cur.fetchall()
        if len(rows) == 0:
            return None
        else:
            associations = []
            for values in rows:
                assoc = Association(*values)
                assoc.secret = self.blobDecode(assoc.secret)
                if assoc.getExpiresIn() == 0:
                    self.txn_removeAssociation(server_url, assoc.handle)
                else:
                    associations.append((assoc.issued, assoc))

            if associations:
                associations.sort()
                return associations[-1][1]
            else:
                return None
예제 #9
0
 def getAssociation(self, server_url, handle=None):
     log.debug("Association requested for server_url: %s, with handle: %s",
               server_url, handle)
     if server_url.find('://') == -1:
         raise ValueError('Bad server URL: %r' % server_url)
     if handle is None:
         associations = self.associations.find({"server_url": server_url})
         if associations.count():
             associations = [
                 Association.deserialize(a['association'])
                 for a in associations
             ]
             # Now use the one that was issued most recently
             associations.sort(cmp=lambda x, y: cmp(x.issued, y.issued))
             log.debug("Most recent is %s", associations[-1].handle)
             return associations[-1]
     else:
         association = self.associations.find_one({
             "_id":
             hash((server_url, handle)),
             "server_url":
             server_url,
             "handle":
             handle
         })
         if association:
             return Association.deserialize(association['association'])
예제 #10
0
파일: store.py 프로젝트: ausbin/mediagoblin
    def getAssociation(self, server_url, handle=None):
        assocs = []
        if handle is not None:
            assocs = Association.query.filter_by(
                server_url=server_url, handle=handle
            )
        else:
            assocs = Association.query.filter_by(
                server_url=server_url
            )

        if assocs.count() == 0:
            return None
        else:
            associations = []
            for assoc in assocs:
                association = OIDAssociation(
                    assoc.handle, base64.decodestring(assoc.secret),
                    assoc.issued, assoc.lifetime, assoc.assoc_type
                )
                if association.getExpiresIn() == 0:
                    assoc.delete()
                else:
                    associations.append((association.issued, association))

            if not associations:
                return None
            associations.sort()
            return associations[-1][1]
예제 #11
0
    def txn_getAssociation(self, server_url, handle=None):
        """Get the most recent association that has been set for this
        server URL and handle.

        @type server_url: six.text_type, six.binary_type is deprecated
        @rtype: Optional[Association]
        """
        server_url = string_to_text(server_url, "Binary values for server_url are deprecated. Use text input instead.")

        if handle is not None:
            self.db_get_assoc(server_url, handle)
        else:
            self.db_get_assocs(server_url)

        rows = self.cur.fetchall()
        if len(rows) == 0:
            return None
        else:
            associations = []
            for values in rows:
                # Decode secret before association is created
                handle, secret, issued, lifetime, assoc_type = values
                secret = self.blobDecode(secret)
                assoc = Association(handle, secret, issued, lifetime, assoc_type)
                if assoc.getExpiresIn() == 0:
                    self.txn_removeAssociation(server_url, assoc.handle)
                else:
                    associations.append((assoc.issued, assoc))

            if associations:
                associations.sort()
                return associations[-1][1]
            else:
                return None
예제 #12
0
    def getAssociation(self, server_url, handle=None):
        assocs = []
        if handle is not None:
            assocs = Association.objects.filter(
                server_url=server_url, handle=handle,
            )
        else:
            assocs = Association.objects.filter(server_url=server_url)
        if not assocs:
            return None
        associations = []
        expired = []
        for assoc in assocs:
            association = OIDAssociation(
                assoc.handle, base64.decodestring(assoc.secret), assoc.issued,
                assoc.lifetime, assoc.assoc_type,
            )
            if association.getExpiresIn() == 0:
                expired.append(assoc)
            else:
                associations.append((association.issued, association))

        for assoc in expired:
            assoc.delete()
        if not associations:
            return None
        associations.sort()
        return associations[-1][1]
예제 #13
0
    def getAssociation(self, server_url, handle=None):
        stored_assocs = OpenIDStore.objects.filter(
            server_url=server_url
        )
        if handle:
            stored_assocs = stored_assocs.filter(handle=handle)

        stored_assocs.order_by('-issued')

        if stored_assocs.count() == 0:
            return None

        return_val = None

        for stored_assoc in stored_assocs:
            assoc = OIDAssociation(
                stored_assoc.handle,
                base64.decodestring(stored_assoc.secret.encode('utf-8')),
                stored_assoc.issued, stored_assoc.lifetime,
                stored_assoc.assoc_type
            )
            # See:
            # necaris/python3-openid@1abb155c8fc7b508241cbe9d2cae24f18e4a379b
            if hasattr(assoc, 'getExpiresIn'):
                expires_in = assoc.getExpiresIn()
            else:
                expires_in = assoc.expiresIn
            if expires_in == 0:
                stored_assoc.delete()
            else:
                if return_val is None:
                    return_val = assoc

        return return_val
예제 #14
0
        def getAssociation(self, server_url, handle = None):
                associations = None
                if handle is not None:
                        associations = OidStoreAssociation.objects.filter(server_url = server_url, handle = handle)
                else:
                        associations = OidStoreAssociation.objects.filter(server_url = server_url)
                if associations.count() == 0:
                        return None
                else:
                        assocs = []
                        for a in associations:
                                adata = [a.handle, self.blobDecode(a.secret), a.issued, a.lifetime, a.assoc_type]

                                assoc = Association(*adata)

                                if assoc.getExpiresIn() == 0:
                                        self.removeAssociation(server_url, assoc.handle)
                                else:
                                        assocs.append((assoc.issued, assoc))
                         
                        if assocs:
                                assocs.sort()
                                return assocs[-1][1]
                        else:
                                return None
예제 #15
0
파일: sqlstore.py 프로젝트: 18600597055/hue
    def txn_getAssociation(self, server_url, handle=None):
        """Get the most recent association that has been set for this
        server URL and handle.

        str -> NoneType or Association
        """
        if handle is not None:
            self.db_get_assoc(server_url, handle)
        else:
            self.db_get_assocs(server_url)

        rows = self.cur.fetchall()
        if len(rows) == 0:
            return None
        else:
            associations = []
            for values in rows:
                assoc = Association(*values)
                assoc.secret = self.blobDecode(assoc.secret)
                if assoc.getExpiresIn() == 0:
                    self.txn_removeAssociation(server_url, assoc.handle)
                else:
                    associations.append((assoc.issued, assoc))

            if associations:
                associations.sort()
                return associations[-1][1]
            else:
                return None
예제 #16
0
    def getAssociation(self, server_url, handle=None):
        stored_assocs = OpenIDStoreModel.objects.filter(
            server_url=server_url
        )
        if handle:
            stored_assocs = stored_assocs.filter(handle=handle)

        stored_assocs.order_by('-issued')

        if stored_assocs.count() == 0:
            return None

        return_val = None

        for stored_assoc in stored_assocs:
            assoc = OIDAssociation(
                stored_assoc.handle, base64.decodestring(stored_assoc.secret),
                stored_assoc.issued, stored_assoc.lifetime, stored_assoc.assoc_type
            )

            if assoc.getExpiresIn() == 0:
                stored_assoc.delete()
            else:
                if return_val is None:
                    return_val = assoc

        return return_val
예제 #17
0
 def test_storeAssociation(self):
     """Tests the NDBOpenIDStore.storeAssociation(server_url, association) method."""
     
     # create association
     association = Association(handle='handle',
                               secret='secret',
                               issued=int(time.time()),
                               lifetime=3600,
                               assoc_type='HMAC-SHA1')
     
     server_url = 'server_url_abc'
     
     # store association
     NDBOpenIDStore.storeAssociation(server_url, association)
     
     # retrieve association
     key = ndb.Key('ServerUrl', server_url, NDBOpenIDStore, association.handle)
     entity = key.get()
     
     # check if entity exists
     assert entity is not None
     
     # check whether serialized match
     assert entity.serialized == association.serialize()
     
     # check whether expiration_date match
     issued = datetime.datetime.fromtimestamp(association.issued)
     lifetime = datetime.timedelta(0, association.lifetime)        
     expiration_date = issued + lifetime
     
     assert entity.expiration_date == expiration_date
     
     # check whether the original and deserialized associations match
     assert association == Association.deserialize(entity.serialized)
예제 #18
0
    def getAssociation(self, server_url, handle=None):
        q = (OpenIDAssociationData
            .all()
            .filter('idp_server_url =', server_url)
            .order('-issued'))
        
        if handle:
            q.filter('handle', handle)
        
        results = q.fetch(1)
        if not results:
            return None
        
        r = results[0]

        association = Association(r.handle, 
                                  r.secret, 
                                  r.issued, 
                                  r.lifetime, 
                                  r.assoc_type)
    
        if association.getExpiresIn(self.current_timestamp()) > 0:
            return association
        else:
            return None
예제 #19
0
 def getAssociation(self, server_url, handle=None):
     if self.log_debug:
         log.debug("Association requested for server_url: %s, with handle: %s",
                   server_url, handle)
     if server_url.find('://') == -1:
         raise ValueError('Bad server URL: %r' % server_url)
     if handle is None:
         associations = self.associations.find({
             "server_url": server_url
         })
         if associations.count():
             associations = [Association.deserialize(a['association'])
                             for a in associations]
             # Now use the one that was issued most recently
             associations.sort(cmp=lambda x, y: cmp(x.issued, y.issued))
             log.debug("Most recent is %s", associations[-1].handle)
             return associations[-1]
     else:
         association = self.associations.find_one({
             "_id": hash((server_url, handle)),
             "server_url": server_url,
             "handle": handle
         })
         if association:
             return Association.deserialize(association['association'])
예제 #20
0
    def getAssociation(self, server_url, handle=None):
        assocs = []
        if handle is not None:
            assocs = Association.objects.filter(
                server_url=server_url,
                handle=handle,
            )
        else:
            assocs = Association.objects.filter(server_url=server_url)
        if not assocs:
            return None
        associations = []
        expired = []
        for assoc in assocs:
            association = OIDAssociation(
                assoc.handle,
                base64.decodestring(assoc.secret),
                assoc.issued,
                assoc.lifetime,
                assoc.assoc_type,
            )
            if association.getExpiresIn() == 0:
                expired.append(assoc)
            else:
                associations.append((association.issued, association))

        for assoc in expired:
            assoc.delete()
        if not associations:
            return None
        associations.sort()
        return associations[-1][1]
예제 #21
0
    def getAssociation(self, server_url, handle=None):
        stored_assocs = OpenIDStore.objects.filter(server_url=server_url)
        if handle:
            stored_assocs = stored_assocs.filter(handle=handle)

        stored_assocs.order_by('-issued')

        if stored_assocs.count() == 0:
            return None

        return_val = None

        for stored_assoc in stored_assocs:
            assoc = OIDAssociation(
                stored_assoc.handle,
                base64.decodestring(stored_assoc.secret.encode('utf-8')),
                stored_assoc.issued, stored_assoc.lifetime,
                stored_assoc.assoc_type)
            # See:
            # necaris/python3-openid@1abb155c8fc7b508241cbe9d2cae24f18e4a379b
            if hasattr(assoc, 'getExpiresIn'):
                expires_in = assoc.getExpiresIn()
            else:
                expires_in = assoc.expiresIn
            if expires_in == 0:
                stored_assoc.delete()
            else:
                if return_val is None:
                    return_val = assoc

        return return_val
예제 #22
0
파일: samadhi.py 프로젝트: ccoss/fas
 def getAssociation(self, server_url, handle=None):
     results = SamadhiAssociation.get(server_url, handle)
     for a in results:
         assoc = OpenIDAssociation(a.handle, a.secret, a.issued, a.lifetime,
                                   a.assoc_type)
         if assoc.getExpiresIn() == 0:
             SamadhiAssociation.remove(server_url, assoc.handle)
         else:
             return assoc
     return None
예제 #23
0
 def getAssociation(self, server_url, handle=None):
     q = OpenIDAssociation.query.filter_by(server_url=server_url)
     if handle is not None:
         q = q.filter_by(handle=handle)
     result_assoc = None
     for item in q.all():
         assoc = Association(item.handle, item.secret.decode("base64"), item.issued, item.lifetime, item.assoc_type)
         if assoc.getExpiresIn() <= 0:
             self.removeAssociation(server_url, assoc.handle)
         else:
             result_assoc = assoc
     return result_assoc
예제 #24
0
 def getAssociation(self, server_url, handle=None):
     q = OpenIDAssociation.query.filter_by(server_url=server_url)
     if handle is not None:
         q = q.filter_by(handle=handle)
     result_assoc = None
     for item in q.all():
         assoc = Association(item.handle, item.secret.decode('base64'),
                             item.issued, item.lifetime, item.assoc_type)
         if assoc.getExpiresIn() <= 0:
             self.removeAssociation(server_url, assoc.handle)
         else:
             result_assoc = assoc
     return result_assoc
예제 #25
0
파일: samadhi.py 프로젝트: Affix/fas
 def getAssociation(self, server_url, handle=None):
     results = SamadhiAssociation.get(server_url, handle)
     for a in results:
         assoc = OpenIDAssociation(a.handle,
                                   a.secret,
                                   a.issued,
                                   a.lifetime,
                                   a.assoc_type)
         if assoc.getExpiresIn() == 0:
             SamadhiAssociation.remove(server_url, assoc.handle)
         else:
             return assoc
     return None
    def test_getAssociation_no_handle(self):
        timestamp = int(time.time())
        self.store.storeAssociation(
            'server-url',
            Association('handle1', 'secret', timestamp, 600, 'HMAC-SHA1'))
        self.store.storeAssociation(
            'server-url',
            Association('handle2', 'secret', timestamp + 1, 600, 'HMAC-SHA1'))

        # The most recent handle is returned.
        assoc = self.store.getAssociation('server-url', None)
        self.assertNotEqual(assoc, None)
        self.assertEqual(assoc.handle, 'handle2')
    def test_cleanupAssociations(self):
        timestamp = int(time.time()) - 100
        self.store.storeAssociation(
            'server-url',
            Association('handle1', 'secret', timestamp, 50, 'HMAC-SHA1'))
        self.store.storeAssociation(
            'server-url',
            Association('handle2', 'secret', timestamp, 200, 'HMAC-SHA1'))

        self.assertEqual(self.store.cleanupAssociations(), 1)

        # The second (non-expired) association is left behind.
        self.assertNotEqual(self.store.getAssociation('server-url', 'handle2'),
                            None)
예제 #28
0
 def getAssociation(self, server_url, handle=None):
     filter = openid_association.c.server_url == server_url
     if handle is not None:
         filter &= openid_association.c.handle == handle
     with self.connection() as con:
         result = con.execute(openid_association.select(filter))
         result_assoc = None
         for row in result.fetchall():
             assoc = Association(row.handle, row.secret.decode('base64'),
                                 row.issued, row.lifetime, row.assoc_type)
             if assoc.getExpiresIn() <= 0:
                 self.removeAssociation(server_url, assoc.handle)
             else:
                 result_assoc = assoc
         return result_assoc
예제 #29
0
 def getAssociation(self, server_url, handle=None):
     filter = openid_association.c.server_url == server_url
     if handle is not None:
         filter &= openid_association.c.handle == handle
     with self.connection() as con:
         result = con.execute(openid_association.select(filter))
         result_assoc = None
         for row in result.fetchall():
             assoc = Association(row.handle, row.secret.decode('base64'),
                                 row.issued, row.lifetime, row.assoc_type)
             if assoc.getExpiresIn() <= 0:
                 self.removeAssociation(server_url, assoc.handle)
             else:
                 result_assoc = assoc
         return result_assoc
예제 #30
0
  def getAssociation(self, server_url, handle=None):
    """
    This method returns an C{L{Association <openid.association.Association>}}
    object from storage that matches the server URL and, if specified, handle.
    It returns C{None} if no such association is found or if the matching
    association is expired.

    If no handle is specified, the store may return any association which
    matches the server URL. If multiple associations are valid, the
    recommended return value for this method is the one that will remain valid
    for the longest duration.
    """
    query = models.Association.all().filter('url', server_url)
    if handle:
      query.filter('handle', handle)

    results = query.fetch(1)
    assoc = None
    if len(results) > 0:
      assoc = xAssociation.deserialize(results[0].association)
      if assoc.getExpiresIn() <= 0:
        results[0].delete() #self.removeAssociation(server_url, handle)
        assoc = None
    
    return assoc
예제 #31
0
    def _allAssocs(self):
        all_associations = []

        association_filenames = [os.path.join(self.association_dir, f) for f in os.listdir(self.association_dir)]
        for association_filename in association_filenames:
            try:
                association_file = open(association_filename, 'rb')
            except IOError as why:
                if why.errno == ENOENT:
                    _LOGGER.exception("%s disappeared during %s._allAssocs",
                                      association_filename, self.__class__.__name__)
                else:
                    raise
            else:
                try:
                    assoc_s = association_file.read()
                finally:
                    association_file.close()

                # Remove expired or corrupted associations
                try:
                    association = Association.deserialize(assoc_s.decode('utf-8'))
                except ValueError:
                    _removeIfPresent(association_filename)
                else:
                    all_associations.append(
                        (association_filename, association))

        return all_associations
예제 #32
0
    def createAssociation(self, dumb=True, assoc_type='HMAC-SHA1'):
        """Make a new association.

        @param dumb: Is this association for a dumb-mode transaction?
        @type dumb: bool

        @param assoc_type: The type of association to create.  Currently
            there is only one type defined, C{HMAC-SHA1}.
        @type assoc_type: str

        @returns: the new association.
        @returntype: L{openid.association.Association}
        """
        secret = cryptutil.getBytes(20)
        uniq = oidutil.toBase64(cryptutil.getBytes(4))
        handle = '{%s}{%x}{%s}' % (assoc_type, int(time.time()), uniq)

        assoc = Association.fromExpiresIn(self.SECRET_LIFETIME, handle, secret,
                                          assoc_type)

        if dumb:
            key = self._dumb_key
        else:
            key = self._normal_key
        self.store.storeAssociation(key, assoc)
        return assoc
예제 #33
0
    def createAssociation(self, dumb=True, assoc_type='HMAC-SHA1'):
        """Make a new association.

        @param dumb: Is this association for a dumb-mode transaction?
        @type dumb: bool

        @param assoc_type: The type of association to create.  Currently
            there is only one type defined, C{HMAC-SHA1}.
        @type assoc_type: str

        @returns: the new association.
        @returntype: L{openid.association.Association}
        """
        secret = cryptutil.getBytes(20)
        uniq = oidutil.toBase64(cryptutil.getBytes(4))
        handle = '{%s}{%x}{%s}' % (assoc_type, int(time.time()), uniq)

        assoc = Association.fromExpiresIn(
            self.SECRET_LIFETIME, handle, secret, assoc_type)

        if dumb:
            key = self._dumb_key
        else:
            key = self._normal_key
        self.store.storeAssociation(key, assoc)
        return assoc
예제 #34
0
    def _getAssociation(self, filename):
        try:
            assoc_file = open(filename, 'rb')
        except IOError as why:
            if why.errno == ENOENT:
                # No association exists for that URL and handle
                return None
            else:
                raise

        try:
            assoc_s = assoc_file.read()
        finally:
            assoc_file.close()

        try:
            association = Association.deserialize(assoc_s)
        except ValueError:
            _removeIfPresent(filename)
            return None

        # Clean up expired associations
        if association.expiresIn == 0:
            _removeIfPresent(filename)
            return None
        else:
            return association
예제 #35
0
    def _allAssocs(self):
        all_associations = []

        association_filenames = [
            os.path.join(self.association_dir, filename)
            for filename in os.listdir(self.association_dir)
        ]
        for association_filename in association_filenames:
            try:
                association_file = open(association_filename, 'rb')
            except IOError as why:
                if why.errno == ENOENT:
                    logging.exception("%s disappeared during %s._allAssocs" % (
                        association_filename, self.__class__.__name__))
                else:
                    raise
            else:
                try:
                    assoc_s = association_file.read()
                finally:
                    association_file.close()

                # Remove expired or corrupted associations
                try:
                    association = Association.deserialize(assoc_s)
                except ValueError:
                    _removeIfPresent(association_filename)
                else:
                    all_associations.append(
                        (association_filename, association))

        return all_associations
예제 #36
0
    def _getAssociation(self, filename):
        try:
            assoc_file = open(filename, 'rb')
        except IOError as why:
            if why.errno == ENOENT:
                # No association exists for that URL and handle
                return None
            else:
                raise
        else:
            try:
                assoc_s = assoc_file.read()
            finally:
                assoc_file.close()

            try:
                association = Association.deserialize(assoc_s)
            except ValueError:
                _removeIfPresent(filename)
                return None

        # Clean up expired associations
        if association.expiresIn == 0:
            _removeIfPresent(filename)
            return None
        else:
            return association
예제 #37
0
    def test_removeAssociation(self):

        # create and store some associations
        associations = []

        for i in range(3):
            assoc = Association(handle='handle-{}'.format(i),
                                secret='secret',
                                issued=int(time.time()),
                                lifetime=3600,
                                assoc_type='HMAC-SHA1')
            associations.append(assoc)
            NDBOpenIDStore.storeAssociation('server_url', assoc)

        # remove existing association
        removed = NDBOpenIDStore.removeAssociation('server_url', 'handle-1')

        # check whether the method returned True
        assert removed is True

        # check whether there is one less association in the datastore
        assert NDBOpenIDStore.query().count() == 2

        # check whether the right association was deleted
        assert NDBOpenIDStore.getAssociation('server_url', 'handle-1') is None

        # check whether the remaining are there
        assert NDBOpenIDStore.getAssociation('server_url',
                                             'handle-0') == associations[0]
        assert NDBOpenIDStore.getAssociation('server_url',
                                             'handle-2') == associations[2]
예제 #38
0
    def _allAssocs(self):
        all_associations = []

        association_filenames = map(
            lambda filename: os.path.join(self.association_dir, filename),
            os.listdir(self.association_dir))
        for association_filename in association_filenames:
            try:
                association_file = file(association_filename, 'rb')
            except IOError, why:
                if why.errno == ENOENT:
                    oidutil.log(
                        "%s disappeared during %s._allAssocs" %
                        (association_filename, self.__class__.__name__))
                else:
                    raise
            else:
                try:
                    assoc_s = association_file.read()
                finally:
                    association_file.close()

                # Remove expired or corrupted associations
                try:
                    association = Association.deserialize(assoc_s)
                except ValueError:
                    _removeIfPresent(association_filename)
                else:
                    all_associations.append(
                        (association_filename, association))
예제 #39
0
    def getAssociation(self, server_url, handle=None):
        """
    This method returns an C{L{Association <openid.association.Association>}}
    object from storage that matches the server URL and, if specified, handle.
    It returns C{None} if no such association is found or if the matching
    association is expired.

    If no handle is specified, the store may return any association which
    matches the server URL. If multiple associations are valid, the
    recommended return value for this method is the one that will remain valid
    for the longest duration.
    """
        query = models.Association.all().filter('url', server_url)
        if handle:
            query.filter('handle', handle)

        results = query.fetch(1)
        assoc = None
        if len(results) > 0:
            assoc = xAssociation.deserialize(results[0].association)
            if assoc.getExpiresIn() <= 0:
                results[0].delete(
                )  #self.removeAssociation(server_url, handle)
                assoc = None

        return assoc
    def test_storeAssociation_update_existing(self):
        self.store.storeAssociation(
            'server-url', Association('handle', 'secret', 42, 600,
                                      'HMAC-SHA1'))
        db_assoc = IMasterStore(self.store.Association).get(
            self.store.Association, (u'server-url', u'handle'))
        self.assertNotEqual(db_assoc, None)

        # Now update the association with new information.
        self.store.storeAssociation(
            'server-url',
            Association('handle', 'secret2', 420, 900, 'HMAC-SHA256'))
        self.assertEqual(db_assoc.secret, 'secret2')
        self.assertEqual(db_assoc.issued, 420)
        self.assertEqual(db_assoc.lifetime, 900)
        self.assertEqual(db_assoc.assoc_type, u'HMAC-SHA256')
예제 #41
0
    def getAssociation(self, server_url, handle=None):
        """
      Get an association from ndb
      """
        if handle == None:
            # find the newest association
            qry = OpenIDAssociation.query(
                OpenIDAssociation.server_url_hash == url_hash(
                    server_url)).order(-OpenIDAssociation.issued)
            results = qry.fetch(1)

            if results == None or len(results) == 0:
                return None

            gae_assoc = results[0]
            if gae_assoc == None:
                return None

            association = None

            try:
                association = Association.deserialize(
                    gae_assoc.association_bits)
            except:
                gae_assoc.key.delete()
                return None

            return association

        else:
            # find the specific association
            gae_assoc_key = ndb.Key(
                OpenIDAssociation,
                OpenIDAssociation.make_key_name(server_url, handle))
            gae_assoc = gae_assoc_key.get()

            if gae_assoc == None:
                return None

            try:
                association = Association.deserialize(
                    gae_assoc.association_bits)
            except:
                gae_assoc_key.delete()
                return None

            return association
예제 #42
0
 def cleanup_assocs(self):
     old_len = len(self.assocs)
     self.assocs = [
         a for a in self.assocs
         if Association.deserialize(a['value']).getExpiresIn() != 0
     ]
     new_len = len(self.assocs)
     return (old_len - new_len), new_len
예제 #43
0
    def getAssociation(self, server_url, handle=None):
        log_debug = self.log_debug

        if log_debug:
            log.debug(
                'Association requested for server_url: %s, with handle: %s',
                server_url, handle)

        if handle is None:
            # Retrieve all the keys for this server connection
            key_name = self.getAssociationFilename(server_url, '')
            cursor = 0
            assocs = set()
            while True:
                state = self._conn.scan(cursor, '%s*' % key_name,
                                        self._scan_count)
                cursor = state[0]
                for key in state[1]:
                    assocs.add(key)
                if cursor == 0:
                    break

            if not assocs:
                if log_debug:
                    log.debug('No association found for: %s', server_url)
                return None

            # Now use the one that was issued most recently
            associations = []
            for assoc in self._conn.mget(assocs):
                associations.append(Association.deserialize(assoc))
            associations.sort(cmp=lambda x, y: cmp(x.issued, y.issued))
            if log_debug:
                log.debug('getAssociation found, returns most recently issued')
            return associations[-1]
        else:
            key_name = self.getAssociationFilename(server_url, handle)
            association_s = self._conn.get(key_name)
            if association_s:
                if log_debug:
                    log.debug('getAssociation found, returning association')
                return Association.deserialize(association_s)
            else:
                if log_debug:
                    log.debug('No association found for getAssociation')
                return None
예제 #44
0
파일: openid.py 프로젝트: s-y/chukchi
 def getAssociation(self, server_url, handle=None):
     assoc = self._get(server_url, handle)
     if assoc:
         return Association(handle=assoc.handle,
                            secret=assoc.secret,
                            issued=assoc.issued,
                            lifetime=assoc.lifetime,
                            assoc_type=assoc.assoc_type)
예제 #45
0
 def getAssociation(self, server_url, handle=None):
     # Try to get association.
     assoc = self.session.get(self.ASSOCIATION_KEY)
     if assoc and assoc[0] == server_url:
         # If found deserialize and return it.
         self._log(logging.DEBUG, "SessionOpenIDStore: Association found.")
         return Association.deserialize(assoc[2].encode("latin-1"))
     else:
         self._log(logging.DEBUG, "SessionOpenIDStore: Association not found.")
 def test_removeAssociation(self):
     timestamp = int(time.time())
     self.store.storeAssociation(
         'server-url',
         Association('handle', 'secret', timestamp, 600, 'HMAC-SHA1'))
     self.assertEqual(self.store.removeAssociation('server-url', 'handle'),
                      True)
     self.assertEqual(self.store.getAssociation('server-url', 'handle'),
                      None)
    def getAssociation(self, server_url, handle=None):
        q = OpenIDAssociationData.all().filter("idp_server_url =", server_url).order("-issued")

        if handle:
            q.filter("handle", handle)

        results = q.fetch(1)
        if not results:
            return None

        r = results[0]

        association = Association(r.handle, r.secret, r.issued, r.lifetime, r.assoc_type)

        if association.getExpiresIn(self.current_timestamp()) > 0:
            return association
        else:
            return None
예제 #48
0
 def best_assoc(self):
     best = None
     for assoc in self.assocs:
         assoc = Association.deserialize(assoc['value'])
         if best is None or best.issued < assoc.issued:
             best = assoc
     if best:
         return best
     else:
         return None
예제 #49
0
 def best_assoc(self):
     best = None
     for assoc in self.assocs:
         assoc = Association.deserialize(assoc['value'])
         if best is None or best.issued < assoc.issued:
             best = assoc
     if best:
         return best
     else:
         return None
예제 #50
0
 def getAssociation(self, server_url, handle=None):
     # Try to get association.
     assoc = self.session.get('oia')
     
     if assoc and assoc[0] == server_url:
         # If found deserialize and return it.
         self._log(logging.DEBUG, 'SessionOpenIDStore: Association found.')
         return Association.deserialize(assoc[2])
     else:
         self._log(logging.DEBUG, 'SessionOpenIDStore: Association not found.')
예제 #51
0
 def getAssociation(self, server_url, handle=None):
     # Try to get association.
     assoc = self.session.get(self.ASSOCIATION_KEY)
     if assoc and assoc[0] == server_url:
         # If found deserialize and return it.
         self._log(logging.DEBUG, u'SessionOpenIDStore: Association found.')
         return Association.deserialize(assoc[2].encode('latin-1'))
     else:
         self._log(logging.DEBUG,
                   u'SessionOpenIDStore: Association not found.')
예제 #52
0
    def getAssociation(self, server_url, handle=None):
        kwargs = {'server_url': server_url}
        if handle:
            kwargs['handle'] = handle

        openid_assocs = []
        for assoc in Association.objects.filter(**kwargs).order_by('-issued'):
            openid_assoc = OpenidAssociation(assoc.handle,
                                             base64.decodestring(assoc.secret),
                                             assoc.issued,
                                             assoc.lifetime,
                                             assoc.assoc_type)

            if openid_assoc.getExpiresIn() > 0:
                openid_assocs.append(openid_assoc)
            else:
                assoc.delete()

        if openid_assocs:
            return openid_assocs[0]
예제 #53
0
파일: store.py 프로젝트: Arachnid/aeoid
 def getAssociation(self, server_url, handle=None):
   key1, key2 = self.getAssociationKeys(server_url, handle)
   if handle:
     results = memcache.get_multi([key1, key2], namespace=MEMCACHE_NAMESPACE)
   else:
     results = {key1: memcache.get(key1, namespace=MEMCACHE_NAMESPACE)}
   data = results.get(key2) or results.get(key1)
   if data:
     return OpenIDAssociation.deserialize(data)
   else:
     return None
    def handle(self, *args, **options):
        from social_auth.models import Association
        print('Clearing expired Association instances')
        timestamp = time.time() + Signatory.SECRET_LIFETIME
        associations = Association.objects.filter(issued__lt=timestamp)
        remove = []

        for assoc in associations:
            oid = OIDAssociation(assoc.handle,
                                 base64.decodestring(assoc.secret),
                                 assoc.issued,
                                 assoc.lifetime,
                                 assoc.assoc_type)
            if oid.getExpiresIn() == 0:
                remove.append(assoc.pk)
        if remove:
            print('Cleaning %s Associations' % len(remove))
            Association.filter(pk__in=remove).delete()
        else:
            print('No Associations to remove')
예제 #55
0
    def getAssociation(self, server_url, handle=None, remove=True):
        try:
            key=self.getAssociationKey(server_url, handle)
            assoc=Association.deserialize(self.associations[key])
        except KeyError:
            return None

        if remove and assoc.getExpiresIn()==0:
            self.removeAssociation(server_url, handle)
            return None

        return assoc
예제 #56
0
파일: _openid.py 프로젝트: rivan/w3fu
 def getAssociation(self, url, handle=None):
     params = {"url": url}
     if handle is None:
         cursor = self._conn.cursor().query(self.get_assocs_sql, params)
     else:
         params["handle"] = handle
         cursor = self._conn.cursor().query(self.get_assoc_sql, params)
     if not cursor.count:
         return None
     assocs = []
     for row in cursor:
         assoc = Association(row["handle"], row["secret"], row["issued"], row["lifetime"], row["type"])
         if assoc.getExpiresIn() == 0:
             self.removeAssociation(url, assoc.handle)
         else:
             assocs.append((assoc.issued, assoc))
     if assocs:
         assocs.sort()
         return assocs[-1][1]
     else:
         return None
예제 #57
0
파일: store.py 프로젝트: sweis/PseudoID
 def cleanupAssociations(self):
   query = datastore.Query('Association')
   results = query.Get(100)
   numDeleted = 0
   
   for result in results:
     assoc = Association.deserialize(result['association'])
     if assoc.getExpiresIn() == 0:
       numDeleted += 1
       datastore.Delete(result.key())
   
   return numDeleted
예제 #58
0
    def removeAssociation(self, server_url, handle):
        key=self.getAssociationKey(server_url, handle)
        try:
            assoc=Association.deserialize(self.associations[key])
            del self.associations[key]

            lst=self.handles[server_url]
            lst.remove(key)
            self.handles[server_url]=lst

            self.assoctimeline.remove((assoc.issued+assoc.lifetime, key))
            return True
        except KeyError:
            return False