Exemple #1
0
def resource_create(context: Context, data_dict: DataDict) -> AuthResult:
    model = context['model']
    user = context.get('user')

    package_id = data_dict.get('package_id')
    if not package_id and data_dict.get('id'):
        # This can happen when auth is deferred, eg from `resource_view_create`
        resource = logic_auth.get_resource_object(context, data_dict)
        package_id = resource.package_id

    if not package_id:
        raise logic.NotFound(_('No dataset id provided, cannot check auth.'))

    # check authentication against package
    pkg = model.Package.get(package_id)
    if not pkg:
        raise logic.NotFound(
            _('No package found for this resource, cannot check auth.'))

    pkg_dict = {'id': pkg.id}
    authorized = authz.is_authorized('package_update', context,
                                     pkg_dict).get('success')

    if not authorized:
        return {
            'success':
            False,
            'msg':
            _('User %s not authorized to create resources on dataset %s') %
            (str(user), package_id)
        }
    else:
        return {'success': True}
Exemple #2
0
def term_translation_update_many(
        context: Context, data_dict: DataDict) -> ActionResult.TermTranslationUpdateMany:
    '''Create or update many term translations at once.

    :param data: the term translation dictionaries to create or update,
        for the format of term translation dictionaries see
        :py:func:`~term_translation_update`
    :type data: list of dictionaries

    :returns: a dictionary with key ``'success'`` whose value is a string
        stating how many term translations were updated
    :rtype: string

    '''
    model = context['model']

    if not (data_dict.get('data') and isinstance(data_dict.get('data'), list)):
        raise ValidationError(
            {'error': 'term_translation_update_many needs to have a '
                      'list of dicts in field data'}
        )

    context['defer_commit'] = True

    action = _get_action('term_translation_update')
    num = 0
    for num, row in enumerate(data_dict['data']):
        action(context, row)

    model.Session.commit()

    return {'success': '%s rows updated' % (num + 1)}
Exemple #3
0
def package_owner_org_update(
        context: Context,
        data_dict: DataDict) -> ActionResult.PackageOwnerOrgUpdate:
    '''Update the owning organization of a dataset

    :param id: the name or id of the dataset to update
    :type id: string

    :param organization_id: the name or id of the owning organization
    :type organization_id: string
    '''
    model = context['model']
    name_or_id = data_dict.get('id', '')
    organization_id = data_dict.get('organization_id')

    _check_access('package_owner_org_update', context, data_dict)

    pkg = model.Package.get(name_or_id)
    if pkg is None:
        raise NotFound(_('Package was not found.'))
    if organization_id:
        org = model.Group.get(organization_id)
        if org is None or not org.is_organization:
            raise NotFound(_('Organization was not found.'))

        # FIXME check we are in that org
        pkg.owner_org = org.id
    else:
        org = None
        pkg.owner_org = None

    members = model.Session.query(model.Member) \
        .filter(model.Member.table_id == pkg.id) \
        .filter(model.Member.capacity == 'organization')

    need_update = True
    for member_obj in members:
        if org and member_obj.group_id == org.id:
            need_update = False
        else:
            member_obj.state = 'deleted'
            member_obj.save()

    # add the organization to member table
    if org and need_update:
        member_obj = model.Member(table_id=pkg.id,
                                  table_name='package',
                                  group=org,
                                  capacity='organization',
                                  group_id=org.id,
                                  state='active')
        model.Session.add(member_obj)

    if not context.get('defer_commit'):
        model.Session.commit()
