Exemplo n.º 1
0
def saml2_main(global_config, **settings):
    """ This function returns a WSGI application.

        This is only useful for saml2 testing

    """
    settings = dict(settings)

    config = Configurator(settings=settings,
                          root_factory=RootFactory)

    factory = SessionFactory(settings)
    config.set_session_factory(factory)

    config.include('pyramid_jinja2')
    _userdb = UserDBWrapper(config.registry.settings['mongo_uri'])
    config.registry.settings['userdb'] = _userdb
    config.add_request_method(lambda x: x.registry.settings['userdb'], 'userdb', reify=True)
    mongodb = MongoDB(db_uri=settings['mongo_uri'])
    authninfodb = MongoDB(db_uri=settings['mongo_uri'], db_name='authninfo')
    config.registry.settings['mongodb'] = mongodb
    config.registry.settings['authninfodb'] = authninfodb
    config.registry.settings['db_conn'] = mongodb.get_connection
    config.registry.settings['db'] = mongodb.get_database('eduid_dashboard')
    config.set_request_property(lambda x: x.registry.settings['mongodb'].get_database('eduid_dashboard'), 'db', reify=True)

    saml2_includeme(config)

    config.scan(ignore=[re.compile('.*tests.*').search, '.testing'])
    return config.make_wsgi_app()
Exemplo n.º 2
0
class CacheMDB(object):

    _init_collections: dict = {}

    def __init__(self, mongo_dburi, mongo_dbname, mongo_collection, ttl, expiration_freq=60):
        self.conn = MongoDB(mongo_dburi)
        self.db = self.conn.get_database(mongo_dbname)
        self.collection = self.db[mongo_collection]
        self._expiration_freq = expiration_freq
        self._last_expire_at = None
        self._ttl = ttl
        self.ensure_indices(mongo_collection)

    def add_cache_item(self, identifier, data):
        date = datetime.fromtimestamp(time(), None)
        doc = {'identifier': identifier,
               'data': data,
               'created_at': date}
        self.collection.insert(doc)
        self.expire_cache_items()
        return True

    def get_cache_item(self, identifier):
        query = {'identifier': identifier}
        result = self.collection.find_one(query)
        if result is not None:
            return result['data']
        return result

    def get_cached_items_by_query(self, query):
        result = self.collection.find(query)
        return result

    def update_cache_item(self, identifier, data):
        date = datetime.fromtimestamp(time(), None)
        return self.collection.update({'identifier': identifier}, {'$set': {'data': data, 'updated_at': date}}, w=1,
                                      getLastError=True)

    def remove_cache_item(self, identifier):
        return self.collection.remove({'identifier': identifier}, w=1, getLastError=True)

    def expire_cache_items(self, force=False):
        ts = time() - self._ttl
        if not force and (self._last_expire_at is not None) and (self._last_expire_at > ts - self._expiration_freq):
            return False
        self._last_expire_at = ts
        date = datetime.fromtimestamp(ts, None)
        self.collection.remove({'created_at': {'$lt': date}}, w=1)
        return True

    def ensure_indices(self, collection):
        if collection not in self._init_collections:  # Only ensure indices once
            self._init_collections[collection] = 1
            self.db[collection].ensure_index('created_at', name='created_at_idx', unique=False)
            self.db[collection].ensure_index('identifier', name='identifier_idx', unique=True)
Exemplo n.º 3
0
    def __call__(self, f):
        if not self.enabled:
            return f

        def audit(*args, **kwargs):
            ret = f(*args, **kwargs)
            if not isclass(ret):  # we can't save class objects in mongodb
                date = datetime.utcnow()
                doc = {
                    'function': f.__name__,
                    'data': self._filter(f.__name__, ret, *args, **kwargs),
                    'created_at': date
                }
                self.collection.insert(doc)
            return ret

        if self.collection is None:
            conn = MongoDB(self.db_uri)
            db = conn.get_database(self.db_name)
            self.collection = db[self.collection_name]
        return audit
