def user_acquired_datasets(self):

        db.init_db(model)

        c = plugins.toolkit.c
        context = {
            'model': model,
            'session': model.Session,
            'user': plugins.toolkit.c.user,
        }

        # Get user information
        try:
            c.user_dict = plugins.toolkit.get_action('user_show')(context.copy(), {'user_obj': c.userobj})
            c.user_dict['acquired_datasets'] = []
        except plugins.toolkit.ObjectNotFound:
            plugins.toolkit.abort(404, _('User not found'))
        except plugins.toolkit.NotAuthorized:
            plugins.toolkit.abort(401, _('Not authorized to see this page'))

        # Get the datasets acquired by the user
        query = db.AllowedUser.get(user_name=context['user'])

        # Get the datasets
        for dataset in query:
            try:
                dataset_dict = plugins.toolkit.get_action('package_show')(context.copy(), {'id': dataset.package_id})
                # Only packages with state == 'active' can be shown
                if dataset_dict.get('state', None) == 'active':
                    c.user_dict['acquired_datasets'].append(dataset_dict)
            except Exception:
                continue

        return plugins.toolkit.render('user/dashboard_acquired.html')
Exemplo n.º 2
0
    def _after_create_pkg(self, context, pkg_dict):
        session = context['session']
        update_cache = False

        db.init_db(context['model'])

        # Get the users and the package ID
        if constants.ALLOWED_USERS in pkg_dict:

            allowed_users = pkg_dict[constants.ALLOWED_USERS]
            package_id = pkg_dict['id']

            # Get current users
            users = db.AllowedUser.get(package_id=package_id)

            # Delete users and save the list of current users
            current_users = []
            for user in users:
                current_users.append(user.user_name)
                if user.user_name not in allowed_users:
                    session.delete(user)
                    update_cache = True

            # Add non existing users
            for user_name in allowed_users:
                if user_name not in current_users:
                    out = db.AllowedUser()
                    out.package_id = package_id
                    out.user_name = user_name
                    out.save()
                    session.add(out)
                    update_cache = True

            session.commit()

            # The cache should be updated. Otherwise, the system may return
            # outdated information in future requests
            if update_cache:
                new_pkg_dict = tk.get_action('package_show')(
                    {
                        'model': context['model'],
                        'ignore_auth': True,
                        'validate': False,
                        'use_cache': False
                    }, {
                        'id': package_id
                    })

                # Prevent acquired datasets jumping to the first position
                revision = tk.get_action('revision_show')(
                    {
                        'ignore_auth': True
                    }, {
                        'id': new_pkg_dict['revision_id']
                    })
                new_pkg_dict['metadata_modified'] = revision.get(
                    'timestamp', '')
                self.indexer.update_dict(new_pkg_dict)

        return pkg_dict
Exemplo n.º 3
0
def acquisitions_list(context, data_dict):
    '''
    API to retrieve the list of datasets that have been acquired by a certain user

    :parameter user: The user whose acquired dataset you want to retrieve. This parameter
        is optional. If you don't include this identifier, the system will use the one
        of the user that is performing the request
    :type user: string

    :return: The list of datarequest that has been acquired by the specified user
    :rtype: list
    '''

    if data_dict is None:
        data_dict = {}

    if 'user' not in data_dict and 'user' in context:
        data_dict['user'] = context['user']

    plugins.toolkit.check_access(constants.ACQUISITIONS_LIST, context.copy(),
                                 data_dict)

    # Init db
    db.init_db(context['model'])

    # Init the result array
    result = []

    # Check that the user exists
    try:
        plugins.toolkit.get_validator('user_name_exists')(data_dict['user'],
                                                          context.copy())
    except Exception:
        raise plugins.toolkit.ValidationError('User %s does not exist' %
                                              data_dict['user'])

    # Get the datasets acquired by the user
    query = db.AllowedUser.get(user_name=data_dict['user'])

    # Get the datasets
    for dataset in query:
        try:
            dataset_show_func = 'package_show'
            func_data_dict = {'id': dataset.package_id}
            internal_context = context.copy()

            # Check that the the dataset can be accessed and get its data
            # FIX: If the check_access function is not called, an exception is risen.
            plugins.toolkit.check_access(dataset_show_func, internal_context,
                                         func_data_dict)
            dataset_dict = plugins.toolkit.get_action(dataset_show_func)(
                internal_context, func_data_dict)

            # Only packages with state == 'active' can be shown
            if dataset_dict.get('state', None) == 'active':
                result.append(dataset_dict)
        except Exception:
            pass

    return result