Exemple #4
0
def _bulk_update_dataset(
        context: Context, data_dict: DataDict, update_dict: dict[str, Any]):
    ''' Bulk update shared code for organizations'''

    datasets = data_dict.get('datasets', [])
    org_id = data_dict.get('org_id')

    model = context['model']
    model.Session.query(model.package_table) \
        .filter(
            # type_ignore_reason: incomplete SQLAlchemy types
            model.Package.id.in_(datasets)  # type: ignore
        ) .filter(model.Package.owner_org == org_id) \
        .update(update_dict, synchronize_session=False)

    model.Session.commit()

    # solr update here
    psi = search.PackageSearchIndex()

    # update the solr index in batches
    BATCH_SIZE = 50

    def process_solr(q: str):
        # update the solr index for the query
        query = search.PackageSearchQuery()
        q_dict = {
            'q': q,
            'fl': 'data_dict',
            'wt': 'json',
            'fq': 'site_id:"%s"' % config.get_value('ckan.site_id'),
            'rows': BATCH_SIZE
        }

        for result in query.run(q_dict)['results']:
            data_dict = json.loads(result['data_dict'])
            if data_dict['owner_org'] == org_id:
                data_dict.update(update_dict)
                psi.index_package(data_dict, defer_commit=True)

    count = 0
    q = []
    for id in datasets:
        q.append('id:"%s"' % (id))
        count += 1
        if count % BATCH_SIZE == 0:
            process_solr(' OR '.join(q))
            q = []
    if len(q):
        process_solr(' OR '.join(q))
    # finally commit the changes
    psi.commit()
Exemple #5
0
def group_activity_list(context: Context,
                        data_dict: DataDict) -> list[dict[str, Any]]:
    """Return a group's activity stream.

    You must be authorized to view the group.

    :param id: the id or name of the group
    :type id: string
    :param offset: where to start getting activity items from
        (optional, default: ``0``)
    :type offset: int
    :param limit: the maximum number of activities to return
        (optional, default: ``31`` unless set in site's configuration
        ``ckan.activity_list_limit``, upper limit: ``100`` unless set in
        site's configuration ``ckan.activity_list_limit_max``)
    :type limit: int
    :param include_hidden_activity: whether to include 'hidden' activity, which
        is not shown in the Activity Stream page. Hidden activity includes
        activity done by the site_user, such as harvests, which are not shown
        in the activity stream because they can be too numerous, or activity by
        other users specified in config option `ckan.hide_activity_from_users`.
        NB Only sysadmins may set include_hidden_activity to true.
        (default: false)
    :type include_hidden_activity: bool

    :rtype: list of dictionaries

    """
    # FIXME: Filter out activities whose subject or object the user is not
    # authorized to read.
    data_dict = dict(data_dict, include_data=False)
    include_hidden_activity = data_dict.get("include_hidden_activity", False)
    tk.check_access("group_activity_list", context, data_dict)

    group_id = data_dict.get("id")
    offset = data_dict.get("offset", 0)
    limit = data_dict["limit"]  # defaulted, limited & made an int by schema

    # Convert group_id (could be id or name) into id.
    group_show = tk.get_action("group_show")
    group_id = group_show(context, {"id": group_id})["id"]

    activity_objects = model_activity.group_activity_list(
        group_id,
        limit=limit,
        offset=offset,
        include_hidden_activity=include_hidden_activity,
    )

    return model_activity.activity_list_dictize(activity_objects, context)
Exemple #6
0
def activity_list(context: Context, data_dict: DataDict) -> AuthResult:
    """
    :param id: the id or name of the object (e.g. package id)
    :type id: string
    :param object_type: The type of the object (e.g. 'package', 'organization',
                        'group', 'user')
    :type object_type: string
    :param include_data: include the data field, containing a full object dict
        (otherwise the data field is only returned with the object's title)
    :type include_data: boolean
    """
    if data_dict["object_type"] not in (
            "package",
            "organization",
            "group",
            "user",
    ):
        return {"success": False, "msg": "object_type not recognized"}
    is_public = authz.check_config_permission("public_activity_stream_detail")
    if data_dict.get("include_data") and not is_public:
        # The 'data' field of the activity is restricted to users who are
        # allowed to edit the object
        show_or_update = "update"
    else:
        # the activity for an object (i.e. the activity metadata) can be viewed
        # if the user can see the object
        show_or_update = "show"
    action_on_which_to_base_auth = "{}_{}".format(
        data_dict["object_type"], show_or_update)  # e.g. 'package_update'
    return authz.is_authorized(action_on_which_to_base_auth, context,
                               {"id": data_dict["id"]})
