예제 #1
0
 def __init__(self, app):
     for database in app.config['DATABASES']:
         # We need to have an active request to 'trick' set_database and work with the database we want
         with app.test_request_context('/{}/devices'.format(database)):
             print('Starting update process for database {}'.format(AccountDomain.get_requested_database()))
             app.auth._set_database(True)
             self.set_prefix()
             self.re_materialize_events()
             self.re_materialize_owners()
             print('Database {} successfully updated.'.format(AccountDomain.get_requested_database()))
예제 #2
0
 def __init__(self, app):
     for database in app.config['DATABASES']:
         # We need to have an active request to 'trick' set_database and work with the database we want
         with app.test_request_context('/{}/devices'.format(database)):
             print(('Starting update process for database {}'.format(
                 AccountDomain.get_requested_database())))
             app.auth._set_database(True)
             self.materialize_component_info()
             print(('Database {} successfully updated.'.format(
                 AccountDomain.get_requested_database())))
예제 #3
0
파일: migrate.py 프로젝트: eReuse/DeviceHub
 def clean_device(device: dict):
     """Removes values that are not supposed to be sent, like materialized or readonly ones."""
     schema = current_app.config['DOMAIN'][Naming.resource(device['@type'])]['schema']
     _id = device['_id']
     for field in copy.copy(device):
         if '_' in field or not {'materialized', 'readonly'}.isdisjoint(set(schema[field].keys())):
             del device[field]
     device['url'] = DeviceDomain.url_agent_for(AccountDomain.get_requested_database(), _id)
예제 #4
0
 def clean_device(device: dict):
     """Removes values that are not supposed to be sent, like materialized or readonly ones."""
     schema = current_app.config['DOMAIN'][Naming.resource(
         device['@type'])]['schema']
     _id = device['_id']
     for field in copy.copy(device):
         if '_' in field or not {'materialized', 'readonly'}.isdisjoint(
                 set(schema[field].keys())):
             del device[field]
     device['url'] = DeviceDomain.url_agent_for(
         AccountDomain.get_requested_database(), _id)
예제 #5
0
    def generate_returned_same_as(self):
        """
        Populates self.returned_same_as with a dict where the URL of devices in the caller agent as keys and a copy of
        'sameAs' in this agent.

        This value will be returned to the caller agent (see
        :py:func:`ereuse_devicehub.resources.event.device.migrate.hooks.return_same_as`) which can use it to update
        its 'sameAs' values with new references.
        """
        for device, url in zip([self.device] + self.components, self.urls):
            device = DeviceDomain.get_one(device['_id'])
            same_as = set(device['sameAs'])
            same_as.remove(url)
            same_as.add(
                DeviceDomain.url_agent_for(
                    AccountDomain.get_requested_database(), device['_id']))
            self.returned_same_as[url] = list(same_as)
예제 #6
0
파일: hooks.py 프로젝트: eReuse/DeviceHub
def _add_or_get_inactive_account_id(event, field_name):
    """
    We need to execute after insert and insert_resource.
    """
    if field_name in event and type(event[field_name]) is dict:
        try:
            # We look for just accounts that share our database
            _id = AccountDomain.get_one(
                {
                    "email": event[field_name]["email"]
                    # 'databases': {'$in': AccountDomain.actual['databases']} todo review this
                }
            )["_id"]
        except UserNotFound:
            event[field_name]["databases"] = [AccountDomain.get_requested_database()]
            event[field_name]["active"] = False
            event[field_name]["@type"] = "Account"
            _id = execute_post_internal("accounts", event[field_name], True)["_id"]
        event[field_name] = _id
예제 #7
0
def _add_or_get_inactive_account_id(event, field_name):
    """
    We need to execute after insert and insert_resource.
    """
    if field_name in event and type(event[field_name]) is dict:
        try:
            # We look for just accounts that share our database
            _id = AccountDomain.get_one({
                'email': event[field_name]['email']
                # 'databases': {'$in': AccountDomain.actual['databases']} todo review this
            })['_id']
        except UserNotFound:
            event[field_name]['databases'] = [
                AccountDomain.get_requested_database()
            ]
            event[field_name]['active'] = False
            event[field_name]['@type'] = 'Account'
            _id = execute_post_internal('accounts', event[field_name],
                                        True)['_id']
        event[field_name] = _id
예제 #8
0
def submit_migrate(migrates: dict):
    """
    Sends a Migrate event to the other DeviceHub.
    Note as the other DeviceHub requires the url of this event,
    this method needs to be executed after reaching the Database.
    """
    for migrate in migrates:
        if 'to' in migrate:
            auth = AgentAuth(migrate['to']['baseUrl'])
            submitter = MigrateSubmitter(current_app, MigrateTranslator(current_app.config), auth=auth)
            try:
                response, *_ = submitter.submit(migrate, AccountDomain.get_requested_database())
                migrate['to']['url'] = migrate['to']['baseUrl'] + response['_links']['self']['href']
                _update_same_as(response['returnedSameAs'])
            except InnerRequestError as e:
                execute_delete(Migrate.resource_name, migrate['_id'])
                raise e
            else:
                _remove_devices_from_places(migrate)
                update = {'$set': {'to.url': migrate['to']['url'], 'devices': [_id for _id in migrate['devices']]}}
                DeviceEventDomain.update_one_raw(migrate['_id'], update)
예제 #9
0
파일: hooks.py 프로젝트: eReuse/DeviceHub
def submit_migrate(migrates: dict):
    """
    Sends a Migrate event to the other DeviceHub.
    Note as the other DeviceHub requires the url of this event,
    this method needs to be executed after reaching the Database.
    """
    for migrate in migrates:
        if 'to' in migrate:
            auth = AgentAuth(migrate['to']['baseUrl'])
            submitter = MigrateSubmitter(current_app, MigrateTranslator(current_app.config), auth=auth)
            try:
                response, *_ = submitter.submit(migrate, AccountDomain.get_requested_database())
                migrate['to']['url'] = migrate['to']['baseUrl'] + response['_links']['self']['href']
                _update_same_as(response['returnedSameAs'])
            except InnerRequestError as e:
                execute_delete(Migrate.resource_name, migrate['_id'])
                raise e
            else:
                _remove_devices_from_places(migrate)
                update = {'$set': {'to.url': migrate['to']['url'], 'devices': [_id for _id in migrate['devices']]}}
                DeviceEventDomain.update_one_raw(migrate['_id'], update)
예제 #10
0
 def _set_database(self, force: bool = False):
     """
     Sets the actual database according of the value in the URL.
     :param force: Sets the database even if the user has no access to it
     :raises NotADatabase: When the URL is malformed or doesn't contain an existing database
     :raises UnauthorizedToUseDatabase: If force is true this won't raise
     """
     try:
         requested_database = AccountDomain.get_requested_database()
     except NotADatabase as e:
         try:
             if e.body['requested_path'] not in current_app.config['RESOURCES_NOT_USING_DATABASES'] \
                     and not current_app.config['DOMAIN'][e.body['requested_path']]['use_default_database']:
                 raise e
         except KeyError:
             raise e
     else:
         if force or (requested_database in AccountDomain.actual['databases']
                      or AccountDomain.actual['role'] == Role.SUPERUSER):
             self.set_mongo_prefix(requested_database.replace("-", "").upper())
         else:
             raise UnauthorizedToUseDatabase()