Exemplo n.º 4
0
    def test_initdb_not_initialized(self):

        # Call the function
        model = MagicMock()
        db.init_db(model)

        # Assert that table method has been called
        db.sa.Table.assert_called_once()
        model.meta.mapper.assert_called_once()
def get_allowed_users(key, data, errors, context):
    pkg_id = data[('id',)]

    db.init_db(context['model'])

    users = db.AllowedUser.get(package_id=pkg_id)

    for i, user in enumerate(users):
        data[(key[0], i)] = user.user_name
Exemplo n.º 6
0
    def test_initdb_not_initialized(self):

        # Call the function
        model = MagicMock()
        db.init_db(model)

        # Assert that table method has been called
        db.sa.Table.assert_called_once()
        model.meta.mapper.assert_called_once()
Exemplo n.º 7
0
def resource_show(context, data_dict):

    user = context.get('user')
    user_obj = context.get('auth_user_obj')
    resource = logic_auth.get_resource_object(context, data_dict)
    # check authentication against package
    package_dict = {'id': resource.package_id}
    package = logic_auth.get_package_object(context, package_dict)
    if not package:
        raise tk.ObjectNotFound(
            _('No package found for this resource, cannot check auth.'))

    if package and user_obj and package.creator_user_id == user_obj.id:
        return {'success': True}

    # active packages can only be seen by its owners
    if package.state == 'active':

        # anyone can see a public package
        if not package.private:
            return {'success': True}

        # if the user has rights to read in the organization or in the group
        if package.owner_org:
            authorized = authz.has_user_permission_for_group_or_org(
                package.owner_org, user, 'read')
        else:
            authorized = False

        if not authorized:
            # Init the model
            db.init_db(context['model'])

            # Branch not executed if the database return an empty list
            if db.AllowedUser.get(package_id=package.id, user_name=user):
                authorized = True

        if not authorized:
            return {
                'success':
                False,
                'msg':
                _('User %s not authorized to read resource %s') %
                (user, resource.id)
            }

        else:
            return {'success': True}

    else:
        return {
            'success':
            False,
            'msg':
            _('User %s not authorized to read resource %s') %
            (user, resource.id)
        }
Exemplo n.º 8
0
def get_allowed_users(key, data, errors, context):
    pkg_id = data[('id', )]

    db.init_db(context['model'])

    users = db.AllowedUser.get(package_id=pkg_id)

    for i, user in enumerate(users):
        data[(key[0], i)] = user.user_name
Exemplo n.º 9
0
    def test_initdb_initialized(self):
        db.AllowedUser = MagicMock()

        # Call the function
        model = MagicMock()
        db.init_db(model)

        # Assert that table method has been called
        self.assertEquals(0, db.sa.Table.call_count)
        self.assertEquals(0, model.meta.mapper.call_count)
Exemplo n.º 10
0
    def test_initdb_initialized(self):
        db.AllowedUser = MagicMock()

        # Call the function
        model = MagicMock()
        db.init_db(model)

        # Assert that table method has been called
        self.assertEquals(0, db.sa.Table.call_count)
        self.assertEquals(0, model.meta.mapper.call_count)
Exemplo n.º 11
0
def is_dataset_acquired(pkg_dict):

    db.init_db(model)

    if tk.c.user:
        return len(
            db.AllowedUser.get(package_id=pkg_dict['id'],
                               user_name=tk.c.user)) > 0
    else:
        return False