Exemple #7
0
def api_token_revoke(context: Context,
                     data_dict: DataDict) -> ActionResult.ApiTokenRevoke:
    """Delete API Token.

    :param string token: Token to remove(required if `jti` not specified).
    :param string jti: Id of the token to remove(overrides `token` if
        specified).

    .. versionadded:: 3.0
    """
    jti = data_dict.get(u'jti')
    if not jti:
        token = _get_or_bust(data_dict, u'token')
        decoders = plugins.PluginImplementations(plugins.IApiToken)
        for plugin in decoders:
            data = plugin.decode_api_token(token)
            if data:
                break
        else:
            data = api_token.decode(token)

        if data:
            jti = data.get(u'jti')

    _check_access(u'api_token_revoke', context, {u'jti': jti})
    model = context[u'model']
    model.ApiToken.revoke(jti)
Exemple #8
0
def activity_list(context: Context, data_dict: DataDict) -> AuthResult:
    '''
    :param id: the id or name of the object (e.g. package id)
    :type id: string
    :param object_type: The type of the object (e.g. 'package', 'organization',
                        'group', 'user')
    :type object_type: string
    :param include_data: include the data field, containing a full object dict
        (otherwise the data field is only returned with the object's title)
    :type include_data: boolean
    '''
    if data_dict['object_type'] not in ('package', 'organization', 'group',
                                        'user'):
        return {'success': False, 'msg': 'object_type not recognized'}
    if (data_dict.get('include_data') and
            not authz.check_config_permission('public_activity_stream_detail')
        ):
        # The 'data' field of the activity is restricted to users who are
        # allowed to edit the object
        show_or_update = 'update'
    else:
        # the activity for an object (i.e. the activity metadata) can be viewed
        # if the user can see the object
        show_or_update = 'show'
    action_on_which_to_base_auth = '{}_{}'.format(
        data_dict['object_type'], show_or_update)  # e.g. 'package_update'
    return authz.is_authorized(action_on_which_to_base_auth, context,
                               {'id': data_dict['id']})
Exemple #9
0
def _unfollow(context: Context, data_dict: DataDict, schema: Schema,
              FollowerClass: Type['ModelFollowingModel[Any, Any]']):
    model = context['model']

    if not context.get('user'):
        raise ckan.logic.NotAuthorized(
            _("You must be logged in to unfollow something."))
    userobj = model.User.get(context['user'])
    if not userobj:
        raise ckan.logic.NotAuthorized(
            _("You must be logged in to unfollow something."))
    follower_id = userobj.id

    validated_data_dict, errors = validate(data_dict, schema, context)
    if errors:
        raise ValidationError(errors)
    object_id = validated_data_dict.get('id')

    follower_obj = FollowerClass.get(follower_id, object_id)
    if follower_obj is None:
        raise NotFound(
            _('You are not following {0}.').format(data_dict.get('id')))

    follower_obj.delete()
    model.repo.commit()
Exemple #10
0
def tag_delete(context: Context, data_dict: DataDict) -> None:
    '''Delete a tag.

    You must be a sysadmin to delete tags.

    :param id: the id or name of the tag
    :type id: string
    :param vocabulary_id: the id or name of the vocabulary that the tag belongs
        to (optional, default: None)
    :type vocabulary_id: string

    '''
    model = context['model']

    if 'id' not in data_dict or not data_dict['id']:
        raise ValidationError({'id': _('id not in data')})
    tag_id_or_name = _get_or_bust(data_dict, 'id')

    vocab_id_or_name = data_dict.get('vocabulary_id')

    tag_obj = model.Tag.get(tag_id_or_name, vocab_id_or_name)

    if tag_obj is None:
        raise NotFound(_('Could not find tag "%s"') % tag_id_or_name)

    _check_access('tag_delete', context, data_dict)

    tag_obj.delete()
    model.repo.commit()
Exemple #11
0
def recently_changed_packages_activity_list(
        context: Context, data_dict: DataDict) -> list[dict[str, Any]]:
    """Return the activity stream of all recently added or changed packages.

    :param offset: where to start getting activity items from
        (optional, default: ``0``)
    :type offset: int
    :param limit: the maximum number of activities to return
        (optional, default: ``31`` unless set in site's configuration
        ``ckan.activity_list_limit``, upper limit: ``100`` unless set in
        site's configuration ``ckan.activity_list_limit_max``)
    :type limit: int

    :rtype: list of dictionaries

    """
    # FIXME: Filter out activities whose subject or object the user is not
    # authorized to read.
    offset = data_dict.get("offset", 0)
    limit = data_dict["limit"]  # defaulted, limited & made an int by schema

    activity_objects = model_activity.recently_changed_packages_activity_list(
        limit=limit, offset=offset)

    return model_activity.activity_list_dictize(activity_objects, context)
