def resource_version_list(context, data_dict): """List versions of a given resource :param resource_id: the id the resource :type resource_id: string :returns: list of matched versions :rtype: list """ model = context.get('model', core_model) resource_id = toolkit.get_or_bust(data_dict, ['resource_id']) resource = model.Resource.get(resource_id) if not resource: raise toolkit.ObjectNotFound('Resource not found') toolkit.check_access('version_list', context, {"package_id": resource.package_id}) versions = model.Session.query(Version).\ filter(Version.resource_id == resource.id).\ order_by(Version.created.desc()) if not versions: raise toolkit.ObjectNotFound('Versions not found for this resource') return [v.as_dict() for v in versions]
def dataset_collaborator_create(context, data_dict): '''Make a user a collaborator in a dataset. If the user is already a collaborator in the dataset then their capacity will be updated. Currently you must be an Admin on the dataset owner organization to manage collaborators. :param id: the id or name of the dataset :type id: string :param user_id: the id or name of the user to add or edit :type user_id: string :param capacity: the capacity of the membership. Must be one of {} :type capacity: string :returns: the newly created (or updated) collaborator :rtype: dictionary '''.format(', '.join(ALLOWED_CAPACITIES)) model = context.get('model', core_model) dataset_id, user_id, capacity = toolkit.get_or_bust( data_dict, ['id', 'user_id', 'capacity']) if capacity not in ALLOWED_CAPACITIES: raise toolkit.ValidationError('Capacity must be one of "{}"'.format( ', '.join(ALLOWED_CAPACITIES))) dataset = model.Package.get(dataset_id) if not dataset: raise toolkit.ObjectNotFound('Dataset not found') user = model.User.get(user_id) if not user: raise toolkit.ObjectNotFound('User not found') toolkit.check_access('dataset_collaborator_create', context, data_dict) # Check if member already exists member = model.Session.query(DatasetMember).\ filter(DatasetMember.dataset_id == dataset.id).\ filter(DatasetMember.user_id == user.id).one_or_none() if not member: member = DatasetMember(dataset_id=dataset.id, user_id=user.id) member.capacity = capacity member.modified = datetime.datetime.utcnow() model.Session.add(member) model.repo.commit() log.info('User {} added as collaborator in dataset {} ({})'.format( user.name, dataset.id, capacity)) mail_notification_to_collaborator(dataset_id, user_id, capacity, event='create') return member.as_dict()
def package_collaborator_org_create(context, data_dict): '''Make a user a collaborator in a dataset. If the user is already a collaborator in the dataset then their capacity will be updated. Currently you must be an Admin on the dataset owner organization to manage collaborators. :param id: the id or name of the dataset :type id: string :param user_id: the id or name of the user to add or edit :type user_id: string :param capacity: the capacity of the membership. Must be either 'editor' or 'member' :type capacity: string :returns: the newly created (or updated) collaborator :rtype: dictionary ''' model = context.get('model', core_model) dataset_id, org_id, capacity = toolkit.get_or_bust( data_dict, ['id', 'org_id', 'capacity']) dataset = model.Package.get(dataset_id) if not dataset: raise toolkit.ObjectNotFound('Dataset not found') toolkit.check_access('package_collaborator_org_create', context, data_dict) org = model.Group.get(org_id) if not org: raise toolkit.ObjectNotFound('Organization not found') if capacity not in ALLOWED_CAPACITIES: raise toolkit.ValidationError('Capacity must be one of "{}"'.format( ', '.join(ALLOWED_CAPACITIES))) # Check if organization already exists member = model.Session.query(PackageOrgMember).\ filter(PackageOrgMember.dataset_id == dataset.id).\ filter(PackageOrgMember.org_id == org.id).one_or_none() if not member: member = PackageOrgMember(dataset_id=dataset.id, org_id=org.id) member.capacity = capacity member.modified = datetime.datetime.utcnow() model.Session.add(member) model.repo.commit() #Rebuild search index for package to reflect updated permissions rebuild(dataset_id) log.info('Organization {} added as collaborator in dataset {} ({})'.format( org.name, dataset.id, capacity)) return member.as_dict()
def user_role_unassign(context, data_dict): """ Unassign a role from a user. You must be a sysadmin to unassign roles. :param user_id: the id or name of the user :type user_id: string :param role_id: the id or name of the role :type role_id: string :param organization_id: the id or name of the organization for which the user role assignment applies :type organization_id: string """ log.info("Unassigning role from user: %r", data_dict) tk.check_access('user_role_unassign', context, data_dict) model = context['model'] author = context['user'] defer_commit = context.get('defer_commit', False) user_id, role_id, organization_id = tk.get_or_bust( data_dict, ['user_id', 'role_id', 'organization_id']) user = model.User.get(user_id) if user is not None and user.state == 'active': user_id = user.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('User'))) role = extmodel.Role.get(role_id) if role is not None: role_id = role.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Role'))) organization = model.Group.get(organization_id) if organization is not None and organization.state == 'active' and organization.type == 'organization': organization_id = organization.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Organization'))) user_role = extmodel.UserRole.lookup(user_id, role_id, organization_id) if not user_role or user_role.state != 'active': raise tk.ValidationError( _('The user does not have the specified role')) user_role.delete() rev = model.repo.new_revision() rev.author = author if 'message' in context: rev.message = context['message'] else: rev.message = _( u'REST API: Unassign role %s from user %s in organization %s') % ( role.name, user.name, organization.name) if not defer_commit: model.repo.commit()
def new_indicator(self, params): dataset = DatasetService.get_dataset(params['dataset_id']) params['dataset_id'] = dataset.ckan_meta['id'] if params['ind_type'] != 'common': user_indicators_id = self.session.query(UserIndicatorLink.indicator_id)\ .filter(and_(UserIndicatorLink.user_id == params['user'].ckan_user_id, UserIndicatorLink.deleted == False)).all() existing_inds = self.session.query(ProfileIndicator)\ .filter(and_(ProfileIndicator.dataset_id == dataset.ckan_meta['id'], ProfileIndicator.id.in_(user_indicators_id))) # check that there're currently no such indicators in the db # there's a JSON type for fields in postgre, so maybe there's a way to do it using SQL for ex_ind in existing_inds: ex_fltrs = json.loads(ex_ind.filters) # python allows us to compare lists of dicts if sorted(params['filters']) == sorted( ex_fltrs) and params['ind_type'] != 'gallery': raise ProfileAlreadyExists( "Profile with such dataset and filters already exists") if type(params['filters']) is not list: params['filters'] = json.loads(params['filters']) try: params['data_type'] = dict_with_key_value( "field", "Measure Type", params['filters'])['values'][0] params['years'] = dict_with_key_value( "field", "Year", params['filters'])['values'][0] except (TypeError, AttributeError, IndexError): raise toolkit.ObjectNotFound( "There must be values for the 'Measure Type' and 'Year' filters" ) variable_fltr = dict_with_key_value("field", "Variable", params['filters']) params['variable'] = '' if variable_fltr: params['variable'] = variable_fltr["values"][ 0] if "values" in variable_fltr else None try: params['years'] = int(params['years']) except ValueError: try: params['years'] = int( datetime.datetime.strptime("2008-09-03 00:00:00", "%Y-%m-%d %H:%M:%S").year) except ValueError: raise toolkit.ObjectNotFound( "'Year' filter value must be an integer or have '%Y-%m-%d %H:%M:%S' format" ) params['filters'] = json.dumps(params['filters']) indicator = ProfileIndicator(params) return indicator
def role_permission_grant(context, data_dict): """ Grant a permission to a role. You must be a sysadmin to grant permissions. :param role_id: the id or name of the role :type role_id: string :param content_type: the content type that the permission relates to :type content_type: string :param operation: the operation to allow the role to perform on the content type :type operation: string :returns: the newly created role permission :rtype: dictionary """ log.info("Granting permission to role: %r", data_dict) tk.check_access('role_permission_grant', context, data_dict) model = context['model'] user = context['user'] defer_commit = context.get('defer_commit', False) role_id, content_type, operation = tk.get_or_bust( data_dict, ['role_id', 'content_type', 'operation']) role = extmodel.Role.get(role_id) if role is not None and role.state == 'active': role_id = role.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Role'))) permission = extmodel.Permission.lookup(content_type, operation) if permission is None: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Permission'))) role_permission = extmodel.RolePermission.lookup(role_id, content_type, operation) if role_permission and role_permission.state == 'active': raise tk.ValidationError( _('The specified permission has already been granted to the role')) data_dict['role_id'] = role_id data_dict['state'] = 'active' role_permission = dictization.role_permission_dict_save(data_dict, context) rev = model.repo.new_revision() rev.author = user if 'message' in context: rev.message = context['message'] else: rev.message = _(u'REST API: Grant permission to role %s: %s %s') % ( role.name, permission.operation, permission.content_type) if not defer_commit: model.repo.commit() return dictization.role_permission_dictize(role_permission, context)
def harvest_job_create(context, data_dict): ''' Authorization check for harvest job creation It forwards the checks to package_update, ie the user can only create new jobs if she is allowed to edit the harvest source dataset. ''' model = context['model'] source_id = data_dict['source_id'] pkg = model.Package.get(source_id) if not pkg: raise pt.ObjectNotFound(pt._('Harvest source not found')) context['package'] = pkg try: pt.check_access('package_update', context, data_dict) return {'success': True} except pt.NotAuthorized: return { 'success': False, 'msg': pt._('User not authorized to create a job for source {0}').format( source_id) }
def jsonpatch_show(context, data_dict): """ Return a JSON Patch definition. The structure of the returned dictionary may be customized by passing 'schema' in the context. :param id: the id of the JSON Patch :type id: string :rtype: dictionary """ log.debug("Retrieving JSON Patch: %r", data_dict) jsonpatch_id = tk.get_or_bust(data_dict, 'id') jsonpatch = JSONPatch.get(jsonpatch_id) if jsonpatch is not None: jsonpatch_id = jsonpatch.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('JSON Patch'))) tk.check_access('jsonpatch_show', context, data_dict) output_schema = context.get('schema') context['jsonpatch'] = jsonpatch jsonpatch_dict = jsonpatch_dictize(jsonpatch, context) result_dict, errors = tk.navl_validate(jsonpatch_dict, output_schema or schema.jsonpatch_show_schema(), context) return result_dict
def _get_metadata(resource_id): try: return ResourceMetadata.one(resource_id=resource_id) except NoResultFound: raise toolkit.ObjectNotFound( toolkit._("No metadata found for resource '{resource}'.").format( resource=resource_id))
def basket_purge(context, data_dict): """Purge a basket :param id: The id of the basket :type id: string :returns: """ tk.check_access('basket_owner_only', context, data_dict) model = context['model'] id = _get_or_bust(data_dict, 'id') basket = Basket.get(id) if basket is None: raise tk.ObjectNotFound('Basket was not found') basket_associations = model.Session.query(BasketAssociation) \ .filter(BasketAssociation.basket_id == id) if basket_associations.count() > 0: for ba in basket_associations.all(): ba.purge() basket.purge() model.repo.commit()
def access_request_update(context, data_dict): user = context.get('user') request_id = toolkit.get_or_bust(data_dict, "id") request = model.Session.query(AccessRequest).get(request_id) if not request: raise toolkit.ObjectNotFound("Access Request not found") if request.object_type not in ['organization', 'package', 'user']: raise toolkit.Invalid("Unknown Object Type") if request.object_type == 'package': package = toolkit.get_action('package_show')(context, { 'id': request.object_id }) org_id = package['owner_org'] return { 'success': has_user_permission_for_group_or_org(org_id, user, 'admin') } elif request.object_type == 'organization': org_id = request.object_id return { 'success': has_user_permission_for_group_or_org(org_id, user, 'admin') } elif request.object_type == 'user': data_dict = { 'id': request.object_id, 'renew_expiry_date': request.data.get( 'user_request_type', USER_REQUEST_TYPE_NEW) == USER_REQUEST_TYPE_RENEWAL } return external_user_update_state(context, data_dict)
def resource_show_revision(context, data_dict): """Show a resource from a specified revision Takes the same arguments as 'resource_show' but with an additional revision_ref parameter :param id: the id of the resource :type id: string :param revision_ref: the ID of the revision or release name :type revision_ref: string :returns: A resource dict :rtype: dict """ revision_ref = _get_revision_ref(data_dict) if revision_ref is None: return core_resource_show(context, data_dict) model = context['model'] id = toolkit.get_or_bust(data_dict, 'id') resource = model.Resource.get(id) package = _get_package_in_revision(context, {'id': resource.package_id}, revision_ref) resource_dict = h.find_resource_in_package(package, id) if resource_dict is None: raise toolkit.ObjectNotFound("Resource not found for dataset revision") return resource_dict
def dataset_release_update(context, data_dict): """Update a release of the current dataset. :param dataset: the id or name of the dataset :type dataset: string :param release: the id of the release :type release: string :param name: A short name for the release :type name: string :param description: A description for the release :type description: string :returns: the edited release :rtype: dictionary """ release, name, dataset_name_or_id = toolkit.get_or_bust( data_dict, ['release', 'name', 'dataset']) toolkit.check_access('dataset_release_create', context, data_dict) assert context.get('auth_user_obj') # Should be here after `check_access` backend = get_metastore_backend() author = create_author_from_context(context) try: release_info = backend.tag_update( _get_dataset_name(dataset_name_or_id), release, new_name=name, new_description=data_dict.get('description', None), author=author) except exc.NotFound: raise toolkit.ObjectNotFound("Dataset release not found.") log.info('Release "%s" with id %s modified successfully', name, release) return tag_to_dict(release_info)
def infrastructure_member_delete(context, data_dict): """ Remove a user from an infrastructure. You must be authorized to edit the infrastructure. :param id: the id or name of the infrastructure :type id: string :param username: name or id of the user :type username: string """ log.info("Deleting a user's membership of an infrastructure: %r", data_dict) tk.check_access('infrastructure_member_delete', context, data_dict) model = context['model'] infrastructure_id = tk.get_or_bust(data_dict, 'id') username = data_dict.get('username') or data_dict.get('user_id') infrastructure = model.Group.get(infrastructure_id) if infrastructure is not None and infrastructure.type == 'infrastructure': infrastructure_id = infrastructure.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Project'))) member_dict = { 'id': infrastructure_id, 'object': username, 'object_type': 'user', } member_context = context.copy() member_context['ignore_auth'] = True return tk.get_action('member_delete')(member_context, member_dict)
def metadata_json_attr_map_delete(context, data_dict): """ Delete a metadata JSON attribute map. You must be authorized to delete the metadata JSON attribute map. :param id: the id or name of the metadata JSON attribute map to delete :type id: string """ log.info("Deleting metadata JSON attribute map: %r", data_dict) model = context['model'] user = context['user'] session = context['session'] defer_commit = context.get('defer_commit', False) metadata_json_attr_map_id = tk.get_or_bust(data_dict, 'id') metadata_json_attr_map = ckanext_model.MetadataJSONAttrMap.get( metadata_json_attr_map_id) if metadata_json_attr_map is not None: metadata_json_attr_map_id = metadata_json_attr_map.id else: raise tk.ObjectNotFound( '%s: %s' % (_('Not found'), _('Metadata JSON Attribute Map'))) tk.check_access('metadata_json_attr_map_delete', context, data_dict) rev = model.repo.new_revision() rev.author = user rev.message = _(u'REST API: Delete metadata JSON attribute map %s' ) % metadata_json_attr_map_id metadata_json_attr_map.delete() if not defer_commit: model.repo.commit()
def workflow_annotation_delete(context, data_dict): """ Delete a workflow annotation. You must be authorized to delete the workflow annotation. :param id: the id or name of the workflow annotation to delete :type id: string """ log.info("Deleting workflow annotation: %r", data_dict) model = context['model'] user = context['user'] session = context['session'] defer_commit = context.get('defer_commit', False) workflow_annotation_id = tk.get_or_bust(data_dict, 'id') workflow_annotation = ckanext_model.WorkflowAnnotation.get( workflow_annotation_id) if workflow_annotation is not None: workflow_annotation_id = workflow_annotation.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Workflow Annotation'))) tk.check_access('workflow_annotation_delete', context, data_dict) rev = model.repo.new_revision() rev.author = user rev.message = _( u'REST API: Delete workflow annotation %s') % workflow_annotation_id workflow_annotation.delete() if not defer_commit: model.repo.commit()
def infrastructure_delete(context, data_dict): """ Delete an infrastructure. You must be authorized to delete the infrastructure. :param id: the id or name of the infrastructure to delete :type id: string """ log.info("Deleting infrastructure: %r", data_dict) session = context['session'] model = context['model'] user = context['user'] infrastructure_id = tk.get_or_bust(data_dict, 'id') infrastructure = model.Group.get(infrastructure_id) if infrastructure is not None and infrastructure.type == 'infrastructure': infrastructure_id = infrastructure.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Project'))) tk.check_access('infrastructure_delete', context, data_dict) if session.query(model.Member) \ .join(model.Group, model.Group.id == model.Member.table_id) \ .filter(model.Member.group_id == infrastructure_id) \ .filter(model.Member.table_name == 'group') \ .filter(model.Member.state != 'deleted') \ .filter(model.Group.type == 'metadata_collection') \ .filter(model.Group.state != 'deleted') \ .count() > 0: raise tk.ValidationError( _('Project has dependent metadata collections')) # cascade delete to dependent metadata schemas cascade_context = { 'model': model, 'user': user, 'session': session, 'defer_commit': True, 'ignore_auth': True, } metadata_schema_ids = session.query(ckanext_model.MetadataSchema.id) \ .filter(ckanext_model.MetadataSchema.infrastructure_id == infrastructure_id) \ .filter(ckanext_model.MetadataSchema.state != 'deleted') \ .all() for (metadata_schema_id, ) in metadata_schema_ids: tk.get_action('metadata_schema_delete')(cascade_context, { 'id': metadata_schema_id }) data_dict['type'] = 'infrastructure' group_context = context.copy() group_context.update({ 'invoked_action': 'infrastructure_delete', 'ignore_auth': True, }) tk.get_action('group_delete')(group_context, data_dict)
def update_entry(cls, **kwargs): """ Update name or long_url for the existing entry :param kwargs: :return: """ _id = kwargs.get(u'id', u'') rec = cls.get_entry(id=_id) if not rec: raise toolkit.ObjectNotFound(u"Given record not found") if u'name' in kwargs: rec.name = convert_to_name(kwargs[u'name']) if u'long_url' in kwargs: validators.validate_url(kwargs[u'long_url']) rec.long_url = kwargs[u'long_url'] try: model.Session.commit() except orm_exceptions.IntegrityError as e: log.error(e) model.Session.flush() raise toolkit.ValidationError(u"Another Record with same name or url exists") return rec
def basket_list(context, data_dict): """List all baskets for user :param user_id: The id of the user for whom to list the baskets (only admin) :type user_id: string :returns: """ model = context['model'] user = context['user'] user_id = data_dict.get( 'user_id', authz.get_user_id_for_username(user, allow_none=True)) if not user_id: return [] if data_dict.get('user_id'): user = model.User.get(user_id) if user is None: raise tk.ObjectNotFound('User was not found') user_id = user.id q = model.Session.query(Basket).filter(Basket.user_id == user_id) return [basket.as_dict() for basket in q.all()]
def role_delete(context, data_dict): """ Delete a role. You must be a sysadmin to delete roles. :param id: the id of the role to delete :type id: string """ log.info("Deleting role: %r", data_dict) model = context['model'] user = context['user'] session = context['session'] defer_commit = context.get('defer_commit', False) role_id = tk.get_or_bust(data_dict, 'id') role = extmodel.Role.get(role_id) if role is not None: role_id = role.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Role'))) tk.check_access('role_delete', context, data_dict) rev = model.repo.new_revision() rev.author = user rev.message = _(u'REST API: Delete Role %s') % role_id role.delete() if not defer_commit: model.repo.commit()
def _get_deposited_dataset(context, dataset_id): deposit = helpers.get_data_deposit() dataset = toolkit.get_action('package_show')(context, {'id': dataset_id}) if dataset.get('owner_org') != deposit['id']: message = 'Deposited dataset "%s" not found' % dataset_id raise toolkit.ObjectNotFound(message) return dataset
def basket_element_remove(context, data_dict): """Remove an element from a basket :param basket_id: The id of the basket :type basket_id: string :param packages: The id of the packages :type packages: list of strings :param package_id: The id of the package :type package_id: string :returns: """ tk.check_access('basket_owner_only', context, {'id': data_dict['basket_id']}) model = context['model'] basket_id = _get_or_bust(data_dict, 'basket_id') basket = Basket.get(basket_id) if not basket: raise tk.ObjectNotFound('Basket was not found.') pkgs = data_dict.get('packages', None) package_id = data_dict.get('package_id', None) if pkgs is not None: for package_id in pkgs: _basket_element_remove(context, model, package_id, basket) elif package_id is not None: _basket_element_remove(context, model, package_id, basket) else: basket_id = _get_or_bust(data_dict, 'package_id') model.repo.commit()
def role_show(context, data_dict): """ Return a role definition. You must be a sysadmin to view roles. :param id: the id of the role :type id: string :rtype: dictionary """ log.debug("Retrieving role: %r", data_dict) role_id = tk.get_or_bust(data_dict, 'id') role = extmodel.Role.get(role_id) if role is not None: role_id = role.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Role'))) tk.check_access('role_show', context, data_dict) context['role'] = role role_dict = dictization.role_dictize(role, context) result_dict, errors = tk.navl_validate(role_dict, schema.role_show_schema(), context) return result_dict
def version_show(context, data_dict): """Show a specific version object :param version_id: the id or name of the version :type version_id: string :param dataset_id: [Optional] the id or name of a dataset. Mandatory if version name provided as version_id :type dataset_id: string :returns: the version dictionary :rtype: dict """ model = context.get('model', core_model) version_name_or_id = toolkit.get_or_bust(data_dict, ['version_id']) version = model.Session.query(Version).get(version_name_or_id) if not version: version_name = version_name_or_id dataset_name_or_id = data_dict.get('dataset_id') dataset = model.Package.get(dataset_name_or_id) if dataset: dataset_id = dataset.id version = model.Session.query(Version). \ filter(Version.package_id == dataset_id). \ filter(Version.name == version_name).one_or_none() if not version: raise toolkit.ObjectNotFound('Version not found') toolkit.check_access('version_show', context, {"package_id": version.package_id}) return version.as_dict()
def role_permission_list(context, data_dict): """ Return a list of permissions for a role. You must be a sysadmin to list role permissions. :param role_id: the id or name of the role :type role_id: string :returns: list of dicts """ log.debug("Retrieving role permission list: %r", data_dict) tk.check_access('role_permission_list', context, data_dict) session = context['session'] role_id = tk.get_or_bust(data_dict, 'role_id') role = extmodel.Role.get(role_id) if role is not None: role_id = role.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('Role'))) permissions = session.query(extmodel.Permission) \ .join(extmodel.RolePermission, and_(extmodel.Permission.content_type == extmodel.RolePermission.content_type, extmodel.Permission.operation == extmodel.RolePermission.operation)) \ .filter(extmodel.RolePermission.role_id == role_id) \ .filter(extmodel.RolePermission.state == 'active') \ .all() return dictization.permission_list_dictize(permissions, context)
def remove_indicator(self, user, indicator_id): # in case someone accidentally forgot to pass a valid user object assert user is not None, "User must be passed in order for indicator removal to work" ind = self.session.query(ProfileIndicator).get(indicator_id) if ind and user.is_admin and ind.ind_type == 'headline': self.session.delete(ind) self.remove_indicator_id_from_profiles(ind.id) if ind: if ind.is_global: # users don't actually remove global indicators, but only mark them as removed link = self.session.query(UserIndicatorLink).\ filter(and_(UserIndicatorLink.indicator_id == indicator_id, UserIndicatorLink.user_id == user.ckan_user_id)).first() if link: link.deleted = True else: if not ind in user.indicators: # regular user tries to delete someone else's indicator raise CantDeletePrivateIndicator( "The indicator you're trying to delete is not yours") # regular users can permanently delete their own indicators self.session.delete(ind) self.remove_indicator_id_from_profiles(ind.id) else: raise toolkit.ObjectNotFound("Indicator not found")
def get_dataset(dataset_id): dataset = DatasetService.get_dataset_meta(dataset_id) resource = None incs = None defaults = None meta = None if dataset: for res in dataset['resources']: if res['format'].lower() == 'csv': resource = res if res['format'].lower() == 'json' and res['name'].lower( ) == 'incsinfo': incs = res if res['format'].lower() == 'json' and res['name'].lower( ) == 'defaultinfo': defaults = res if res['format'].lower() == 'yml' and res['name'].lower( ) == 'metadata': meta = res if resource: table_name = resource['id'] if incs: incs = incs.get('url') if defaults: defaults = defaults.get('url') if meta: meta = meta.get('url') return Dataset(table_name, dataset, incs, defaults, meta) else: raise toolkit.ObjectNotFound( "There's no resource for the given dataset")
def show_datarequest_comment(context, data_dict): """ Action to retrieve a comment. Access rights will be checked before getting the comment and a NotAuthorized exception will be risen if the user is not allowed to get the comment :param id: The ID of the comment to be retrieved :type id: string :returns: A dict with the following fields: id, user_id, datarequest_id, time and comment :rtype: dict """ model = context["model"] comment_id = data_dict.get("id", "") # Check id if not comment_id: raise tk.ValidationError([tk._("Comment ID has not been included")]) # Init the data base db.init_db(model) # Check access tk.check_access(constants.SHOW_DATAREQUEST_COMMENT, context, data_dict) # Get comments result = db.Comment.get(id=comment_id) if not result: raise tk.ObjectNotFound( tk._("Comment {comment_id} not found in the data base").format( comment_id=comment_id)) return _dictize_comment(result[0])
def harvest_source_update(context, data_dict): ''' Authorization check for harvest source update It forwards the checks to package_update, which will check for organization membership, whether if sysadmin, etc according to the instance configuration. ''' model = context.get('model') user = context.get('user') source_id = data_dict['id'] pkg = model.Package.get(source_id) if not pkg: raise pt.ObjectNotFound(pt._('Harvest source not found')) context['package'] = pkg try: pt.check_access('package_update', context, data_dict) return {'success': True} except pt.NotAuthorized: return { 'success': False, 'msg': pt._( 'User {0} not authorized to update harvest source {1}').format( user, source_id) }
def jsonpatch_delete(context, data_dict): """ Delete a JSON Patch. :param id: the id of the JSON Patch to delete :type id: string """ log.info("Deleting JSON Patch: %r", data_dict) model = context['model'] user = context['user'] session = context['session'] defer_commit = context.get('defer_commit', False) jsonpatch_id = tk.get_or_bust(data_dict, 'id') jsonpatch = JSONPatch.get(jsonpatch_id) if jsonpatch is not None: jsonpatch_id = jsonpatch.id else: raise tk.ObjectNotFound('%s: %s' % (_('Not found'), _('JSON Patch'))) tk.check_access('jsonpatch_delete', context, data_dict) rev = model.repo.new_revision() rev.author = user rev.message = _(u'REST API: Delete JSON Patch %s') % jsonpatch_id jsonpatch.delete() if not defer_commit: model.repo.commit()