Exemplo n.º 12
0
def acquisitions_list(context, data_dict):
    '''
    API to retrieve the list of datasets that have been acquired by a certain user

    :parameter user: The user whose acquired dataset you want to retrieve. This parameter
        is optional. If you don't include this identifier, the system will use the one
        of the user that is performing the request
    :type user: string

    :return: The list of datarequest that has been acquired by the specified user
    :rtype: list
    '''

    if data_dict is None:
        data_dict = {}

    if 'user' not in data_dict and 'user' in context:
        data_dict['user'] = context['user']

    plugins.toolkit.check_access(constants.ACQUISITIONS_LIST, context.copy(), data_dict)

    # Init db
    db.init_db(context['model'])

    # Init the result array
    result = []

    # Check that the user exists
    try:
        plugins.toolkit.get_validator('user_name_exists')(data_dict['user'], context.copy())
    except Exception:
        raise plugins.toolkit.ValidationError('User %s does not exist' % data_dict['user'])

    # Get the datasets acquired by the user
    query = db.AllowedUser.get(user_name=data_dict['user'])

    # Get the datasets
    for dataset in query:
        try:
            dataset_show_func = 'package_show'
            func_data_dict = {'id': dataset.package_id}
            internal_context = context.copy()

            # Check that the the dataset can be accessed and get its data
            # FIX: If the check_access function is not called, an exception is risen.
            plugins.toolkit.check_access(dataset_show_func, internal_context, func_data_dict)
            dataset_dict = plugins.toolkit.get_action(dataset_show_func)(internal_context, func_data_dict)

            # Only packages with state == 'active' can be shown
            if dataset_dict.get('state', None) == 'active':
                result.append(dataset_dict)
        except Exception:
            pass

    return result
Exemplo n.º 13
0
def package_show(context, data_dict):
    user = context.get('user')
    user_obj = context.get('auth_user_obj')
    package = logic_auth.get_package_object(context, data_dict)

    # datasets can be read by its creator
    if package and user_obj and package.creator_user_id == user_obj.id:
        return {'success': True}

    # Not active packages can only be seen by its owners
    if package.state == 'active':
        # anyone can see a public package
        if package.private:

            acquired = False

            if package.owner_org:
                acquired = authz.has_user_permission_for_group_or_org(
                    package.owner_org, user, 'read')

            if not acquired:
                # Init the model
                db.init_db(context['model'])

                # Branch not executed if the database return an empty list
                if db.AllowedUser.get(package_id=package.id, user_name=user):
                    acquired = True

            if not acquired:

                # Show a flash message with the URL to acquire the dataset
                # This message only can be shown when the user tries to access the dataset via its URL (/dataset/...)
                # The message cannot be displayed in other pages that uses the package_show function such as
                # the user profile page

                if hasattr(package, 'extras') and 'acquire_url' in package.extras and request.path.startswith(
                        '/dataset/') \
                        and package.extras['acquire_url'] != '':
                    helpers.flash_notice(_(
                        'This private dataset can be acquired. To do so, please click '
                        + '<a target="_blank" href="%s">here</a>') %
                                         package.extras['acquire_url'],
                                         allow_html=True)

        return {'success': True}
    else:
        return {
            'success':
            False,
            'msg':
            _('User %s not authorized to read package %s') % (user, package.id)
        }
    def clearBBDD(self):
        # Clean Solr
        search_index.clear_index()

        # Clean the database
        model.repo.rebuild_db()

        # Delete previous users
        db.init_db(model)
        users = db.AllowedUser.get()
        for user in users:
            model.Session.delete(user)
        model.Session.commit()
    def clearBBDD(self):
        # Clean Solr
        search_index.clear_index()

        # Clean the database
        model.repo.rebuild_db()

        # Delete previous users
        db.init_db(model)
        users = db.AllowedUser.get()
        for user in users:
            model.Session.delete(user)
        model.Session.commit()
Exemplo n.º 16
0
    def after_create(self, context, pkg_dict):
        session = context['session']
        update_cache = False

        db.init_db(context['model'])

        # Get the users and the package ID
        if constants.ALLOWED_USERS in pkg_dict:

            allowed_users = pkg_dict[constants.ALLOWED_USERS]
            package_id = pkg_dict['id']

            # Get current users
            users = db.AllowedUser.get(package_id=package_id)

            # Delete users and save the list of current users
            current_users = []
            for user in users:
                current_users.append(user.user_name)
                if user.user_name not in allowed_users:
                    session.delete(user)
                    update_cache = True

            # Add non existing users
            for user_name in allowed_users:
                if user_name not in current_users:
                    out = db.AllowedUser()
                    out.package_id = package_id
                    out.user_name = user_name
                    out.save()
                    session.add(out)
                    update_cache = True

            session.commit()

            # The cache should be updated. Otherwise, the system may return
            # outdated information in future requests
            if update_cache:
                new_pkg_dict = tk.get_action('package_show')(
                    {'model': context['model'],
                     'ignore_auth': True,
                     'validate': False,
                     'use_cache': False},
                    {'id': package_id})

                # Prevent acquired datasets jumping to the first position
                revision = tk.get_action('revision_show')({'ignore_auth': True}, {'id': new_pkg_dict['revision_id']})
                new_pkg_dict['metadata_modified'] = revision.get('timestamp', '')
                self.indexer.update_dict(new_pkg_dict)

        return pkg_dict