Exemple #12
0
def bulk_update_delete(context: Context, data_dict: DataDict) -> AuthResult:
    org_id = data_dict.get('org_id')
    user = context['user']
    authorized = authz.has_user_permission_for_group_or_org(
        org_id, user, 'update')
    if not authorized:
        return {'success': False}
    return {'success': True}
Exemple #13
0
def group_show(context: Context, data_dict: DataDict) -> AuthResult:
    user = context.get('user')
    group = get_group_object(context, data_dict)
    if group.state == 'active':
        if config.get_value('ckan.auth.public_user_details') or \
            (not asbool(data_dict.get('include_users', False)) and
                (data_dict.get('object_type', None) != 'user')):
            return {'success': True}
    authorized = authz.has_user_permission_for_group_or_org(
        group.id, user, 'read')
    if authorized:
        return {'success': True}
    else:
        return {
            'success': False,
            'msg':
            _('User %s not authorized to read group %s') % (user, group.id)
        }
Exemple #14
0
def user_list(context: Context, data_dict: DataDict) -> AuthResult:
    # Users list is visible by default
    if data_dict.get('email'):
        # only sysadmins can specify the 'email' parameter
        return {'success': False}
    if not config.get_value('ckan.auth.public_user_details'):
        return restrict_anon(context)
    else:
        return {'success': True}
Exemple #15
0
def package_collaborator_list_for_user(context: Context,
                                       data_dict: DataDict) -> AuthResult:
    '''Checks if a user is allowed to list all datasets a user is a collaborator in

    The current implementation restricts to the own users themselves.
    '''
    user_obj = context.get('auth_user_obj')
    if user_obj and data_dict.get('id') in (user_obj.name, user_obj.id):
        return {'success': True}
    return {'success': False}
Exemple #16
0
def dashboard_activity_list(context: Context,
                            data_dict: DataDict) -> list[dict[str, Any]]:
    """Return the authorized (via login or API key) user's dashboard activity
       stream.

    Unlike the activity dictionaries returned by other ``*_activity_list``
    actions, these activity dictionaries have an extra boolean value with key
    ``is_new`` that tells you whether the activity happened since the user last
    viewed her dashboard (``'is_new': True``) or not (``'is_new': False``).

    The user's own activities are always marked ``'is_new': False``.

    :param offset: where to start getting activity items from
        (optional, default: ``0``)
    :type offset: int
    :param limit: the maximum number of activities to return
        (optional, default: ``31`` unless set in site's configuration
        ``ckan.activity_list_limit``, upper limit: ``100`` unless set in
        site's configuration ``ckan.activity_list_limit_max``)
    :type limit: int

    :rtype: list of activity dictionaries

    """
    tk.check_access("dashboard_activity_list", context, data_dict)

    model = context["model"]
    user_obj = model.User.get(context["user"])
    assert user_obj
    user_id = user_obj.id
    offset = data_dict.get("offset", 0)
    limit = data_dict["limit"]  # defaulted, limited & made an int by schema

    # FIXME: Filter out activities whose subject or object the user is not
    # authorized to read.
    activity_objects = model_activity.dashboard_activity_list(user_id,
                                                              limit=limit,
                                                              offset=offset)

    activity_dicts = model_activity.activity_list_dictize(
        activity_objects, context)

    # Mark the new (not yet seen by user) activities.
    strptime = datetime.datetime.strptime
    fmt = "%Y-%m-%dT%H:%M:%S.%f"
    last_viewed = model.Dashboard.get(user_id).activity_stream_last_viewed
    for activity in activity_dicts:
        if activity["user_id"] == user_id:
            # Never mark the user's own activities as new.
            activity["is_new"] = False
        else:
            activity["is_new"] = (strptime(activity["timestamp"], fmt) >
                                  last_viewed)

    return activity_dicts