Exemplo n.º 4
0
def get_db(settings):
    mongodb = MongoDB(db_uri=settings['mongo_uri'])
    logger.warning("Using a raw MongoDB instance: {!r} (mongo_uri: {!r})".format(mongodb, settings['mongo_uri']))
    return mongodb.get_database()
Exemplo n.º 5
0
class CacheMDB():
    _init_collections = {}

    def __init__(self,
                 mongo_dburi,
                 mongo_dbname,
                 mongo_collection,
                 ttl,
                 expiration_freq=60):
        self.conn = MongoDB(mongo_dburi)
        self.db = self.conn.get_database(mongo_dbname)
        self.collection = self.db[mongo_collection]
        self._expiration_freq = expiration_freq
        self._last_expire_at = None
        self._ttl = ttl
        self.ensure_indices(mongo_collection)

    def add_cache_item(self, identifier, data):
        date = datetime.fromtimestamp(time(), None)
        doc = {'identifier': identifier, 'data': data, 'created_at': date}
        self.collection.insert(doc)
        self.expire_cache_items()
        return True

    def get_cache_item(self, identifier):
        query = {'identifier': identifier}
        result = self.collection.find_one(query)
        if result is not None:
            return result['data']
        return result

    def get_cached_items_by_query(self, query):
        result = self.collection.find(query)
        return result

    def update_cache_item(self, identifier, data):
        date = datetime.fromtimestamp(time(), None)
        return self.collection.update(
            {'identifier': identifier},
            {'$set': {
                'data': data,
                'updated_at': date
            }},
            w=1,
            getLastError=True)

    def remove_cache_item(self, identifier):
        return self.collection.remove({'identifier': identifier},
                                      w=1,
                                      getLastError=True)

    def expire_cache_items(self, force=False):
        ts = time() - self._ttl
        if not force and (self._last_expire_at > ts - self._expiration_freq):
            return False
        self._last_expire_at = ts
        date = datetime.fromtimestamp(ts, None)
        self.collection.remove({'created_at': {'$lt': date}}, w=1)
        return True

    def ensure_indices(self, collection):
        if collection not in self._init_collections:  # Only ensure indices once
            self._init_collections[collection] = 1
            self.db[collection].ensure_index('created_at',
                                             name='created_at_idx',
                                             unique=False)
            self.db[collection].ensure_index('identifier',
                                             name='identifier_idx',
                                             unique=True)
Exemplo n.º 6
0
class TransactionAudit(object):
    enabled = False

    def __init__(self,
                 db_uri,
                 db_name='eduid_queue',
                 collection_name='transaction_audit'):
        self._conn = None
        self.db_uri = db_uri
        self.db_name = db_name
        self.collection_name = collection_name
        self.collection = None

    def __call__(self, f):
        if not self.enabled:
            return f

        def audit(*args, **kwargs):
            ret = f(*args, **kwargs)
            if not isclass(ret):  # we can't save class objects in mongodb
                date = datetime.utcnow()
                doc = {
                    'function': f.__name__,
                    'data': self._filter(f.__name__, ret, *args, **kwargs),
                    'created_at': date,
                }
                self.collection.insert_one(doc)
            return ret

        if self._conn is None or not self._conn.is_healthy():
            self._conn = MongoDB(self.db_uri)
            db = self._conn.get_database(self.db_name)
            self.collection = db[self.collection_name]
        return audit

    @classmethod
    def enable(cls):
        cls.enabled = True

    @classmethod
    def disable(cls):
        cls.enabled = False

    @staticmethod
    def _filter(func, data, *args, **kwargs):
        if data is False:
            return data
        if func == '_get_navet_data':
            return {'identity_number': args[1]}
        elif func == 'send_message':
            return {
                'type': args[1],
                'recipient': args[4],
                'transaction_id': data,
                'audit_reference': args[2],
                'template': args[5],
            }
        elif func == 'sendmail':
            return {
                'type': 'mail',
                'recipient': args[1],
                'send_errors': data,
                'audit_reference': args[3]
            }
        elif func == 'sendsms':
            return {
                'type': 'sms',
                'recipient': args[1],
                'transaction_id': data,
                'audit_reference': args[3]
            }
        return data