Exemplo n.º 17
0
    def _after_delete_pkg(self, context, pkg_dict):
        session = context['session']
        package_id = pkg_dict['id']

        # Get current users
        db.init_db(context['model'])
        users = db.AllowedUser.get(package_id=package_id)

        # Delete all the users
        for user in users:
            session.delete(user)
        session.commit()

        return pkg_dict
Exemplo n.º 18
0
    def after_delete(self, context, pkg_dict):
        session = context['session']
        package_id = pkg_dict['id']

        # Get current users
        db.init_db(context['model'])
        users = db.AllowedUser.get(package_id=package_id)

        # Delete all the users
        for user in users:
            session.delete(user)
        session.commit()

        return pkg_dict
Exemplo n.º 19
0
def package_show(context, data_dict):
    user = context.get('user')
    user_obj = context.get('auth_user_obj')
    package = logic_auth.get_package_object(context, data_dict)

    # datasets can be read by its creator
    if package and user_obj and package.creator_user_id == user_obj.id:
        return {'success': True}

    # Not active packages can only be seen by its owners
    if package.state == 'active':
        # anyone can see a public package
        if package.private:

            acquired = False

            if package.owner_org:
                acquired = authz.has_user_permission_for_group_or_org(
                    package.owner_org, user, 'read')

            if not acquired:
                # Init the model
                db.init_db(context['model'])

                # Branch not executed if the database return an empty list
                if db.AllowedUser.get(package_id=package.id, user_name=user):
                    acquired = True

            if not acquired:

                # Show a flash message with the URL to acquire the dataset
                # This message only can be shown when the user tries to access the dataset via its URL (/dataset/...)
                # The message cannot be displayed in other pages that uses the package_show function such as
                # the user profile page

                if hasattr(package, 'extras') and 'acquire_url' in package.extras and request.path.startswith(
                        '/dataset/') \
                        and package.extras['acquire_url'] != '':
                    helpers.flash_notice(_('This private dataset can be acquired. To do so, please click ' +
                                           '<a target="_blank" href="%s">here</a>') % package.extras['acquire_url'],
                                         allow_html=True)

        return {'success': True}
    else:
        return {'success': False, 'msg': _('User %s not authorized to read package %s') % (user, package.id)}
Exemplo n.º 20
0
def resource_show(context, data_dict):

    user = context.get('user')
    user_obj = context.get('auth_user_obj')
    resource = logic_auth.get_resource_object(context, data_dict)
    # check authentication against package
    package_dict = {'id': resource.package_id}
    package = logic_auth.get_package_object(context, package_dict)
    if not package:
        raise tk.ObjectNotFound(_('No package found for this resource, cannot check auth.'))

    if package and user_obj and package.creator_user_id == user_obj.id:
        return {'success': True}

    # active packages can only be seen by its owners
    if package.state == 'active':

        # anyone can see a public package
        if not package.private:
            return {'success': True}

        # if the user has rights to read in the organization or in the group
        if package.owner_org:
            authorized = authz.has_user_permission_for_group_or_org(
                package.owner_org, user, 'read')
        else:
            authorized = False

        if not authorized:
            # Init the model
            db.init_db(context['model'])

            # Branch not executed if the database return an empty list
            if db.AllowedUser.get(package_id=package.id, user_name=user):
                authorized = True

        if not authorized:
            return {'success': False, 'msg': _('User %s not authorized to read resource %s') % (user, resource.id)}

        else:
            return {'success': True}

    else:
        return {'success': False, 'msg': _('User %s not authorized to read resource %s') % (user, resource.id)}