Exemple #17
0
def package_relationship_update(
        context: Context,
        data_dict: DataDict) -> ActionResult.PackageRelationshipUpdate:
    '''Update a relationship between two datasets (packages).

    The subject, object and type parameters are required to identify the
    relationship. Only the comment can be updated.

    You must be authorized to edit both the subject and the object datasets.

    :param subject: the name or id of the dataset that is the subject of the
        relationship
    :type subject: string
    :param object: the name or id of the dataset that is the object of the
        relationship
    :type object: string
    :param type: the type of the relationship, one of ``'depends_on'``,
        ``'dependency_of'``, ``'derives_from'``, ``'has_derivation'``,
        ``'links_to'``, ``'linked_from'``, ``'child_of'`` or ``'parent_of'``
    :type type: string
    :param comment: a comment about the relationship (optional)
    :type comment: string

    :returns: the updated relationship
    :rtype: dictionary

    '''
    model = context['model']
    schema = context.get('schema') \
        or schema_.default_update_relationship_schema()

    id, id2, rel = _get_or_bust(data_dict, ['subject', 'object', 'type'])

    pkg1 = model.Package.get(id)
    pkg2 = model.Package.get(id2)
    if not pkg1:
        raise NotFound('Subject package %r was not found.' % id)
    if not pkg2:
        raise NotFound('Object package %r was not found.' % id2)

    _data, errors = _validate(data_dict, schema, context)
    if errors:
        model.Session.rollback()
        raise ValidationError(errors)

    _check_access('package_relationship_update', context, data_dict)

    existing_rels = pkg1.get_relationships_with(pkg2, rel)
    if not existing_rels:
        raise NotFound('This relationship between the packages was not found.')
    entity = existing_rels[0]
    comment = data_dict.get('comment', u'')
    context['relationship'] = entity
    return _update_package_relationship(entity, comment, context)
Exemple #18
0
def _group_or_org_member_delete(context: Context, data_dict: DataDict) -> None:
    model = context['model']
    user = context['user']
    session = context['session']

    group_id = data_dict.get('id')
    group = model.Group.get(group_id)
    user_id = data_dict.get('username')
    user_id = data_dict.get('user_id') if user_id is None else user_id
    assert group
    member_dict = {
        'id': group.id,
        'object': user_id,
        'object_type': 'user',
    }
    member_context = cast(Context, {
        'model': model,
        'user': user,
        'session': session
    })
    _get_action('member_delete')(member_context, member_dict)
Exemple #19
0
def user_activity_list(context: Context,
                       data_dict: DataDict) -> list[dict[str, Any]]:
    """Return a user's public activity stream.

    You must be authorized to view the user's profile.


    :param id: the id or name of the user
    :type id: string
    :param offset: where to start getting activity items from
        (optional, default: ``0``)
    :type offset: int
    :param limit: the maximum number of activities to return
        (optional, default: ``31`` unless set in site's configuration
        ``ckan.activity_list_limit``, upper limit: ``100`` unless set in
        site's configuration ``ckan.activity_list_limit_max``)
    :type limit: int

    :rtype: list of dictionaries

    """
    # FIXME: Filter out activities whose subject or object the user is not
    # authorized to read.
    tk.check_access("user_activity_list", context, data_dict)

    model = context["model"]

    user_ref = data_dict.get("id")  # May be user name or id.
    user = model.User.get(user_ref)
    if user is None:
        raise tk.ObjectNotFound()

    offset = data_dict.get("offset", 0)
    limit = data_dict["limit"]  # defaulted, limited & made an int by schema

    activity_objects = model_activity.user_activity_list(user.id,
                                                         limit=limit,
                                                         offset=offset)

    return model_activity.activity_list_dictize(activity_objects, context)
