def test_auth_plugin_override(self): plugins.load_all(config) package_list_original = new_authz.is_authorized('package_list', {}) plugins.load('auth_plugin') assert new_authz.is_authorized('package_list', {}) != package_list_original plugins.unload('auth_plugin') assert new_authz.is_authorized('package_list', {}) == package_list_original
def test_auth_plugin_override(self): package_list_original = new_authz.is_authorized('package_list', {}) with plugins.use_plugin('auth_plugin'): assert new_authz.is_authorized('package_list', {}) != package_list_original assert new_authz.is_authorized('package_list', {}) == package_list_original
def check_access(action, context, data_dict=None): action = new_authz.clean_action_name(action) # Auth Auditing. We remove this call from the __auth_audit stack to show # we have called the auth function try: audit = context.get('__auth_audit', [])[-1] except IndexError: audit = '' if audit and audit[0] == action: context['__auth_audit'].pop() user = context.get('user') log.debug('check access - user %r, action %s' % (user, action)) if action: #if action != model.Action.READ and user in # (model.PSEUDO_USER__VISITOR, ''): # # TODO Check the API key is valid at some point too! # log.debug('Valid API key needed to make changes') # raise NotAuthorized logic_authorization = new_authz.is_authorized(action, context, data_dict) if not logic_authorization['success']: msg = logic_authorization.get('msg', '') raise NotAuthorized(msg) elif not user: msg = _('No valid API key provided.') log.debug(msg) raise NotAuthorized(msg) log.debug('Access OK.') return True
def resource_update(context, data_dict): model = context['model'] user = context.get('user') resource = logic_auth.get_resource_object(context, data_dict) # check authentication against package query = model.Session.query(model.Package)\ .join(model.ResourceGroup)\ .join(model.Resource)\ .filter(model.ResourceGroup.id == resource.resource_group_id) pkg = query.first() if not pkg: raise logic.NotFound( _('No package found for this resource, cannot check auth.') ) pkg_dict = {'id': pkg.id} authorized = new_authz.is_authorized('package_update', context, pkg_dict).get('success') if not authorized: return {'success': False, 'msg': _('User %s not authorized to edit resource %s') % (str(user), resource.id)} else: return {'success': True}
def package_update_rest(context, data_dict): model = context["model"] user = context["user"] if user in (model.PSEUDO_USER__VISITOR, ""): return {"success": False, "msg": _("Valid API key needed to edit a package")} return new_authz.is_authorized("package_update", context, data_dict)
def resource_create(context, data_dict): 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 = new_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}
def package_show(context, data_dict): user = context.get('user') package = get_package_object(context, data_dict) # draft state indicates package is still in the creation process # so we need to check we have creation rights. if package.state.startswith('draft'): auth = new_authz.is_authorized('package_update', context, data_dict) authorized = auth.get('success') elif package.owner_org is None and package.state == 'active': return {'success': True} else: # anyone can see a public package if not package.private and package.state == 'active': return {'success': True} authorized = new_authz.has_user_permission_for_group_or_org( package.owner_org, user, 'read') if not authorized: return { 'success': False, 'msg': _('User %s not authorized to read package %s') % (user, package.id) } else: return {'success': True}
def resource_show(context, data_dict): model = context['model'] user = context.get('user') resource = get_resource_object(context, data_dict) # check authentication against package pkg = model.Package.get(resource.package_id) if not pkg: raise logic.NotFound( _('No package found for this resource, cannot check auth.')) pkg_dict = {'id': pkg.id} authorized = new_authz.is_authorized('package_show', context, pkg_dict).get('success') if not authorized: return { 'success': False, 'msg': _('User %s not authorized to read resource %s') % (user, resource.id) } else: return {'success': True}
def _update_relationships(self, existing_rels, havested_rels): log.info('import_stage() : updating existing relationships ({0}) with harvested relationships ({1}).'.format(existing_rels, havested_rels)) _ctx = {'model': model, 'session': Session, 'user': self._get_user_name()} try: for _existing in existing_rels: try: ## TODO: should use toolkit.get_action(...) logic.action.delete.package_relationship_delete(_ctx, _existing.as_dict()) log.info('import_stage() . deleted relationship : {0}'.format(_existing.as_dict())) except Exception as e: log.info('import_stage().relationship : could not delete: {0}'.format(e)) except logic.NotFound as nf: # The package was not created: log.info('import_stage().relationship : could not find package: {0}'.format(nf)) except Exception as e: log.info('import_stage().relationship : exception {0}'.format(e)) for _rel in havested_rels: try: _can_create = new_authz.is_authorized('package_relationship_create', _ctx, _rel) if _can_create['success']: ## TODO: should use toolkit.get_action(...) # _r_dicts = toolkit.get_action('package_relationship_create')(_ctx, _rel) _r_dicts = logic.action.create.package_relationship_create(_ctx, _rel) log.info('import_stage() . created relationship : {0}'.format(_r_dicts)) except logic.NotFound as nf: log.info('import_stage().relationship : not found package: {0}'.format(nf)) except logic.ValidationError as ve: log.info('import_stage().relationship : validation error : {0}'.format(ve))
def resource_create(context, data_dict): # resource_create runs through package_update, no need to # check users eligibility to add resource to package here. # FIXME This is identical behaviour to what existed but feels like we # should be using package_update permissions and have better errors. I # am also not sure about the need for the group issue return new_authz.is_authorized('package_create', context, data_dict)
def package_update_rest(context, data_dict): model = context['model'] user = context['user'] if user in (model.PSEUDO_USER__VISITOR, ''): return {'success': False, 'msg': _('Valid API key needed to edit a package')} return new_authz.is_authorized('package_update', context, data_dict)
def package_delete(context, data_dict): user = context.get('user') package = logic_auth.get_package_object(context, data_dict) can_package_update = new_authz.is_authorized( 'package_update', context, {'id': package.id}) if can_package_update.get('success'): return can_package_update else: return {'success': False, 'msg': _('User %s not authorized to delete package %s') % (str(user), package.id)}
def _update_relationships(self, existing_rels, havested_rels): log.info( 'import_stage() : updating existing relationships ({0}) with harvested relationships ({1}).' .format(existing_rels, havested_rels)) _ctx = { 'model': model, 'session': Session, 'user': self._get_user_name() } try: for _existing in existing_rels: try: ## TODO: should use toolkit.get_action(...) logic.action.delete.package_relationship_delete( _ctx, _existing.as_dict()) log.info( 'import_stage() . deleted relationship : {0}'.format( _existing.as_dict())) except Exception as e: log.info( 'import_stage().relationship : could not delete: {0}'. format(e)) except logic.NotFound as nf: # The package was not created: log.info( 'import_stage().relationship : could not find package: {0}'. format(nf)) except Exception as e: log.info('import_stage().relationship : exception {0}'.format(e)) for _rel in havested_rels: try: _can_create = new_authz.is_authorized( 'package_relationship_create', _ctx, _rel) if _can_create['success']: ## TODO: should use toolkit.get_action(...) # _r_dicts = toolkit.get_action('package_relationship_create')(_ctx, _rel) _r_dicts = logic.action.create.package_relationship_create( _ctx, _rel) log.info( 'import_stage() . created relationship : {0}'.format( _r_dicts)) except logic.NotFound as nf: log.info( 'import_stage().relationship : not found package: {0}'. format(nf)) except logic.ValidationError as ve: log.info( 'import_stage().relationship : validation error : {0}'. format(ve))
def resource_show(context, data_dict): model = context['model'] user = context.get('user') resource = get_resource_object(context, data_dict) # check authentication against package pkg = model.Package.get(resource.package_id) if not pkg: raise logic.NotFound(_('No package found for this resource, cannot check auth.')) pkg_dict = {'id': pkg.id} authorized = new_authz.is_authorized('package_show', context, pkg_dict).get('success') if not authorized: return {'success': False, 'msg': _('User %s not authorized to read resource %s') % (user, resource.id)} else: return {'success': True}
def package_delete(context, data_dict): user = context.get('user') package = logic_auth.get_package_object(context, data_dict) can_package_update = new_authz.is_authorized('package_update', context, {'id': package.id}) if can_package_update.get('success'): return can_package_update else: return { 'success': False, 'msg': _('User %s not authorized to delete package %s') % (str(user), package.id) }
def package_show(context, data_dict): user = context.get("user") package = get_package_object(context, data_dict) # draft state indicates package is still in the creation process # so we need to check we have creation rights. if package.state.startswith("draft"): auth = new_authz.is_authorized("package_update", context, data_dict) authorized = auth.get("success") else: # anyone can see a public package if not package.private and package.state == "active": return {"success": True} authorized = new_authz.has_user_permission_for_group_or_org(package.owner_org, user, "read") if not authorized: return {"success": False, "msg": _("User %s not authorized to read package %s") % (user, package.id)} else: return {"success": True}
def package_show(context, data_dict): user = context.get('user') package = get_package_object(context, data_dict) # draft state indicates package is still in the creation process # so we need to check we have creation rights. if package.state.startswith('draft'): auth = new_authz.is_authorized('package_update', context, data_dict) authorized = auth.get('success') else: # anyone can see a public package if not package.private and package.state == 'active': return {'success': True} authorized = new_authz.has_user_permission_for_group_or_org( package.owner_org, user, 'read') if not authorized: return {'success': False, 'msg': _('User %s not authorized to read package %s') % (user, package.id)} else: return {'success': True}
def check_access(action, context, data_dict=None): model = context['model'] user = context.get('user') log.debug('check access - user %r, action %s' % (user,action)) if action: #if action != model.Action.READ and user in (model.PSEUDO_USER__VISITOR, ''): # # TODO Check the API key is valid at some point too! # log.debug('Valid API key needed to make changes') # raise NotAuthorized logic_authorization = is_authorized(action, context, data_dict) if not logic_authorization['success']: msg = logic_authorization.get('msg','') raise NotAuthorized(msg) elif not user: msg = _('No valid API key provided.') log.debug(msg) raise NotAuthorized(msg) log.debug('Access OK.') return True
def check_access(action, context, data_dict=None): user = context.get('user') log.debug('check access - user %r, action %s' % (user, action)) if action: #if action != model.Action.READ and user in # (model.PSEUDO_USER__VISITOR, ''): # # TODO Check the API key is valid at some point too! # log.debug('Valid API key needed to make changes') # raise NotAuthorized logic_authorization = is_authorized(action, context, data_dict) if not logic_authorization['success']: msg = logic_authorization.get('msg', '') raise NotAuthorized(msg) elif not user: msg = _('No valid API key provided.') log.debug(msg) raise NotAuthorized(msg) log.debug('Access OK.') return True
def resource_update(context, data_dict): model = context["model"] user = context.get("user") resource = logic_auth.get_resource_object(context, data_dict) # check authentication against package query = ( model.Session.query(model.Package) .join(model.ResourceGroup) .join(model.Resource) .filter(model.ResourceGroup.id == resource.resource_group_id) ) pkg = query.first() if not pkg: raise logic.NotFound(_("No package found for this resource, cannot check auth.")) pkg_dict = {"id": pkg.id} authorized = new_authz.is_authorized("package_update", context, pkg_dict).get("success") if not authorized: return {"success": False, "msg": _("User %s not authorized to edit resource %s") % (str(user), resource.id)} else: return {"success": True}
def make_latest_pending_package_active(context, data_dict): return new_authz.is_authorized('package_update', context, data_dict)
def package_relationship_update(context, data_dict): return new_authz.is_authorized('package_relationship_create', context, data_dict)
def package_create_default_resource_views(context, data_dict): return new_authz.is_authorized('package_update', context, data_dict['package'])
def dashboard_mark_activities_old(context, data_dict): return new_authz.is_authorized('dashboard_activity_list', context, data_dict)
def dashboard_new_activities_count(context, data_dict): # FIXME: This should go through check_access() not call is_authorized() # directly, but wait until 2939-orgs is merged before fixing this. # This is so a better not authourized message can be sent. return new_authz.is_authorized("dashboard_activity_list", context, data_dict)
def dashboard_new_activities_count(context, data_dict): # FIXME: This should go through check_access() not call is_authorized() # directly, but wait until 2939-orgs is merged before fixing this. # This is so a better not authourized message can be sent. return new_authz.is_authorized('dashboard_activity_list', context, data_dict)
def check_access(action, context, data_dict=None): '''Calls the authorization function for the provided action This is the only function that should be called to determine whether a user (or an anonymous request) is allowed to perform a particular action. The function accepts a context object, which should contain a 'user' key with the name of the user performing the action, and optionally a dictionary with extra data to be passed to the authorization function. For example:: check_access('package_update', context, data_dict) If not already there, the function will add an `auth_user_obj` key to the context object with the actual User object (in case it exists in the database). This check is only performed once per context object. Raise :py:exc:`~ckan.plugins.toolkit.NotAuthorized` if the user is not authorized to call the named action function. If the user *is* authorized to call the action, return ``True``. :param action: the name of the action function, eg. ``'package_create'`` :type action: string :param context: :type context: dict :param data_dict: :type data_dict: dict :raises: :py:exc:`~ckan.plugins.toolkit.NotAuthorized` if the user is not authorized to call the named action ''' action = new_authz.clean_action_name(action) # Auth Auditing. We remove this call from the __auth_audit stack to show # we have called the auth function try: audit = context.get('__auth_audit', [])[-1] except IndexError: audit = '' if audit and audit[0] == action: context['__auth_audit'].pop() user = context.get('user') log.debug('check access - user %r, action %s' % (user, action)) if not 'auth_user_obj' in context: context['auth_user_obj'] = None if not context.get('ignore_auth'): if not context.get('__auth_user_obj_checked'): if context.get('user') and not context.get('auth_user_obj'): context['auth_user_obj'] = model.User.by_name(context['user']) context['__auth_user_obj_checked'] = True context = _prepopulate_context(context) logic_authorization = new_authz.is_authorized(action, context, data_dict) if not logic_authorization['success']: msg = logic_authorization.get('msg', '') raise NotAuthorized(msg) log.debug('Access OK.') return True