Exemple #20
0
def task_status_update(
        context: Context, data_dict: DataDict) -> ActionResult.TaskStatusUpdate:
    '''Update a task status.

    :param id: the id of the task status to update
    :type id: string
    :param entity_id:
    :type entity_id: string
    :param entity_type:
    :type entity_type: string
    :param task_type:
    :type task_type: string
    :param key:
    :type key: string
    :param value: (optional)
    :type value:
    :param state: (optional)
    :type state:
    :param last_updated: (optional)
    :type last_updated:
    :param error: (optional)
    :type error:

    :returns: the updated task status
    :rtype: dictionary

    '''
    model = context['model']
    session = context['session']

    id = data_dict.get("id")
    schema = context.get('schema') or schema_.default_task_status_schema()

    if id:
        task_status = model.TaskStatus.get(id)
        if task_status is None:
            raise NotFound(_('TaskStatus was not found.'))
        context["task_status"] = task_status

    _check_access('task_status_update', context, data_dict)

    data, errors = _validate(data_dict, schema, context)
    if errors:
        session.rollback()
        raise ValidationError(errors)

    task_status = model_save.task_status_dict_save(data, context)

    session.commit()
    session.close()
    return model_dictize.task_status_dictize(task_status, context)
Exemple #21
0
def _followee_list(context: Context, data_dict: DataDict) -> AuthResult:
    model = context['model']

    # Visitors cannot see what users are following.
    authorized_user = model.User.get(context.get('user'))
    if not authorized_user:
        return {'success': False, 'msg': _('Not authorized')}

    # Any user is authorized to see what she herself is following.
    requested_user = model.User.get(data_dict.get('id', ''))
    if authorized_user == requested_user:
        return {'success': True}

    # Sysadmins are authorized to see what anyone is following.
    return authz.is_authorized('sysadmin', context, data_dict)
Exemple #22
0
def resource_view_clear(context: Context,
                        data_dict: DataDict) -> ActionResult.ResourceViewClear:
    '''Delete all resource views, or all of a particular type.

    :param view_types: specific types to delete (optional)
    :type view_types: list

    '''
    model = context['model']

    _check_access('resource_view_clear', context, data_dict)

    view_types = data_dict.get('view_types', [])
    model.ResourceView.delete_all(view_types)
    model.repo.commit()
Exemple #23
0
def vocabulary_update(context: Context,
                      data_dict: DataDict) -> ActionResult.VocabularyUpdate:
    '''Update a tag vocabulary.

    You must be a sysadmin to update vocabularies.

    For further parameters see
    :py:func:`~ckan.logic.action.create.vocabulary_create`.

    :param id: the id of the vocabulary to update
    :type id: string

    :returns: the updated vocabulary
    :rtype: dictionary

    '''
    model = context['model']

    vocab_id = data_dict.get('id')
    if not vocab_id:
        raise ValidationError({'id': _('id not in data')})

    vocab = model.Vocabulary.get(vocab_id)
    if vocab is None:
        raise NotFound(_('Could not find vocabulary "%s"') % vocab_id)

    data_dict['id'] = vocab.id
    if 'name' in data_dict:
        if data_dict['name'] == vocab.name:
            del data_dict['name']

    _check_access('vocabulary_update', context, data_dict)

    schema = context.get(
        'schema') or schema_.default_update_vocabulary_schema()
    data, errors = _validate(data_dict, schema, context)
    if errors:
        model.Session.rollback()
        raise ValidationError(errors)

    updated_vocab = model_save.vocabulary_dict_update(data, context)

    if not context.get('defer_commit'):
        model.repo.commit()

    return model_dictize.vocabulary_dictize(updated_vocab, context)
Exemple #24
0
def member_create(context: Context, data_dict: DataDict) -> AuthResult:
    group = logic_auth.get_group_object(context, data_dict)
    user = context['user']

    # User must be able to update the group to add a member to it
    permission = 'update'
    # However if the user is member of group then they can add/remove datasets
    if not group.is_organization and data_dict.get('object_type') == 'package':
        permission = 'manage_group'

    authorized = authz.has_user_permission_for_group_or_org(group.id,
                                                                user,
                                                                permission)
    if not authorized:
        return {'success': False,
                'msg': _('User %s not authorized to edit group %s') %
                        (str(user), group.id)}
    else:
        return {'success': True}
Exemple #25
0
def datastore_auth(context: Context,
                   data_dict: DataDict,
                   privilege: str = 'resource_update') -> AuthResult:
    if 'id' not in data_dict:
        data_dict['id'] = data_dict.get('resource_id')

    user = context.get('user')

    authorized = p.toolkit.check_access(privilege, context, data_dict)
    if not authorized:
        return {
            'success': False,
            'msg': p.toolkit._(
                'User {0} not authorized to update resource {1}'
                    .format(str(user), data_dict['id'])
            )
        }
    else:
        return {'success': True}
Exemple #26
0
def activity_data_show(context: Context,
                       data_dict: DataDict) -> dict[str, Any]:
    """Show the data from an item of 'activity' (part of the activity
    stream).

    For example for a package update this returns just the dataset dict but
    none of the activity stream info of who and when the version was created.

    :param id: the id of the activity
    :type id: string
    :param object_type: 'package', 'user', 'group' or 'organization'
    :type object_type: string

    :rtype: dictionary
    """
    model = context["model"]
    activity_id = tk.get_or_bust(data_dict, "id")
    object_type = data_dict.get("object_type")

    activity = model.Session.query(model_activity.Activity).get(activity_id)
    if activity is None:
        raise tk.ObjectNotFound()
    context["activity"] = activity

    tk.check_access("activity_data_show", context, data_dict)

    activity = model_activity.activity_dictize(activity, context)
    try:
        activity_data = activity["data"]
    except KeyError:
        raise tk.ObjectNotFound("Could not find data in the activity")
    if object_type:
        try:
            activity_data = activity_data[object_type]
        except KeyError:
            raise tk.ObjectNotFound(
                "Could not find that object_type in the activity")
    return activity_data
Exemple #27
0
def vocabulary_delete(context: Context, data_dict: DataDict) -> None:
    '''Delete a tag vocabulary.

    You must be a sysadmin to delete vocabularies.

    :param id: the id of the vocabulary
    :type id: string

    '''
    model = context['model']

    vocab_id = data_dict.get('id')
    if not vocab_id:
        raise ValidationError({'id': _('id not in data')})

    vocab_obj = model.Vocabulary.get(vocab_id)
    if vocab_obj is None:
        raise NotFound(_('Could not find vocabulary "%s"') % vocab_id)

    _check_access('vocabulary_delete', context, data_dict)

    vocab_obj.delete()
    model.repo.commit()
Exemple #28
0
def package_relationships_list(context: Context,
                               data_dict: DataDict) -> AuthResult:
    user = context.get('user')

    id = data_dict['id']
    id2 = data_dict.get('id2')

    # If we can see each package we can see the relationships
    authorized1 = authz.is_authorized_boolean('package_show', context,
                                              {'id': id})
    if id2:
        authorized2 = authz.is_authorized_boolean('package_show', context,
                                                  {'id': id2})
    else:
        authorized2 = True

    if not (authorized1 and authorized2):
        return {
            'success': False,
            'msg': _('User %s not authorized to read these packages') % user
        }
    else:
        return {'success': True}
Exemple #29
0
def _package_search(data_dict: DataDict) -> tuple[int, list[dict[str, Any]]]:
    """
    Helper method that wraps the package_search action.

     * unless overridden, sorts results by metadata_modified date
     * unless overridden, sets a default item limit
    """
    context = cast(
        Context, {
            u'model': model,
            u'session': model.Session,
            u'user': current_user.name,
            u'auth_user_obj': current_user
        })
    if u'sort' not in data_dict or not data_dict['sort']:
        data_dict['sort'] = u'metadata_modified desc'

    if u'rows' not in data_dict or not data_dict['rows']:
        data_dict['rows'] = config.get_value('ckan.feeds.limit')

    # package_search action modifies the data_dict, so keep our copy intact.
    query = logic.get_action(u'package_search')(context, data_dict.copy())

    return query['count'], query['results']
Exemple #30
0
def job_clear(context: Context, data_dict: DataDict) -> list[str]:
    '''Clear background job queues.

    Does not affect jobs that are already being processed.

    :param list queues: The queues to clear. If not given then ALL
        queues are cleared.

    :returns: The cleared queues.
    :rtype: list

    .. versionadded:: 2.7
    '''
    _check_access(u'job_clear', context, data_dict)
    queues = data_dict.get(u'queues')
    if queues:
        queues = [jobs.get_queue(q) for q in queues]
    else:
        queues = jobs.get_all_queues()
    names = [jobs.remove_queue_name_prefix(queue.name) for queue in queues]
    for queue, name in zip(queues, names):
        queue.empty()
        log.info(u'Cleared background job queue "{}"'.format(name))
    return names