From 45c31815ea3282d185bde284788baf5da1b1749d Mon Sep 17 00:00:00 2001 From: Ross Jones Date: Tue, 28 Aug 2012 15:36:58 +0100 Subject: [PATCH] Removed auth groups from tests, controller, model and logic --- ckan/authz.py | 61 +-- ckan/config/routing.py | 14 - ckan/controllers/admin.py | 147 ++---- ckan/controllers/api.py | 22 - ckan/controllers/authorization_group.py | 216 --------- ckan/forms/__init__.py | 1 - ckan/forms/authorization_group.py | 40 -- ckan/forms/authz.py | 35 +- ckan/lib/authztool.py | 32 +- ckan/lib/base.py | 56 +-- ckan/lib/cli.py | 13 +- ckan/lib/create_test_data.py | 28 +- ckan/lib/helpers.py | 16 - ckan/logic/action/__init__.py | 4 - ckan/logic/action/get.py | 19 +- ckan/logic/action/update.py | 51 +- ckan/logic/auth/__init__.py | 3 - ckan/logic/auth/create.py | 10 - ckan/logic/auth/publisher/create.py | 3 - ckan/logic/auth/publisher/update.py | 10 +- ckan/logic/auth/update.py | 24 +- .../versions/025_add_authorization_groups.py | 6 +- ckan/model/__init__.py | 10 - ckan/model/authorization_group.py | 85 ---- ckan/model/authz.py | 139 +----- ckan/plugins/interfaces.py | 5 - .../images/icons/authorization_group_add.png | Bin 807 -> 0 bytes .../images/icons/authorization_group_edit.png | Bin 785 -> 0 bytes ...{authorization_group.png => followers.png} | Bin ckan/public/scripts/application.js | 21 - ckan/templates/_util.html | 70 --- ckan/templates/admin/authz.html | 21 - .../templates/authorization_group/__init__.py | 0 ckan/templates/authorization_group/authz.html | 52 --- ckan/templates/authorization_group/edit.html | 20 - .../authorization_group/edit_form.html | 30 -- ckan/templates/authorization_group/index.html | 24 - .../templates/authorization_group/layout.html | 43 -- ckan/templates/authorization_group/new.html | 20 - ckan/templates/authorization_group/read.html | 26 -- ckan/templates/group/authz.html | 24 +- ckan/templates/package/authz.html | 24 +- ckan/templates/package/layout.html | 2 +- ckan/templates/package/new_package_form.html | 12 +- ckan/templates/user/layout.html | 6 +- ckan/tests/__init__.py | 30 +- .../ckantestplugin/ckantestplugin/__init__.py | 3 - .../api/test_authorization_group.py | 58 --- ckan/tests/functional/test_admin.py | 81 +--- .../functional/test_authorization_group.py | 440 ------------------ ckan/tests/functional/test_authz.py | 2 +- ckan/tests/functional/test_edit_authz.py | 140 +----- .../functional/test_package_edit_authz.py | 93 +--- ckan/tests/logic/test_action.py | 51 -- ckan/tests/models/test_authz.py | 46 +- ckan/tests/models/test_repo.py | 13 +- ckan/tests/test_authz.py | 119 +---- 57 files changed, 207 insertions(+), 2314 deletions(-) delete mode 100644 ckan/controllers/authorization_group.py delete mode 100644 ckan/model/authorization_group.py delete mode 100644 ckan/public/images/icons/authorization_group_add.png delete mode 100755 ckan/public/images/icons/authorization_group_edit.png rename ckan/public/images/icons/{authorization_group.png => followers.png} (100%) delete mode 100644 ckan/templates/authorization_group/__init__.py delete mode 100644 ckan/templates/authorization_group/authz.html delete mode 100644 ckan/templates/authorization_group/edit.html delete mode 100644 ckan/templates/authorization_group/edit_form.html delete mode 100644 ckan/templates/authorization_group/index.html delete mode 100644 ckan/templates/authorization_group/layout.html delete mode 100644 ckan/templates/authorization_group/new.html delete mode 100644 ckan/templates/authorization_group/read.html delete mode 100644 ckan/tests/functional/api/test_authorization_group.py delete mode 100644 ckan/tests/functional/test_authorization_group.py diff --git a/ckan/authz.py b/ckan/authz.py index cb9375e4dc4..76ca736ec5d 100644 --- a/ckan/authz.py +++ b/ckan/authz.py @@ -27,7 +27,7 @@ class Authorizer(object): ''' blacklister = Blacklister extensions = PluginImplementations(IAuthorizer) - + @classmethod def am_authorized(cls, c, action, domain_object): username = c.user or c.author @@ -36,7 +36,7 @@ def am_authorized(cls, c, action, domain_object): @classmethod def is_authorized(cls, username, action, domain_object): '''Authorize `action` by `username` on `domain_object`. - + :param username: a user identifier (may be e.g. an IP address). :param action: a ckan.model.authz.Action enumeration. :param domain_object: the domain object instance (or class/type in the @@ -47,7 +47,7 @@ def is_authorized(cls, username, action, domain_object): if isinstance(username, str): username = username.decode('utf8') assert isinstance(username, unicode), type(username) - + for extension in cls.extensions: authorized = extension.is_authorized(username, action, @@ -92,7 +92,7 @@ def get_domain_object_roles_printable(cls, domain_obj): printable_prs = [] for user, role in prs: printable_prs.append('%s - \t%s' % (user.name, role)) - return '%s roles:\n' % domain_obj.name + '\n'.join(printable_prs) + return '%s roles:\n' % domain_obj.name + '\n'.join(printable_prs) @classmethod def get_domain_object_roles(cls, domain_obj): @@ -102,29 +102,9 @@ def get_domain_object_roles(cls, domain_obj): q = model.Session.query(model.PackageRole).filter_by(package=domain_obj) elif isinstance(domain_obj, model.Group): q = model.Session.query(model.GroupRole).filter_by(group=domain_obj) - elif isinstance(domain_obj, model.AuthorizationGroup): - q = model.Session.query(model.AuthorizationGroupRole).filter_by(authorization_group=domain_obj) prs = [ (pr.user, pr.role) for pr in q.all() ] return prs - @classmethod - def get_authorization_groups(cls, username): - q = model.Session.query(model.AuthorizationGroup) - q = q.autoflush(False) - user = model.User.by_name(username, autoflush=False) - if username == model.PSEUDO_USER__VISITOR or not user: - q = q.filter(model.AuthorizationGroup.users.any(name=model.PSEUDO_USER__VISITOR)) - else: - q = q.filter(model.AuthorizationGroup.users.any( - sa.or_(model.User.name==model.PSEUDO_USER__VISITOR, - model.User.name==model.PSEUDO_USER__LOGGED_IN, - model.User.name==username))) - - groups = q.all() - for extension in cls.extensions: - extra_groups = extension.get_authorization_groups(username) - groups.extend(extra_groups) - return groups @classmethod def get_roles(cls, username, domain_obj): @@ -134,25 +114,22 @@ def get_roles(cls, username, domain_obj): assert isinstance(username, unicode), repr(username) # filter by user and pseudo-users - # TODO: these can be made into subqueries/joins! + # TODO: these can be made into subqueries/joins! user = model.User.by_name(username, autoflush=False) visitor = model.User.by_name(model.PSEUDO_USER__VISITOR, autoflush=False) q = cls._get_roles_query(domain_obj) q = q.autoflush(False) - + filters = [model.UserObjectRole.user==visitor] - # check for groups: - for authz_group in cls.get_authorization_groups(username): - filters.append(model.UserObjectRole.authorized_group==authz_group) - + if (username != model.PSEUDO_USER__VISITOR) and (user is not None): logged_in = model.User.by_name(model.PSEUDO_USER__LOGGED_IN) filters.append(model.UserObjectRole.user==user) filters.append(model.UserObjectRole.user==logged_in) - + q = q.filter(sa.or_(*filters)) return [pr.role for pr in q] - + @classmethod def is_sysadmin(cls, user): '''Returns whether the given user a sys-admin? @@ -180,9 +157,6 @@ def get_admins(cls, domain_obj): elif isinstance(domain_obj, model.Group): q = model.Session.query(model.GroupRole).filter_by(group=domain_obj, role=model.Role.ADMIN) - elif isinstance(domain_obj, model.AuthorizationGroup): - q = model.Session.query(model.AuthorizationGroupRole).filter_by(authorization_group=domain_obj, - role=model.Role.ADMIN) q = q.autoflush(False) admins = [do_role.user for do_role in q.all() if do_role.user] return admins @@ -202,24 +176,22 @@ def authorized_query(cls, username, entity, action=model.Action.READ): # This gets the role table the entity is joined to. we # need to use this in the queries below as if we use # model.UserObjectRole a cross join happens always - # returning all the roles. + # returning all the roles. if hasattr(entity, 'continuity'): q = q.filter_by(current=True) q = q.outerjoin('continuity', 'roles') continuity = entity.continuity.property.mapper.class_ - role_cls = continuity.roles.property.mapper.class_ + role_cls = continuity.roles.property.mapper.class_ else: - role_cls = entity.roles.property.mapper.class_ + role_cls = entity.roles.property.mapper.class_ q = q.outerjoin('roles') if hasattr(entity, 'state'): state = entity.state else: state = None - + filters = [model.UserObjectRole.user==visitor] - for authz_group in cls.get_authorization_groups(username): - filters.append(role_cls.authorized_group==authz_group) if user: filters.append(role_cls.user==user) filters.append(role_cls.user==logged_in) @@ -234,7 +206,7 @@ def authorized_query(cls, username, entity, action=model.Action.READ): model.RoleAction.action==action, state and state!=model.State.DELETED), ) - q = q.filter(sa.or_(*filters)) + q = q.filter(sa.or_(*filters)) q = q.distinct() return q @@ -282,9 +254,6 @@ def _get_roles_query(cls, domain_obj): elif isinstance(domain_obj, model.Group): q = q.with_polymorphic(model.GroupRole) q = q.filter(model.GroupRole.group==domain_obj) - elif isinstance(domain_obj, model.AuthorizationGroup): - q = q.with_polymorphic(model.AuthorizationGroupRole) - q = q.filter(model.AuthorizationGroupRole.authorization_group==domain_obj) elif isinstance(domain_obj, model.System): q = q.with_polymorphic(model.SystemRole) q = q.filter(model.SystemRole.context==unicode(model.System.__name__)) @@ -295,4 +264,4 @@ def _get_roles_query(cls, domain_obj): q = q.filter_by(context=unicode(context)) return q - + diff --git a/ckan/config/routing.py b/ckan/config/routing.py index a2ab58634b0..fe81fed83c4 100644 --- a/ckan/config/routing.py +++ b/ckan/config/routing.py @@ -58,7 +58,6 @@ def make_map(): 'tag', 'group', 'related', - 'authorizationgroup', 'revision', 'licenses', 'rating', @@ -119,8 +118,6 @@ def make_map(): action='format_autocomplete', conditions=GET) m.connect('/util/resource/format_icon', action='format_icon', conditions=GET) - m.connect('/util/authorizationgroup/autocomplete', - action='authorizationgroup_autocomplete') m.connect('/util/group/autocomplete', action='group_autocomplete') m.connect('/util/markdown', action='markdown') m.connect('/util/dataset/munge_name', action='munge_package_name') @@ -229,17 +226,6 @@ def make_map(): register_package_plugins(map) register_group_plugins(map) - # authz group - map.redirect('/authorizationgroups', '/authorizationgroup') - map.redirect('/authorizationgroups/{url:.*}', '/authorizationgroup/{url}') - with SubMapper(map, controller='authorization_group') as m: - m.connect('/authorizationgroup', action='index') - m.connect('/authorizationgroup/list', action='list') - m.connect('/authorizationgroup/new', action='new') - m.connect('/authorizationgroup/edit/{id}', action='edit') - m.connect('/authorizationgroup/authz/{id}', action='authz') - m.connect('/authorizationgroup/{id}', action='read') - # tags map.redirect('/tags', '/tag') map.redirect('/tags/{url:.*}', '/tag/{url}') diff --git a/ckan/controllers/admin.py b/ckan/controllers/admin.py index 1c14b351939..a7bf8aee2a6 100644 --- a/ckan/controllers/admin.py +++ b/ckan/controllers/admin.py @@ -30,7 +30,7 @@ def index(self): return render('admin/index.html') def authz(self): - def action_save_form(users_or_authz_groups): + def action_save_form(users): # The permissions grid has been saved # which is a grid of checkboxes named user$role rpi = request.params.items() @@ -59,17 +59,9 @@ def action_save_form(users_or_authz_groups): # we get the current user/role assignments # and make a dictionary of them current_uors = model.Session.query(model.SystemRole).all() - - if users_or_authz_groups == 'users': - current_users_roles = [(uor.user.name, uor.role) - for uor in current_uors - if uor.user] - elif users_or_authz_groups == 'authz_groups': - current_users_roles = [(uor.authorized_group.name, uor.role) - for uor in current_uors - if uor.authorized_group] - else: - assert False, "shouldn't be here" + current_users_roles = [(uor.user.name, uor.role) + for uor in current_uors + if uor.user] current_user_role_dict = {} for (u, r) in current_users_roles: @@ -85,32 +77,18 @@ def action_save_form(users_or_authz_groups): # which would seem to be prone to suffer the same effect. Why # the difference? - if users_or_authz_groups == 'users': - for ((u, r), val) in new_user_role_dict.items(): - if val: - if not ((u, r) in current_user_role_dict): - model.add_user_to_role( - model.User.by_name(u), r, - model.System()) - else: - if ((u, r) in current_user_role_dict): - model.remove_user_from_role( - model.User.by_name(u), r, - model.System()) - elif users_or_authz_groups == 'authz_groups': - for ((u, r), val) in new_user_role_dict.items(): - if val: - if not ((u, r) in current_user_role_dict): - model.add_authorization_group_to_role( - model.AuthorizationGroup.by_name(u), r, - model.System()) - else: - if ((u, r) in current_user_role_dict): - model.remove_authorization_group_from_role( - model.AuthorizationGroup.by_name(u), r, - model.System()) - else: - assert False, "shouldn't be here" + + for ((u, r), val) in new_user_role_dict.items(): + if val: + if not ((u, r) in current_user_role_dict): + model.add_user_to_role( + model.User.by_name(u), r, + model.System()) + else: + if ((u, r) in current_user_role_dict): + model.remove_user_from_role( + model.User.by_name(u), r, + model.System()) # finally commit the change to the database model.Session.commit() @@ -119,10 +97,7 @@ def action_save_form(users_or_authz_groups): if ('save' in request.POST): action_save_form('users') - if ('authz_save' in request.POST): - action_save_form('authz_groups') - - def action_add_form(users_or_authz_groups): + def action_add_form(users): # The user is attempting to set new roles for a named user new_user = request.params.get('new_user_name') # this is the list of roles whose boxes were ticked @@ -147,62 +122,33 @@ def action_add_form(users_or_authz_groups): current_uors = model.Session.query(model.SystemRole).all() - if users_or_authz_groups == 'users': - current_roles = [uor.role for uor in current_uors - if (uor.user and uor.user.name == new_user)] - user_object = model.User.by_name(new_user) - if user_object is None: - # The submitted user does not exist. Bail with flash - # message - h.flash_error(_('unknown user:') + str(new_user)) - else: - # Whenever our desired state is different from our - # current state, change it. - for (r, val) in desired_roles.items(): - if val: - if (r not in current_roles): - model.add_user_to_role(user_object, r, - model.System()) - else: - if (r in current_roles): - model.remove_user_from_role(user_object, r, - model.System()) - h.flash_success(_("User Added")) - - elif users_or_authz_groups == 'authz_groups': - current_roles = [uor.role for uor in current_uors - if (uor.authorized_group and - uor.authorized_group.name == new_user)] - user_object = model.AuthorizationGroup.by_name(new_user) - if user_object is None: - # The submitted user does not exist. Bail with flash - # message - h.flash_error(_('unknown authorization group:') + - str(new_user)) - else: - # Whenever our desired state is different from our - # current state, change it. - for (r, val) in desired_roles.items(): - if val: - if (r not in current_roles): - model.add_authorization_group_to_role( - user_object, r, model.System()) - else: - if (r in current_roles): - model.remove_authorization_group_from_role( - user_object, r, model.System()) - h.flash_success(_("Authorization Group Added")) + current_roles = [uor.role for uor in current_uors + if (uor.user and uor.user.name == new_user)] + user_object = model.User.by_name(new_user) + if user_object is None: + # The submitted user does not exist. Bail with flash + # message + h.flash_error(_('unknown user:') + str(new_user)) else: - assert False, "shouldn't be here" + # Whenever our desired state is different from our + # current state, change it. + for (r, val) in desired_roles.items(): + if val: + if (r not in current_roles): + model.add_user_to_role(user_object, r, + model.System()) + else: + if (r in current_roles): + model.remove_user_from_role(user_object, r, + model.System()) + h.flash_success(_("User Added")) # and finally commit all these changes to the database model.Session.commit() if 'add' in request.POST: action_add_form('users') - if 'authz_add' in request.POST: - action_add_form('authz_groups') # ================= # Display the page @@ -214,10 +160,7 @@ def action_add_form(users_or_authz_groups): uors = model.Session.query(model.SystemRole).all() # uniquify and sort users = sorted(list(set([uor.user.name for uor in uors if uor.user]))) - authz_groups = sorted(list(set([uor.authorized_group.name - for uor in uors if uor.authorized_group]))) - # make a dictionary from (user, role) to True, False users_roles = [(uor.user.name, uor.role) for uor in uors if uor.user] user_role_dict = {} for u in users: @@ -227,30 +170,12 @@ def action_add_form(users_or_authz_groups): else: user_role_dict[(u, r)] = False - # and similarly make a dictionary from (authz_group, role) to - # True, False - authz_groups_roles = [(uor.authorized_group.name, uor.role) - for uor in uors if uor.authorized_group] - authz_groups_role_dict = {} - for u in authz_groups: - for r in possible_roles: - if (u, r) in authz_groups_roles: - authz_groups_role_dict[(u, r)] = True - else: - authz_groups_role_dict[(u, r)] = False # pass these variables to the template for rendering c.roles = possible_roles - c.users = users c.user_role_dict = user_role_dict - c.authz_groups = authz_groups - c.authz_groups_role_dict = authz_groups_role_dict - - count = model.Session.query(model.AuthorizationGroup).count() - c.are_any_authz_groups = bool(count) - return render('admin/authz.html') def trash(self): diff --git a/ckan/controllers/api.py b/ckan/controllers/api.py index 66754fdb1f2..4d5905bc1b7 100644 --- a/ckan/controllers/api.py +++ b/ckan/controllers/api.py @@ -631,28 +631,6 @@ def convert_to_dict(user): out = map(convert_to_dict, query.all()) return out - @jsonp.jsonpify - def authorizationgroup_autocomplete(self): - q = request.params.get('q', '') - limit = request.params.get('limit', 20) - try: - limit = int(limit) - except: - limit = 20 - limit = min(50, limit) - - query = model.AuthorizationGroup.search(q) - - def convert_to_dict(user): - out = {} - for k in ['id', 'name']: - out[k] = getattr(user, k) - return out - - query = query.limit(limit) - out = map(convert_to_dict, query.all()) - return out - def is_slug_valid(self): slug = request.params.get('slug') or '' slugtype = request.params.get('type') or '' diff --git a/ckan/controllers/authorization_group.py b/ckan/controllers/authorization_group.py deleted file mode 100644 index e1b4b846ac2..00000000000 --- a/ckan/controllers/authorization_group.py +++ /dev/null @@ -1,216 +0,0 @@ -import genshi - -from sqlalchemy.orm import eagerload_all -from ckan.lib.base import * -from pylons.i18n import get_lang, _ -import ckan.authz as authz -import ckan.forms -from ckan.lib.helpers import Page -from ckan.logic import NotAuthorized, check_access - - -class AuthorizationGroupController(BaseController): - - def __init__(self): - BaseController.__init__(self) - - def index(self): - from ckan.lib.helpers import Page - try: - context = {'model': model, 'user': c.user or c.author} - check_access('site_read', context) - except NotAuthorized: - abort(401, _('Not authorized to see this page')) - - query = ckan.authz.Authorizer().authorized_query( - c.user, model.AuthorizationGroup) - query = query.options(eagerload_all('users')) - c.page = Page( - collection=query, - page=request.params.get('page', 1), - items_per_page=20 - ) - return render('authorization_group/index.html') - - def _get_authgroup_by_name_or_id(self, id): - return model.AuthorizationGroup.by_name(id) or\ - model.Session.query(model.AuthorizationGroup).get(id) - - def read(self, id): - c.authorization_group = self._get_authgroup_by_name_or_id(id) - if c.authorization_group is None: - abort(404) - auth_for_read = self.authorizer.am_authorized(c, model.Action.READ, - c.authorization_group) - if not auth_for_read: - abort(401, _('Not authorized to read %s') % id.encode('utf8')) - - import ckan.misc - c.authorization_group_admins = self.authorizer.get_admins( - c.authorization_group) - - c.page = Page( - collection=c.authorization_group.users, - page=request.params.get('page', 1), - items_per_page=50 - ) - return render('authorization_group/read.html') - - def new(self): - record = model.AuthorizationGroup - c.error = '' - - auth_for_create = self.authorizer.am_authorized( - c, model.Action.AUTHZ_GROUP_CREATE, model.System()) - if not auth_for_create: - abort(401, _('Unauthorized to create a group')) - - is_admin = self.authorizer.is_sysadmin(c.user) - - fs = ckan.forms.get_authorization_group_fieldset(is_admin=is_admin) - - if 'save' in request.params: - # needed because request is nested - # multidict which is read only - params = dict(request.params) - c.fs = fs.bind(record, data=params or None, session=model.Session) - try: - self._update(c.fs, id, record.id) - except ValidationException, error: - fs = error.args[0] - c.form = self._render_edit_form(fs) - return render('authorization_group/edit.html') - # do not use groupname from id as may have changed - c.authzgroupname = c.fs.name.value - authorization_group = model.AuthorizationGroup.by_name( - c.authzgroupname) - assert authorization_group - user = model.User.by_name(c.user) - model.setup_default_user_roles(authorization_group, [user]) - users = [model.User.by_name(name) for name in - request.params.getall('AuthorizationGroup-users-current')] - authorization_group.users = list(set(users)) - usernames = request.params.getall( - 'AuthorizationGroupUser--user_name') - for username in usernames: - if username: - usr = model.User.by_name(username) - if usr and usr not in authorization_group.users: - model.add_user_to_authorization_group( - usr, authorization_group, model.Role.READER) - model.repo.commit_and_remove() - h.redirect_to(controller='authorization_group', action='read', - id=c.authzgroupname) - - c.form = self._render_edit_form(fs) - return render('authorization_group/new.html') - - def edit(self, id=None): - # allow id=None to allow posting - c.error = '' - authorization_group = self._get_authgroup_by_name_or_id(id) - if authorization_group is None: - abort(404, '404 Not Found') - am_authz = self.authorizer.am_authorized(c, model.Action.EDIT, - authorization_group) - if not am_authz: - abort(401, _('User %r not authorized to edit %r') % (c.user, id)) - - is_admin = self.authorizer.is_sysadmin(c.user) - - if not 'save' in request.params: - c.authorization_group = authorization_group - c.authorization_group_name = authorization_group.name - - fs = ckan.forms.get_authorization_group_fieldset( - is_admin=is_admin).bind(authorization_group) - c.form = self._render_edit_form(fs) - return render('authorization_group/edit.html') - else: - # id is the name (pre-edited state) - c.authorization_group_name = id - # needed because request is nested - # multidict which is read only - params = dict(request.params) - c.fs = ckan.forms.get_authorization_group_fieldset()\ - .bind(authorization_group, data=params or None) - try: - self._update(c.fs, id, authorization_group.id) - # do not use groupname from id as may have changed - c.authorization_group = authorization_group - c.authorization_group_name = authorization_group.name - except ValidationException, error: - fs = error.args[0] - c.form = self._render_edit_form(fs) - return render('authorization_group/edit.html') - user = model.User.by_name(c.user) - users = [model.User.by_name(name) for name in - request.params.getall('AuthorizationGroup-users-current')] - authorization_group.users = list(set(users)) - usernames = request.params.\ - getall('AuthorizationGroupUser--user_name') - for username in usernames: - if username: - usr = model.User.by_name(username) - if usr and usr not in authorization_group.users: - model.add_user_to_authorization_group( - usr, authorization_group, model.Role.READER) - model.repo.commit_and_remove() - h.redirect_to(controller='authorization_group', action='read', - id=c.authorization_group_name) - - def authz(self, id): - authorization_group = self._get_authgroup_by_name_or_id(id) - if authorization_group is None: - abort(404, _('Group not found')) - - c.authorization_group_name = authorization_group.name - c.authorization_group = authorization_group - - c.authz_editable = self.authorizer.am_authorized( - c, model.Action.EDIT_PERMISSIONS, authorization_group) - if not c.authz_editable: - abort(401, - gettext('User %r not authorized to edit %s authorizations') - % (c.user, id)) - - roles = self._handle_update_of_authz(authorization_group) - self._prepare_authz_info_for_render(roles) - return render('authorization_group/authz.html') - - def _render_edit_form(self, fs): - # errors arrive in c.error and fs.errors - c.fieldset = fs - c.fieldset2 = ckan.forms.get_authorization_group_user_fieldset() - return render('authorization_group/edit_form.html') - - def _update(self, fs, group_name, group_id): - ''' - Writes the POST data (associated with a group edit) to the database - @input c.error - ''' - validation = fs.validate() - if not validation: - c.form = self._render_edit_form(fs) - raise ValidationException(fs) - - try: - fs.sync() - except Exception, inst: - model.Session.rollback() - raise - else: - model.Session.commit() - - def _update_authz(self, fs): - validation = fs.validate() - if not validation: - c.form = self._render_edit_form(fs) - raise ValidationException(fs) - try: - fs.sync() - except Exception, inst: - model.Session.rollback() - raise - else: - model.Session.commit() diff --git a/ckan/forms/__init__.py b/ckan/forms/__init__.py index 729444b4387..40fc11e37d3 100644 --- a/ckan/forms/__init__.py +++ b/ckan/forms/__init__.py @@ -1,6 +1,5 @@ from package import * from group import * -from authorization_group import * from registry import * from authz import * from package_dict import * diff --git a/ckan/forms/authorization_group.py b/ckan/forms/authorization_group.py index a8df69e4c4c..702fc44c3af 100644 --- a/ckan/forms/authorization_group.py +++ b/ckan/forms/authorization_group.py @@ -40,44 +40,4 @@ def render(self, **kwargs): html = fa_h.text_field(self.name, **kwargs) return html -def build_authorization_group_form(is_admin=False, with_users=False): - builder = FormBuilder(model.AuthorizationGroup) - builder.set_field_text('name', _('Name'), literal( - '
' + _("Unique identifier for group.") + - '
' + _("2+ characters, lowercase, using only 'a-z0-9' and '-_'") - )) - builder.set_field_option('name', 'validate', common.group_name_validator) - builder.set_field_option('name', 'required') - displayed_fields = ['name'] - if with_users: - builder.add_field(UsersField('users')) - displayed_fields.append('users') - builder.set_displayed_fields(OrderedDict([(_('Details'), displayed_fields)])) - builder.set_label_prettifier(common.prettify) - return builder - fieldsets = {} - -def get_authorization_group_fieldset(combined=False, is_admin=False): - if not 'authz_group_fs' in fieldsets: - # group_fs has no packages - first half of the WUI form - fieldsets['authz_group_fs'] = build_authorization_group_form(is_admin=is_admin)\ - .get_fieldset() - - # group_fs_combined has packages - used for REST interface - fieldsets['authz_group_fs_combined'] = build_authorization_group_form( - is_admin=is_admin, - with_users=True).get_fieldset() - if combined: - return fieldsets['authz_group_fs_combined'] - return fieldsets['authz_group_fs'] - -def get_authorization_group_user_fieldset(): - if not 'new_user_authz_group_fs' in fieldsets: - builder = FormBuilder(model.AuthorizationGroupUser) - builder.add_field(UserNameField('user_name')) - builder.set_field_option('user_name', 'with_renderer', UsersRenderer) - builder.set_displayed_fields({_('Add users'):['user_name']}, focus_field=False) - fieldsets['new_user_authz_group_fs'] = builder.get_fieldset() - return fieldsets['new_user_authz_group_fs'] - diff --git a/ckan/forms/authz.py b/ckan/forms/authz.py index ac7c512d4fa..7f1eb0a0935 100644 --- a/ckan/forms/authz.py +++ b/ckan/forms/authz.py @@ -30,15 +30,6 @@ def get_group_linker(action): action, action) -def get_authorization_group_linker(action): - return lambda item: '%s' % ( - ckan_h.url_for(controller='authorization_group', - action='authz', - id=item.authorization_group.name, - role_to_delete=item.id), - action, - action) - class RolesRenderer(formalchemy.fields.FieldRenderer): def render(self, **kwargs): selected = kwargs.get('selected', None) or unicode(self.value) @@ -58,29 +49,20 @@ def authz_fieldset_builder(role_class): fs.append( Field(u'delete', types.String, get_group_linker(u'delete')).readonly() ) - elif role_class == model.AuthorizationGroupRole: - fs.append( - Field(u'delete', types.String, get_authorization_group_linker(u'delete')).readonly() - ) - + fs.append( # use getattr because though we should always have a user name, # sometimes (due to error) we don't and want to avoid a 500 ... Field(u'username', types.String, lambda item: ckan_h.linked_user(getattr(item.user, 'name', ''))).readonly() ) - - fs.append( - Field(u'authzgroupname', types.String, - lambda item: getattr(item.authorized_group, 'name', '')).readonly() - ) + fs.configure( options = [ fs.role.with_renderer(RolesRenderer), ], include=[fs.username, - fs.authzgroupname, fs.role, fs.delete], ) @@ -92,24 +74,16 @@ def render(self, options, **kwargs): selected = None return fa_h.select(self.name, selected, options, **kwargs) -class AuthorizationGroupsRenderer(formalchemy.fields.FieldRenderer): - def render(self, options, **kwargs): - options = [('', '__null_value__')] + [(u.name, u.id) for u in model.Session.query(model.AuthorizationGroup).all()] - selected = None - return fa_h.select(self.name, selected, options, **kwargs) - def get_new_role_fieldset(role_class): fs = fa.FieldSet(role_class, session=model.Session) role_options = model.Role.get_all() fs.configure( include=[ fs.user, - fs.authorized_group, fs.role ], options = [ fs.user.with_renderer(UsersRenderer), - fs.authorized_group.with_renderer(AuthorizationGroupsRenderer), fs.role.dropdown(options=role_options) ], ) @@ -118,12 +92,9 @@ def get_new_role_fieldset(role_class): fieldsets = {} def get_authz_fieldset(name): - if not fieldsets: + if not fieldsets: fieldsets['package_authz_fs'] = authz_fieldset_builder(model.PackageRole) fieldsets['group_authz_fs'] = authz_fieldset_builder(model.GroupRole) - fieldsets['authorization_group_authz_fs'] = authz_fieldset_builder(model.AuthorizationGroupRole) fieldsets['new_package_roles_fs'] = get_new_role_fieldset(model.PackageRole) fieldsets['new_group_roles_fs'] = get_new_role_fieldset(model.GroupRole) - fieldsets['new_authorization_group_roles_fs'] = \ - get_new_role_fieldset(model.AuthorizationGroupRole) return fieldsets[name] diff --git a/ckan/lib/authztool.py b/ckan/lib/authztool.py index 317d34e3307..5003dbd653f 100644 --- a/ckan/lib/authztool.py +++ b/ckan/lib/authztool.py @@ -30,14 +30,10 @@ def make_or_remove_roles(cls, cmd, subj, role, obj, except_on_error=False, do_co if cmd == 'make': if isinstance(subj, model.User): model.add_user_to_role(subj, role, obj) - elif isinstance(subj, model.AuthorizationGroup): - model.add_authorization_group_to_role(subj, role, obj) log.debug('Role made') elif cmd == 'remove': if isinstance(subj, model.User): model.remove_user_from_role(subj, role, obj) - elif isinstance(subj, model.AuthorizationGroup): - model.remove_authorization_group_from_role(subj, role, obj) log.debug('Role removed') else: raise NotImplementedError @@ -49,7 +45,7 @@ def make_or_remove_roles(cls, cmd, subj, role, obj, except_on_error=False, do_co exists=(cmd=='make'))) if do_commit: model.repo.commit_and_remove() - + @classmethod def find_subject(cls, subject): '''Given a name of a system object that could be the subject @@ -58,8 +54,7 @@ def find_subject(cls, subject): _type, name = 'user', subject if ':' in subject and not subject.lower().startswith('http'): _type, name = subject.split(':', 1) - finder = {'agroup': model.AuthorizationGroup.by_name, - 'user': model.User.by_name}.get(_type) + finder = {'user': model.User.by_name}.get(_type) assert finder is not None, "No such subject type: %s" % _type subj = finder(name) assert subj is not None, "No such %s: %s" % (_type, name) @@ -78,7 +73,6 @@ def find_objects(cls, obj): obj_class = { 'package': model.Package, 'group': model.Group, - 'agroup': model.AuthorizationGroup, 'system': model.System, }.get(_type) if name == 'all': @@ -95,7 +89,7 @@ def find_objects(cls, obj): def ensure_role(role): from ckan import model roles = model.Role.get_all() - assert role in roles, "Role %s does not exist: %s" % (role, + assert role in roles, "Role %s does not exist: %s" % (role, ", ".join(roles)) return role @@ -128,10 +122,10 @@ def usage(self): agroup:editors - An authorization group called 'editors' visitor - All web site visitors logged_in - All users that are logged in - + Roles: %(roles)s - + Objects (prefix defaults to 'package:'): package:datablob - A package called 'datablob' package:all - All packages @@ -140,7 +134,7 @@ def usage(self): system: - The entire system (relevant to entity creation) ''' % dict(roles=", ".join(model.Role.get_all())) return RIGHTS_HELP - + def command(self): self._load_config() @@ -151,14 +145,14 @@ def command(self): del args[args.index('list')] self.list(args) return - + assert len(self.args) == 4, "Not enough parameters!" + RIGHTS_HELP cmd, subj, role, obj = self.args RightsTool.make_or_remove_roles(cmd, subj, role, obj, except_on_error=False) def _filter_query(self, query, args): - from ckan import model + from ckan import model for arg in self.args: arg = unicode(arg) for interpret_func, column_name in ((RightsTool.ensure_role, 'role'), @@ -172,8 +166,6 @@ def _filter_query(self, query, args): if column_name == 'user': if isinstance(filter_by_obj, model.User): column_name = 'user' - elif isinstance(filter_by_obj, model.AuthorizationGroup): - column_name = 'authorized_group' else: raise NotImplementedError if column_name == 'object': @@ -216,7 +208,7 @@ def list(self, args): else: obj = model.System() print RightsTool.get_printable_row( - uor.user if uor.user else uor.authorized_group, + uor.user if uor.user else '', uor.role, obj) @@ -241,7 +233,7 @@ def usage(self): %(actions)s ''' % dict(actions=", ".join(model.Action.get_all())) return ROLES_HELP - + def command(self): from ckan import model self._load_config() @@ -255,7 +247,7 @@ def command(self): for role, actions in roles.items(): print "%-20s%s" % (role, ", ".join(actions)) return - + assert len(self.args) == 3, "Not enough paramters!" + ROLES_HELP cmd, role, action = self.args q = model.Session.query(model.RoleAction) @@ -271,4 +263,4 @@ def command(self): model.Session.delete(role_action) print 'Successful: %s %s %s' % (cmd, role, action) model.repo.commit_and_remove() - + diff --git a/ckan/lib/base.py b/ckan/lib/base.py index b521b3cbeab..c9872eea322 100644 --- a/ckan/lib/base.py +++ b/ckan/lib/base.py @@ -473,20 +473,13 @@ def _handle_update_of_authz(self, domain_object): data_dict = {'domain_object': domain_object.id} # Work out actions needed, depending on which button was pressed + update_type = 'user' if 'save' in request.POST: - user_or_authgroup = 'user' update_or_add = 'update' elif 'add' in request.POST: - user_or_authgroup = 'user' - update_or_add = 'add' - elif 'authz_save' in request.POST: - user_or_authgroup = 'authorization_group' - update_or_add = 'update' - elif 'authz_add' in request.POST: - user_or_authgroup = 'authorization_group' update_or_add = 'add' else: - user_or_authgroup = None + update_type = None update_or_add = None # Work out what role checkboxes are checked or unchecked @@ -500,20 +493,20 @@ def _handle_update_of_authz(self, domain_object): # Get user_roles by decoding the checkbox grid - user$role strings user_roles = {} for checked_role in checked_roles: - user_or_authgroup_id, role = checked_role.split('$') - if user_or_authgroup_id not in user_roles: - user_roles[user_or_authgroup_id] = [] - user_roles[user_or_authgroup_id].append(role) + obj_id, role = checked_role.split('$') + if obj_id not in user_roles: + user_roles[obj_id] = [] + user_roles[obj_id].append(role) # Users without roles need adding to the user_roles too to make # their roles be deleted for unchecked_role in unchecked_roles: - user_or_authgroup_id, role = unchecked_role.split('$') - if user_or_authgroup_id not in user_roles: - user_roles[user_or_authgroup_id] = [] + obj_id, role = unchecked_role.split('$') + if obj_id not in user_roles: + user_roles[obj_id] = [] # Convert user_roles to role dictionaries role_dicts = [] for user, roles in user_roles.items(): - role_dicts.append({user_or_authgroup: user, 'roles': roles}) + role_dicts.append({update_type: user, 'roles': roles}) data_dict['user_roles'] = role_dicts action = 'user_role_bulk_update' @@ -522,11 +515,10 @@ def _handle_update_of_authz(self, domain_object): # Roles for this new user is a simple list from the checkbox row data_dict['roles'] = checked_roles - # User (or "user group" aka AuthorizationGroup) comes from - # the input box. + # User comes from the input box. new_user = request.params.get('new_user_name') if new_user: - data_dict[user_or_authgroup] = new_user + data_dict[update_type] = new_user action = 'user_role_update' success_message = _('User role(s) added') @@ -543,8 +535,8 @@ def _handle_update_of_authz(self, domain_object): # Return roles for all users on this domain object if update_or_add is 'add': - if user_or_authgroup in data_dict: - del data_dict[user_or_authgroup] + if update_type in data_dict: + del data_dict[update_type] return get_action('roles_show')(context, data_dict) def _prepare_authz_info_for_render(self, user_object_roles): @@ -559,9 +551,6 @@ def _prepare_authz_info_for_render(self, user_object_roles): users = sorted(list(set([uor['user_id'] for uor in user_object_roles['roles'] if uor['user_id']]))) - authz_groups = sorted(list(set([uor['authorized_group_id'] - for uor in user_object_roles['roles'] - if uor['authorized_group_id']]))) # make a dictionary from (user, role) to True, False users_roles = [(uor['user_id'], uor['role']) @@ -572,26 +561,9 @@ def _prepare_authz_info_for_render(self, user_object_roles): for r in possible_roles: user_role_dict[(u, r)] = (u, r) in users_roles - # and similarly make a dictionary from (authz_group, role) to True - # , False - authz_groups_roles = [(uor['authorized_group_id'], uor['role']) - for uor in user_object_roles['roles'] - if uor['authorized_group_id']] - authz_groups_role_dict = {} - for u in authz_groups: - for r in possible_roles: - if (u, r) in authz_groups_roles: - authz_groups_role_dict[(u, r)] = True - else: - authz_groups_role_dict[(u, r)] = False - c.roles = possible_roles c.users = users c.user_role_dict = user_role_dict - c.authz_groups = authz_groups - c.authz_groups_role_dict = authz_groups_role_dict - c.are_any_authz_groups = bool(model.Session.query( - model.AuthorizationGroup).count()) # Include the '_' function in the public names __all__ = [__name for __name in locals().keys() if not __name.startswith('_') diff --git a/ckan/lib/cli.py b/ckan/lib/cli.py index 11272281628..c20296b3517 100644 --- a/ckan/lib/cli.py +++ b/ckan/lib/cli.py @@ -492,11 +492,10 @@ def list(self): sysadmins = model.Session.query(model.SystemRole).filter_by(role=model.Role.ADMIN) print 'count = %i' % sysadmins.count() for sysadmin in sysadmins: - user_or_authgroup = sysadmin.user or sysadmin.authorized_group - assert user_or_authgroup, 'Could not extract entity with this priviledge from: %r' % sysadmin - print '%s name=%s id=%s' % (user_or_authgroup.__class__.__name__, - user_or_authgroup.name, - user_or_authgroup.id) + assert sysadmin.user, 'Could not extract entity with this priviledge from: %r' % sysadmin + print '%s name=%s id=%s' % (sysadmin.user.__class__.__name__, + sysadmin.user.name, + sysadmin.user.id) def add(self): import ckan.model as model @@ -1212,7 +1211,7 @@ def command(self): import paste.fixture import cProfile import re - + url = self.args[0] def profile_url(url): @@ -1226,7 +1225,7 @@ def profile_url(url): import traceback traceback.print_exc() print 'Unknown error: ', url.strip() - + output_filename = 'ckan%s.profile' % re.sub('[/?]', '.', url.replace('/', '.')) profile_command = "profile_url('%s')" % url cProfile.runctx(profile_command, globals(), locals(), filename=output_filename) diff --git a/ckan/lib/create_test_data.py b/ckan/lib/create_test_data.py index b25d2bbe615..25cb4fd9e0e 100644 --- a/ckan/lib/create_test_data.py +++ b/ckan/lib/create_test_data.py @@ -8,7 +8,7 @@ log = logging.getLogger(__name__) class CreateTestData(object): - # keep track of the objects created by this class so that + # keep track of the objects created by this class so that # tests can easy call delete() method to delete them all again. pkg_names = [] tag_names = [] @@ -488,28 +488,6 @@ def create(cls, auth_profile="", package_type=None): model.repo.commit_and_remove() - # Create a couple of authorization groups - for ag_name in [u'anauthzgroup', u'anotherauthzgroup']: - ag=model.AuthorizationGroup.by_name(ag_name) - if not ag: #may already exist, if not create - ag=model.AuthorizationGroup(name=ag_name) - model.Session.add(ag) - - model.repo.commit_and_remove() - - # and give them a range of roles on various things - ag = model.AuthorizationGroup.by_name(u'anauthzgroup') - aag = model.AuthorizationGroup.by_name(u'anotherauthzgroup') - pkg = model.Package.by_name(u'warandpeace') - g = model.Group.by_name('david') - - model.add_authorization_group_to_role(ag, u'editor', model.System()) - model.add_authorization_group_to_role(ag, u'reader', pkg) - model.add_authorization_group_to_role(ag, u'admin', aag) - model.add_authorization_group_to_role(aag, u'editor', ag) - model.add_authorization_group_to_role(ag, u'editor', g) - - model.repo.commit_and_remove() # method used in DGU and all good tests elsewhere @classmethod @@ -556,7 +534,7 @@ def create_roles(cls, roles): authztool.RightsTool.make_or_remove_roles('make', object_name, role, subject_name, except_on_error=True, do_commit=False) - model.repo.commit_and_remove() + model.repo.commit_and_remove() @classmethod def flag_for_deletion(cls, pkg_names=[], tag_names=[], group_names=[], @@ -673,7 +651,7 @@ def make_some_vocab_tags(cls): model.Package.get('annakarenina').add_tag(sonata_tag) model.Session.commit() - + search_items = [{'name':'gils', diff --git a/ckan/lib/helpers.py b/ckan/lib/helpers.py index d0c1ab4234f..008524562ab 100644 --- a/ckan/lib/helpers.py +++ b/ckan/lib/helpers.py @@ -449,21 +449,6 @@ def linked_user(user, maxlength=0): url_for(controller='user', action='read', id=name)) -def linked_authorization_group(authgroup, maxlength=0): - if not isinstance(authgroup, model.AuthorizationGroup): - authgroup_name = unicode(authgroup) - authgroup = model.AuthorizationGroup.get(authgroup_name) - if not authgroup: - return authgroup_name - if authgroup: - displayname = authgroup.name or authgroup.id - if maxlength and len(display_name) > maxlength: - displayname = displayname[:maxlength] + '...' - return link_to(displayname, - url_for(controller='authorization_group', - action='read', id=displayname)) - - def group_name_to_title(name): group = model.Group.by_name(name) if group is not None: @@ -983,7 +968,6 @@ def render_markdown(data): # am_authorized, # deprecated 'check_access', 'linked_user', - 'linked_authorization_group', 'group_name_to_title', 'markdown_extract', 'icon', diff --git a/ckan/logic/action/__init__.py b/ckan/logic/action/__init__.py index b59a0c2fbfe..970603a2e85 100644 --- a/ckan/logic/action/__init__.py +++ b/ckan/logic/action/__init__.py @@ -35,10 +35,6 @@ def get_domain_object(model, domain_object_ref): group = model.Group.get(domain_object_ref) if group: return group - authorization_group = model.AuthorizationGroup.by_name(domain_object_ref) or\ - model.Session.query(model.AuthorizationGroup).get(domain_object_ref) - if authorization_group: - return authorization_group user = model.User.get(domain_object_ref) if user: return user diff --git a/ckan/logic/action/get.py b/ckan/logic/action/get.py index 128d21ccf73..e196aefe1d6 100644 --- a/ckan/logic/action/get.py +++ b/ckan/logic/action/get.py @@ -1614,13 +1614,11 @@ def get_site_user(context, data_dict): def roles_show(context, data_dict): '''Return the roles of all users and authorization groups for an object. - :param domain_object: a package, group or authorization_group name or id + :param domain_object: a package or group name or id to filter the results by :type domain_object: string :param user: a user name or id :type user: string - :param authorization_group: an authorization group name or id - :type authorization_group: string :rtype: list of dictionaries @@ -1629,15 +1627,12 @@ def roles_show(context, data_dict): session = context['session'] domain_object_ref = _get_or_bust(data_dict, 'domain_object') user_ref = data_dict.get('user') - authgroup_ref = data_dict.get('authorization_group') domain_object = ckan.logic.action.get_domain_object(model, domain_object_ref) if isinstance(domain_object, model.Package): query = session.query(model.PackageRole).join('package') elif isinstance(domain_object, model.Group): query = session.query(model.GroupRole).join('group') - elif isinstance(domain_object, model.AuthorizationGroup): - query = session.query(model.AuthorizationGroupRole).join('authorization_group') elif domain_object is model.System: query = session.query(model.SystemRole) else: @@ -1646,20 +1641,12 @@ def roles_show(context, data_dict): if not isinstance(domain_object, type): query = query.filter_by(id=domain_object.id) - # Filter by the user / authorized_group + # Filter by the user if user_ref: user = model.User.get(user_ref) if not user: raise NotFound(_('unknown user:') + repr(user_ref)) query = query.join('user').filter_by(id=user.id) - if authgroup_ref: - authgroup = model.AuthorizationGroup.get(authgroup_ref) - if not authgroup: - raise NotFound('unknown authorization group:' + repr(authgroup_ref)) - # we need an alias as we join to model.AuthorizationGroup table twice - ag = _aliased(model.AuthorizationGroup) - query = query.join(ag, model.AuthorizationGroupRole.authorized_group) \ - .filter_by(id=authgroup.id) uors = query.all() @@ -1670,8 +1657,6 @@ def roles_show(context, data_dict): 'roles': uors_dictized} if user_ref: result['user'] = user.id - if authgroup_ref: - result['authorization_group'] = authgroup.id return result diff --git a/ckan/logic/action/update.py b/ckan/logic/action/update.py index d60c7927728..5dfb365ba7a 100644 --- a/ckan/logic/action/update.py +++ b/ckan/logic/action/update.py @@ -840,7 +840,7 @@ def package_relationship_update_rest(context, data_dict): def user_role_update(context, data_dict): '''Update a user or authorization group's roles for a domain object. - Either the ``user`` or the ``authorization_group`` parameter must be given. + The ``user`` parameter must be given. You must be authorized to update the domain object. @@ -849,15 +849,13 @@ def user_role_update(context, data_dict): :param user: the name or id of the user :type user: string - :param authorization_group: the name or id of the authorization group - :type authorization_group: string :param domain_object: the name or id of the domain object (e.g. a package, group or authorization group) :type domain_object: string :param roles: the new roles, e.g. ``['editor']`` :type roles: list of strings - :returns: the updated roles of all users and authorization_groups for the + :returns: the updated roles of all users for the domain object :rtype: dictionary @@ -865,9 +863,8 @@ def user_role_update(context, data_dict): model = context['model'] new_user_ref = data_dict.get('user') # the user who is being given the new role - new_authgroup_ref = data_dict.get('authorization_group') # the authgroup who is being given the new role - if bool(new_user_ref) == bool(new_authgroup_ref): - raise logic.ParameterError('You must provide either "user" or "authorization_group" parameter.') + if not bool(new_user_ref): + raise logic.ParameterError('You must provide the "user" parameter.') domain_object_ref = _get_or_bust(data_dict, 'domain_object') if not isinstance(data_dict['roles'], (list, tuple)): raise logic.ParameterError('Parameter "%s" must be of type: "%s"' % ('role', 'list')) @@ -880,13 +877,6 @@ def user_role_update(context, data_dict): data_dict['user'] = user_object.id add_user_to_role_func = model.add_user_to_role remove_user_from_role_func = model.remove_user_from_role - else: - user_object = model.AuthorizationGroup.get(new_authgroup_ref) - if not user_object: - raise NotFound('Cannot find authorization group %r' % new_authgroup_ref) - data_dict['authorization_group'] = user_object.id - add_user_to_role_func = model.add_authorization_group_to_role - remove_user_from_role_func = model.remove_authorization_group_from_role domain_object = logic.action.get_domain_object(model, domain_object_ref) data_dict['id'] = domain_object.id @@ -894,8 +884,6 @@ def user_role_update(context, data_dict): _check_access('package_edit_permissions', context, data_dict) elif isinstance(domain_object, model.Group): _check_access('group_edit_permissions', context, data_dict) - elif isinstance(domain_object, model.AuthorizationGroup): - _check_access('authorization_group_edit_permissions', context, data_dict) # Todo: 'system' object else: raise logic.ParameterError('Not possible to update roles for domain object type %s' % type(domain_object)) @@ -933,20 +921,19 @@ def user_role_bulk_update(context, data_dict): :rtype: dictionary ''' - for user_or_authgroup in ('user', 'authorization_group'): - # Collate all the roles for each user - roles_by_user = {} # user:roles - for user_role_dict in data_dict['user_roles']: - user = user_role_dict.get(user_or_authgroup) - if user: - roles = user_role_dict['roles'] - if user not in roles_by_user: - roles_by_user[user] = [] - roles_by_user[user].extend(roles) - # For each user, update its roles - for user in roles_by_user: - uro_data_dict = {user_or_authgroup: user, - 'roles': roles_by_user[user], - 'domain_object': data_dict['domain_object']} - user_role_update(context, uro_data_dict) + # Collate all the roles for each user + roles_by_user = {} # user:roles + for user_role_dict in data_dict['user_roles']: + user = user_role_dict.get('user') + if user: + roles = user_role_dict['roles'] + if user not in roles_by_user: + roles_by_user[user] = [] + roles_by_user[user].extend(roles) + # For each user, update its roles + for user in roles_by_user: + uro_data_dict = {'user': user, + 'roles': roles_by_user[user], + 'domain_object': data_dict['domain_object']} + user_role_update(context, uro_data_dict) return _get_action('roles_show')(context, data_dict) diff --git a/ckan/logic/auth/__init__.py b/ckan/logic/auth/__init__.py index 7b00f9c8786..66062ead609 100644 --- a/ckan/logic/auth/__init__.py +++ b/ckan/logic/auth/__init__.py @@ -32,6 +32,3 @@ def get_group_object(context, data_dict={}): def get_user_object(context, data_dict={}): return _get_object(context, data_dict, 'user_obj', 'User') -def get_authorization_group_object(context, data_dict={}): - return _get_object(context, data_dict, 'authorization_group', - 'AuthorizationGroup') diff --git a/ckan/logic/auth/create.py b/ckan/logic/auth/create.py index 1d76863550d..2a685fe3655 100644 --- a/ckan/logic/auth/create.py +++ b/ckan/logic/auth/create.py @@ -77,16 +77,6 @@ def group_create(context, data_dict=None): else: return {'success': True} -def authorization_group_create(context, data_dict=None): - model = context['model'] - user = context['user'] - - authorized = logic.check_access_old(model.System(), model.Action.AUTHZ_GROUP_CREATE, context) - if not authorized: - return {'success': False, 'msg': _('User %s not authorized to create authorization groups') % str(user)} - else: - return {'success': True} - def rating_create(context, data_dict): # No authz check in the logic function return {'success': True} diff --git a/ckan/logic/auth/publisher/create.py b/ckan/logic/auth/publisher/create.py index 9a796e9ae8a..441db409609 100644 --- a/ckan/logic/auth/publisher/create.py +++ b/ckan/logic/auth/publisher/create.py @@ -114,9 +114,6 @@ def group_create(context, data_dict=None): else: return {'success': True} -def authorization_group_create(context, data_dict=None): - return {'success': False, 'msg': _('Authorization groups not implemented in this profile') % str(user)} - def rating_create(context, data_dict): # No authz check in the logic function diff --git a/ckan/logic/auth/publisher/update.py b/ckan/logic/auth/publisher/update.py index 30d7a1d92bd..94abc58196c 100644 --- a/ckan/logic/auth/publisher/update.py +++ b/ckan/logic/auth/publisher/update.py @@ -1,7 +1,6 @@ import ckan.logic as logic from ckan.logic.auth import get_package_object, get_group_object, \ - get_user_object, get_resource_object, get_related_object, \ - get_authorization_group_object + get_user_object, get_resource_object, get_related_object from ckan.logic.auth.publisher import _groups_intersect from ckan.logic.auth.publisher.create import package_relationship_create from ckan.authz import Authorizer @@ -107,13 +106,6 @@ def group_change_state(context, data_dict): def group_edit_permissions(context, data_dict): return {'success': False, 'msg': _('Group edit permissions is not implemented')} -def authorization_group_update(context, data_dict): - return {'success': False, 'msg': _('Authorization group update not implemented')} - - -def authorization_group_edit_permissions(context, data_dict): - return {'success': False, 'msg': _('Authorization group update not implemented')} - def user_update(context, data_dict): model = context['model'] user = context['user'] diff --git a/ckan/logic/auth/update.py b/ckan/logic/auth/update.py index babd06f0318..1a1ede9618e 100644 --- a/ckan/logic/auth/update.py +++ b/ckan/logic/auth/update.py @@ -1,7 +1,7 @@ import ckan.logic as logic from ckan.logic.auth import (get_package_object, get_resource_object, - get_group_object, get_authorization_group_object, - get_user_object, get_resource_object, get_related_object) + get_group_object, get_user_object, + get_resource_object, get_related_object) from ckan.logic.auth.create import _check_group_auth, package_relationship_create from ckan.authz import Authorizer from ckan.lib.base import _ @@ -127,27 +127,7 @@ def group_edit_permissions(context, data_dict): else: return {'success': True} -def authorization_group_update(context, data_dict): - model = context['model'] - user = context['user'] - authorization_group = get_authorization_group_object(context, data_dict) - - authorized = logic.check_access_old(authorization_group, model.Action.EDIT, context) - if not authorized: - return {'success': False, 'msg': _('User %s not authorized to edit permissions of authorization group %s') % (str(user),authorization_group.id)} - else: - return {'success': True} -def authorization_group_edit_permissions(context, data_dict): - model = context['model'] - user = context['user'] - authorization_group = get_authorization_group_object(context, data_dict) - - authorized = logic.check_access_old(authorization_group, model.Action.EDIT_PERMISSIONS, context) - if not authorized: - return {'success': False, 'msg': _('User %s not authorized to edit permissions of authorization group %s') % (str(user),authorization_group.id)} - else: - return {'success': True} def user_update(context, data_dict): user = context['user'] diff --git a/ckan/migration/versions/025_add_authorization_groups.py b/ckan/migration/versions/025_add_authorization_groups.py index 15486665780..76e9a25a54b 100644 --- a/ckan/migration/versions/025_add_authorization_groups.py +++ b/ckan/migration/versions/025_add_authorization_groups.py @@ -28,7 +28,7 @@ def upgrade(migrate_engine): Column('user_id', UnicodeText, ForeignKey('user.id'), nullable=False) ) - # make user nullable: + # make user nullable: user_object_role_table = Table('user_object_role', metadata, Column('id', UnicodeText, primary_key=True, default=make_uuid), Column('user_id', UnicodeText, ForeignKey('user.id'), nullable=True), @@ -40,11 +40,11 @@ def upgrade(migrate_engine): Column('user_object_role_id', UnicodeText, ForeignKey('user_object_role.id'), primary_key=True), Column('authorization_group_id', UnicodeText, ForeignKey('authorization_group.id')), ) - + authorization_group_table.create() authorization_group_user_table.create() authorization_group_role_table.create() - authorization_group_id = Column('authorized_group_id', UnicodeText, + authorization_group_id = Column('authorized_group_id', UnicodeText, ForeignKey('authorization_group.id'), nullable=True) authorization_group_id.create(user_object_role_table) diff --git a/ckan/model/__init__.py b/ckan/model/__init__.py index 8faf0c5b169..b622823eb0c 100644 --- a/ckan/model/__init__.py +++ b/ckan/model/__init__.py @@ -52,29 +52,19 @@ UserObjectRole, PackageRole, GroupRole, - AuthorizationGroupRole, SystemRole, PSEUDO_USER__VISITOR, PSEUDO_USER__LOGGED_IN, init_authz_const_data, init_authz_configuration_data, add_user_to_role, - add_authorization_group_to_role, setup_user_roles, setup_default_user_roles, give_all_packages_default_user_roles, user_has_role, remove_user_from_role, - remove_authorization_group_from_role, clear_user_roles, ) -from authorization_group import ( - AuthorizationGroup, - AuthorizationGroupUser, - user_in_authorization_group, - add_user_to_authorization_group, - remove_user_from_authorization_group, -) from group import ( Member, Group, diff --git a/ckan/model/authorization_group.py b/ckan/model/authorization_group.py deleted file mode 100644 index 460f3dfd25c..00000000000 --- a/ckan/model/authorization_group.py +++ /dev/null @@ -1,85 +0,0 @@ -import datetime - -from sqlalchemy import orm, types, Column, Table, ForeignKey, or_ - -import meta -import user -import types as _types -import domain_object - -__all__ = ['AuthorizationGroup', 'AuthorizationGroupUser', - 'user_in_authorization_group', 'add_user_to_authorization_group', - 'remove_user_from_authorization_group'] - -authorization_group_table = Table('authorization_group', meta.metadata, - Column('id', types.UnicodeText, primary_key=True, default=_types.make_uuid), - Column('name', types.UnicodeText), - Column('created', types.DateTime, default=datetime.datetime.now), - ) - -authorization_group_user_table = Table('authorization_group_user', meta.metadata, - Column('id', types.UnicodeText, primary_key=True, default=_types.make_uuid), - Column('authorization_group_id', types.UnicodeText, ForeignKey('authorization_group.id'), - nullable=False), - Column('user_id', types.UnicodeText, ForeignKey('user.id'), nullable=False) - ) - - -class AuthorizationGroup(domain_object.DomainObject): - - @classmethod - def search(cls, querystr, sqlalchemy_query=None): - '''Search name. - ''' - if sqlalchemy_query is None: - query = meta.Session.query(cls) - else: - query = sqlalchemy_query - qstr = '%' + querystr + '%' - query = query.filter(or_( - cls.name.ilike(qstr))) - return query - - @classmethod - def get(cls, auth_group_reference): - query = meta.Session.query(cls).autoflush(False) - query = query.filter(or_(cls.name==auth_group_reference, - cls.id==auth_group_reference)) - return query.first() - -class AuthorizationGroupUser(domain_object.DomainObject): - pass - -def user_in_authorization_group(user, authorization_group): - q = meta.Session.query(AuthorizationGroup) - q = q.filter_by(id=authorization_group.id) - q = q.filter(AuthorizationGroup.users.contains(user)) - return q.count() == 1 - -def add_user_to_authorization_group(user, authorization_group, role): - assert not user_in_authorization_group(user, authorization_group) - from authz import add_user_to_role - meta.Session.add(authorization_group) - authorization_group.users.append(user) - add_user_to_role(user, role, authorization_group) - -def remove_user_from_authorization_group(user, authorization_group): - assert user_in_authorization_group(user, authorization_group) - from authz import remove_user_from_role, AuthorizationGroupRole - meta.Session.add(authorization_group) - authorization_group.users.remove(user) - q = meta.Session.query(AuthorizationGroupRole) - q = q.filter_by(authorization_group=authorization_group, - user=user) - for agr in q: - remove_user_from_role(user, agr.role, authorization_group) - - - -meta.mapper(AuthorizationGroup, authorization_group_table, properties={ - 'users': orm.relation(user.User, lazy=True, secondary=authorization_group_user_table, - backref=orm.backref('authorization_groups', lazy=True)) - }, - order_by=authorization_group_table.c.name) - -meta.mapper(AuthorizationGroupUser, authorization_group_user_table) diff --git a/ckan/model/authz.py b/ckan/model/authz.py index 6929cd49e30..80833c285be 100644 --- a/ckan/model/authz.py +++ b/ckan/model/authz.py @@ -14,18 +14,16 @@ import package as _package import group import user as _user -import authorization_group as auth_group import types as _types __all__ = ['NotRealUserException', 'Enum', 'Action', 'Role', 'RoleAction', 'UserObjectRole', 'PackageRole', 'GroupRole', - 'AuthorizationGroupRole', 'SystemRole', 'PSEUDO_USER__VISITOR', + 'SystemRole', 'PSEUDO_USER__VISITOR', 'PSEUDO_USER__LOGGED_IN', 'init_authz_const_data', 'init_authz_configuration_data', 'add_user_to_role', - 'add_authorization_group_to_role', 'setup_user_roles', - 'setup_default_user_roles', 'give_all_packages_default_user_roles', - 'user_has_role', 'remove_user_from_role', - 'remove_authorization_group_from_role', 'clear_user_roles'] + 'setup_user_roles', 'setup_default_user_roles', + 'give_all_packages_default_user_roles', + 'user_has_role', 'remove_user_from_role', 'clear_user_roles'] PSEUDO_USER__LOGGED_IN = u'logged_in' PSEUDO_USER__VISITOR = u'visitor' @@ -59,12 +57,11 @@ class Action(Enum): EDIT_PERMISSIONS = u'edit-permissions' PACKAGE_CREATE = u'create-package' GROUP_CREATE = u'create-group' - AUTHZ_GROUP_CREATE = u'create-authorization-group' SITE_READ = u'read-site' USER_READ = u'read-user' USER_CREATE = u'create-user' UPLOAD_ACTION = u'file-upload' - + class Role(Enum): ADMIN = u'admin' EDITOR = u'editor' @@ -79,19 +76,18 @@ class Role(Enum): (Role.EDITOR, Action.EDIT), (Role.EDITOR, Action.PACKAGE_CREATE), (Role.EDITOR, Action.GROUP_CREATE), - (Role.EDITOR, Action.AUTHZ_GROUP_CREATE), (Role.EDITOR, Action.USER_CREATE), (Role.EDITOR, Action.USER_READ), (Role.EDITOR, Action.SITE_READ), (Role.EDITOR, Action.READ), - (Role.EDITOR, Action.UPLOAD_ACTION), + (Role.EDITOR, Action.UPLOAD_ACTION), (Role.ANON_EDITOR, Action.EDIT), (Role.ANON_EDITOR, Action.PACKAGE_CREATE), (Role.ANON_EDITOR, Action.USER_CREATE), (Role.ANON_EDITOR, Action.USER_READ), (Role.ANON_EDITOR, Action.SITE_READ), (Role.ANON_EDITOR, Action.READ), - (Role.ANON_EDITOR, Action.UPLOAD_ACTION), + (Role.ANON_EDITOR, Action.UPLOAD_ACTION), (Role.READER, Action.USER_CREATE), (Role.READER, Action.USER_READ), (Role.READER, Action.SITE_READ), @@ -112,7 +108,7 @@ class Role(Enum): user_object_role_table = Table('user_object_role', meta.metadata, Column('id', types.UnicodeText, primary_key=True, default=_types.make_uuid), Column('user_id', types.UnicodeText, ForeignKey('user.id'), nullable=True), - Column('authorized_group_id', types.UnicodeText, ForeignKey('authorization_group.id'), nullable=True), +# Column('authorized_group_id', types.UnicodeText, ForeignKey('authorization_group.id'), nullable=True), Column('context', types.UnicodeText, nullable=False), # stores subtype Column('role', types.UnicodeText) ) @@ -126,11 +122,6 @@ class Role(Enum): Column('user_object_role_id', types.UnicodeText, ForeignKey('user_object_role.id'), primary_key=True), Column('group_id', types.UnicodeText, ForeignKey('group.id')), ) - -authorization_group_role_table = Table('authorization_group_role', meta.metadata, - Column('user_object_role_id', types.UnicodeText, ForeignKey('user_object_role.id'), primary_key=True), - Column('authorization_group_id', types.UnicodeText, ForeignKey('authorization_group.id')), - ) system_role_table = Table('system_role', meta.metadata, Column('user_object_role_id', types.UnicodeText, ForeignKey('user_object_role.id'), primary_key=True), @@ -141,7 +132,7 @@ class RoleAction(domain_object.DomainObject): def __repr__(self): return '<%s role="%s" action="%s" context="%s">' % \ (self.__class__.__name__, self.role, self.action, self.context) - + # dictionary mapping protected objects (e.g. Package) to related ObjectRole protected_objects = {} @@ -154,11 +145,8 @@ def __repr__(self): if self.user: return '<%s user="%s" role="%s" context="%s">' % \ (self.__class__.__name__, self.user.name, self.role, self.context) - elif self.authorized_group: - return '<%s authorized_group="%s" role="%s" context="%s">' % \ - (self.__class__.__name__, self.authorized_group.name, self.role, self.context) else: - assert False, "UserObjectRole is neither for an authzgroup or for a user" + assert False, "UserObjectRole is not a user" @classmethod def get_object_role_class(cls, domain_obj): @@ -175,13 +163,8 @@ def user_has_role(cls, user, role, domain_obj): assert isinstance(user, _user.User), user q = cls._user_query(user, role, domain_obj) return q.count() == 1 - - @classmethod - def authorization_group_has_role(cls, authorized_group, role, domain_obj): - assert isinstance(authorized_group, auth_group.AuthorizationGroup), authorized_group - q = cls._authorized_group_query(authorized_group, role, domain_obj) - return q.count() == 1 - + + @classmethod def _user_query(cls, user, role, domain_obj): q = meta.Session.query(cls).filter_by(role=role) @@ -191,16 +174,7 @@ def _user_query(cls, user, role, domain_obj): q = q.filter_by(**dict({cls.name: domain_obj})) q = q.filter_by(user=user) return q - - @classmethod - def _authorized_group_query(cls, authorized_group, role, domain_obj): - q = meta.Session.query(cls).filter_by(role=role) - # some protected objects are not "contextual" - if cls.name is not None: - # e.g. filter_by(package=domain_obj) - q = q.filter_by(**dict({cls.name: domain_obj})) - q = q.filter_by(authorized_group=authorized_group) - return q + @classmethod def add_user_to_role(cls, user, role, domain_obj): @@ -218,21 +192,7 @@ def add_user_to_role(cls, user, role, domain_obj): if cls.name is not None: setattr(objectrole, cls.name, domain_obj) meta.Session.add(objectrole) - - @classmethod - def add_authorization_group_to_role(cls, authorization_group, role, domain_obj): - '''NB: Leaves the caller to commit the change. If called twice without a - commit, will add the role to the database twice. Since some other - functions count the number of occurrences, that leaves a fairly obvious - bug. But adding a commit here seems to break various tests. - So don\'t call this twice without committing, I guess... - ''' - if cls.authorization_group_has_role(authorization_group, role, domain_obj): - return - objectrole = cls(role=role, authorized_group=authorization_group) - if cls.name is not None: - setattr(objectrole, cls.name, domain_obj) - meta.Session.add(objectrole) + @classmethod def remove_user_from_role(cls, user, role, domain_obj): @@ -242,13 +202,6 @@ def remove_user_from_role(cls, user, role, domain_obj): meta.Session.commit() meta.Session.remove() - @classmethod - def remove_authorization_group_from_role(cls, authorization_group, role, domain_obj): - q = cls._authorized_group_query(authorization_group, role, domain_obj) - for ago_role in q.all(): - meta.Session.delete(ago_role) - meta.Session.commit() - meta.Session.remove() class PackageRole(UserObjectRole): protected_object = _package.Package @@ -258,11 +211,8 @@ def __repr__(self): if self.user: return '<%s user="%s" role="%s" package="%s">' % \ (self.__class__.__name__, self.user.name, self.role, self.package.name) - elif self.authorized_group: - return '<%s authorized_group="%s" role="%s" package="%s">' % \ - (self.__class__.__name__, self.authorized_group.name, self.role, self.package.name) else: - assert False, "%s is neither for an authzgroup or for a user" % self.__class__.__name__ + assert False, "%s is not a user" % self.__class__.__name__ protected_objects[PackageRole.protected_object] = PackageRole @@ -274,29 +224,11 @@ def __repr__(self): if self.user: return '<%s user="%s" role="%s" group="%s">' % \ (self.__class__.__name__, self.user.name, self.role, self.group.name) - elif self.authorized_group: - return '<%s authorized_group="%s" role="%s" group="%s">' % \ - (self.__class__.__name__, self.authorized_group.name, self.role, self.group.name) else: - assert False, "%s is neither for an authzgroup or for a user" % self.__class__.__name__ + assert False, "%s is not a user" % self.__class__.__name__ protected_objects[GroupRole.protected_object] = GroupRole -class AuthorizationGroupRole(UserObjectRole): - protected_object = auth_group.AuthorizationGroup - name = 'authorization_group' - - def __repr__(self): - if self.user: - return '<%s user="%s" role="%s" authorization_group="%s">' % \ - (self.__class__.__name__, self.user.name, self.role, self.authorization_group.name) - elif self.authorized_group: - return '<%s authorized_group="%s" role="%s" authorization_group="%s">' % \ - (self.__class__.__name__, self.authorized_group.name, self.role, self.authorization_group.name) - else: - assert False, "%s is neither for an authzgroup or for a user" % self.__class__.__name__ - -protected_objects[AuthorizationGroupRole.protected_object] = AuthorizationGroupRole class SystemRole(UserObjectRole): protected_object = core.System @@ -321,24 +253,12 @@ def remove_user_from_role(user, role, domain_obj): objectrole = UserObjectRole.get_object_role_class(domain_obj) objectrole.remove_user_from_role(user, role, domain_obj) - -def authorization_group_has_role(authorization_group, role, domain_obj): - objectrole = UserObjectRole.get_object_role_class(domain_obj) - return objectrole.authorization_group_has_role(authorization_group, role, domain_obj) - -def add_authorization_group_to_role(authorization_group, role, domain_obj): - objectrole = UserObjectRole.get_object_role_class(domain_obj) - objectrole.add_authorization_group_to_role(authorization_group, role, domain_obj) -def remove_authorization_group_from_role(authorization_group, role, domain_obj): - objectrole = UserObjectRole.get_object_role_class(domain_obj) - objectrole.remove_authorization_group_from_role(authorization_group, role, domain_obj) - def init_authz_configuration_data(): setup_default_user_roles(core.System()) meta.Session.commit() meta.Session.remove() - + def init_authz_const_data(): '''Setup all default role-actions. @@ -410,7 +330,6 @@ def give_all_packages_default_user_roles(): 'Package': {"visitor": ["reader"], "logged_in": ["reader"]}, 'Group': {"visitor": ["reader"], "logged_in": ["reader"]}, 'System': {"visitor": ["reader"], "logged_in": ["editor"]}, - 'AuthorizationGroup': {"visitor": ["reader"], "logged_in": ["reader"]}, } global _default_user_roles_cache @@ -438,13 +357,13 @@ def _get_default_user_roles(_domain_object): if not _default_user_roles_cache.has_key(_domain_object): _default_user_roles_cache[_domain_object] = _get_default_user_roles(_domain_object) return _default_user_roles_cache[_domain_object] - + def setup_default_user_roles(_domain_object, admins=[]): ''' sets up roles for visitor, logged-in user and any admins provided @param admins - a list of User objects NB: leaves caller to commit change. ''' - assert isinstance(_domain_object, (_package.Package, group.Group, core.System, auth_group.AuthorizationGroup)), _domain_object + assert isinstance(_domain_object, (_package.Package, group.Group, core.System)), _domain_object assert isinstance(admins, list) user_roles_ = get_default_user_roles(_domain_object) setup_user_roles(_domain_object, @@ -469,7 +388,7 @@ def clear_user_roles(_domain_object): ## Mappers meta.mapper(RoleAction, role_action_table) - + meta.mapper(UserObjectRole, user_object_role_table, polymorphic_on=user_object_role_table.c.context, polymorphic_identity=u'user_object', @@ -478,11 +397,6 @@ def clear_user_roles(_domain_object): backref=orm.backref('roles', cascade='all, delete, delete-orphan' ) - ), - 'authorized_group': orm.relation(auth_group.AuthorizationGroup, - backref=orm.backref('authorized_roles', - cascade='all, delete, delete-orphan' - ) ) }, order_by=[user_object_role_table.c.id], @@ -512,19 +426,6 @@ def clear_user_roles(_domain_object): order_by=[group_role_table.c.user_object_role_id], ) -meta.mapper(AuthorizationGroupRole, authorization_group_role_table, inherits=UserObjectRole, - polymorphic_identity=unicode(auth_group.AuthorizationGroup.__name__), - properties={ - 'authorization_group': orm.relation(auth_group.AuthorizationGroup, - backref=orm.backref('roles', - primaryjoin=auth_group.authorization_group_table.c.id==authorization_group_role_table.c.authorization_group_id, - cascade='all, delete, delete-orphan' - ), - ) - }, - order_by=[authorization_group_role_table.c.user_object_role_id], -) - meta.mapper(SystemRole, system_role_table, inherits=UserObjectRole, polymorphic_identity=unicode(core.System.__name__), order_by=[system_role_table.c.user_object_role_id], diff --git a/ckan/plugins/interfaces.py b/ckan/plugins/interfaces.py index 638cbc7d908..bde61f934a6 100644 --- a/ckan/plugins/interfaces.py +++ b/ckan/plugins/interfaces.py @@ -375,11 +375,6 @@ class IAuthorizer(Interface): """ Allow customisation of default Authorization implementation """ - def get_authorization_groups(self, username): - """ - Called by Authorizer to extend the list of groups to which a - user belongs. Should return a list of AuthorizationGroups. - """ def get_roles(self, username, domain_obj): """ diff --git a/ckan/public/images/icons/authorization_group_add.png b/ckan/public/images/icons/authorization_group_add.png deleted file mode 100644 index 06c5350cb197e64439aa1d0b1aa438b013c2f4a1..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 807 zcmV+?1K9kDP)mo3jW}i{%_@b6dHYnoXT!P3L{yXgdAxrsZYf zWtGn6Fta7-gNCWosY{E%J)~Q2p<+ThPn(n)hWUlVmmfdQ=X*FL0HnPnjy}$wR(mbZ zx1PY9#(k}c=g|-q=yB-J|DI-E_(_Vj+1;_w=7ycBOZBYY7odT8j9BROhpm@`AH$Wf z>4LGKJq3%}^ZUL4s_3JYc5^Qlhg4WIKg05S73L>;&|mCl-4}ow9>bk!$=q0)?0{po z6Dt-y>;nXf60Yk03E+~w*h+TjBEcX-#iFbw(|yMXVd_u2j*qWhg|HiPFH0JTB?qXs01CQi` z;2Ti-Qit3|Ed+!H^&_hgDCQAga(%sPx*A;3V83xD&;twuaL1LRd=9a^ zDBPBMqtckTdD*pHZzn)X`rMop)Kf&w4y3i{{nJN5&YN;-8f5V#Lb6Tpyz#;+&q^#v l5PBP&h9y_*-@Dw^-!JB5sxM9&*;W7m002ovPDHLkV1kg{c8>r6 diff --git a/ckan/public/images/icons/authorization_group_edit.png b/ckan/public/images/icons/authorization_group_edit.png deleted file mode 100755 index c88b945b0a8306c856a934c52546f62244af0e51..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 785 zcmV+s1Md8ZP)|`AZJDm8A+@B2c=23){C>RO^S&eiq`i_&3*gLFg*Ys& z$Fa~9xYfuDs*ec|I`rp#PnbtNL71BZJ=V5k*qxfRVDY{L_3R@Ot11jObuwJzWw0ru zU~NAMT~+Yvz65gG;WE2M4abNaTbifX7?s2Fz88Z}&YAZmh^5AH^(~n{*R=|G3@SKv zov;r{kjJ{D^efayZSe;Q|wDjs1pP)Sc{BUjR zEvRx6p>NAZE1wPtlR$L}1+T|g_&S$^&E;XJyT=(6E)4a4>E9#$sPVQ5aoWE~SGS`+216GGRQb4p}yUaTmb-qIPCF$G%mQ53R6(O+~O4Mj - ${authorization_group.name or authorization_group.id} - - ${len(authorization_group.users)} - - - - ${h.markdown_extract(related.title, - - - - - - - - - - - - - - - - - -
User Group ${role}
- ${h.linked_authorization_group(user)} - - - - - - - - - - -
- @@ -267,27 +218,6 @@
${h.markdown_extract(related.title,
- - - - - - - - - - - - - - -
User Group ${role}
- - - - -
- ${revision_list_from_dict(h.convert_to_dict('revisions', revisions), allow_compare=allow_compare)} diff --git a/ckan/templates/admin/authz.html b/ckan/templates/admin/authz.html index edb2bc86413..82284e8387b 100644 --- a/ckan/templates/admin/authz.html +++ b/ckan/templates/admin/authz.html @@ -24,27 +24,6 @@

Add Roles for Any User

-
- - -

Existing Roles for Authorization Groups

- -
- ${authz_form_group_table('authzgroup_form', c.roles, c.authz_groups, c.authz_groups_role_dict)} - -
-
- -

Add Roles for Any Authorization Group

- -
- ${authz_add_group_table(c.roles)} - -
-
-
- - diff --git a/ckan/templates/authorization_group/__init__.py b/ckan/templates/authorization_group/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/ckan/templates/authorization_group/authz.html b/ckan/templates/authorization_group/authz.html deleted file mode 100644 index 1c5378cbdee..00000000000 --- a/ckan/templates/authorization_group/authz.html +++ /dev/null @@ -1,52 +0,0 @@ - - - ${c.authorization_group_name} - Authorization - AuthorizationGroups - Authorization: ${c.authorization_group_name} - -
- -
- Warning: Authorization groups are deprecated and no longer supported. They will be removed - completely on the next CKAN release. -
- -

Update Existing Roles

- -
- ${authz_form_table('theform', c.roles, c.users, c.user_role_dict)} - -
- -

Add Roles for Any User

- -
- ${authz_add_table(c.roles)} - -
- -
- -

Existing Roles for Authorization Groups

- -
- ${authz_form_group_table('authzgroup_form', c.roles, c.authz_groups, c.authz_groups_role_dict)} - -
- -

Add Roles for Any Authorization Group

- -
- ${authz_add_group_table(c.roles)} - -
- -
- - - diff --git a/ckan/templates/authorization_group/edit.html b/ckan/templates/authorization_group/edit.html deleted file mode 100644 index a404ce2318e..00000000000 --- a/ckan/templates/authorization_group/edit.html +++ /dev/null @@ -1,20 +0,0 @@ - - - ${c.authorization_group_name} - Edit - Authorization Groups - Edit: ${c.authorization_group.name if c.authorization_group else ''} - -
- -
- Warning: Authorization groups are deprecated and no longer supported. They will be removed - completely on the next CKAN release. -
- - ${Markup(c.form)} -
- - - - diff --git a/ckan/templates/authorization_group/edit_form.html b/ckan/templates/authorization_group/edit_form.html deleted file mode 100644 index 293428077ff..00000000000 --- a/ckan/templates/authorization_group/edit_form.html +++ /dev/null @@ -1,30 +0,0 @@ -
- - ${h.literal(c.fieldset.render())} - -
- Users -
- -
- -
-
-

There are no users currently in this group.

-
- - ${h.literal(c.fieldset2.render())} - -
- ${h.submit('save', _('Save'))} -
diff --git a/ckan/templates/authorization_group/index.html b/ckan/templates/authorization_group/index.html deleted file mode 100644 index 281f3d1772b..00000000000 --- a/ckan/templates/authorization_group/index.html +++ /dev/null @@ -1,24 +0,0 @@ - - - Authorization Groups - Authorization Groups - -
- -
- Warning: Authorization groups are deprecated and no longer supported. They will be removed - completely on the next CKAN release. -
- -

There are ${c.page.item_count} authorization groups.

- - ${c.page.pager()} - ${authorization_group_list(c.page.items)} - ${c.page.pager()} -
- - - diff --git a/ckan/templates/authorization_group/layout.html b/ckan/templates/authorization_group/layout.html deleted file mode 100644 index e575f8d8b98..00000000000 --- a/ckan/templates/authorization_group/layout.html +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - - -
  • -

    Authorization Groups

    -

    Instead of specifying the privileges of specific users on a dataset or group, - you can also specify a set of users that will share the same rights. To do that, an - authorization group can be set-up and users can be added to it.

    -

    - - - Create a new authorization group - -

    -
  • -
    - - - diff --git a/ckan/templates/authorization_group/new.html b/ckan/templates/authorization_group/new.html deleted file mode 100644 index 1eb973b9282..00000000000 --- a/ckan/templates/authorization_group/new.html +++ /dev/null @@ -1,20 +0,0 @@ - - - New - Authorization Groups - New Authorization Group - -
    - -
    - Warning: Authorization groups are deprecated and no longer supported. They will be removed - completely on the next CKAN release. -
    - - ${Markup(c.form)} -
    - - - - diff --git a/ckan/templates/authorization_group/read.html b/ckan/templates/authorization_group/read.html deleted file mode 100644 index 3c2c7bad233..00000000000 --- a/ckan/templates/authorization_group/read.html +++ /dev/null @@ -1,26 +0,0 @@ - - - ${c.authorization_group.name} - Authorization Groups - ${c.authorization_group.name} - -
    - -
    - Warning: Authorization groups are deprecated and no longer supported. They will be removed - completely on the next CKAN release. -
    - -

    Members

    -

    There are ${c.page.item_count} users in this authorization group.

    - ${c.page.pager()} - ${user_list(c.page.items)} - ${c.page.pager()} -
    - - - - - diff --git a/ckan/templates/group/authz.html b/ckan/templates/group/authz.html index 77c34980cc4..63d955aa514 100644 --- a/ckan/templates/group/authz.html +++ b/ckan/templates/group/authz.html @@ -1,10 +1,10 @@ - + Authorization: ${c.group.display_name} Authorization: ${c.group.display_name} - +

    Update Existing Roles

    @@ -23,26 +23,6 @@

    Add Roles for Any User

    -
    - - -

    Update Existing Roles for Authorization Groups

    - -
    - ${authz_form_group_table('authzgroup_form', c.roles, c.authz_groups, c.authz_groups_role_dict)} - -
    -
    - -

    Add Roles for Any Authorization Group

    - -
    - ${authz_add_group_table(c.roles)} - -
    -
    -
    -
    diff --git a/ckan/templates/package/authz.html b/ckan/templates/package/authz.html index 55132ec3985..97c6772194a 100644 --- a/ckan/templates/package/authz.html +++ b/ckan/templates/package/authz.html @@ -1,7 +1,7 @@ - + Authorization: ${c.pkgtitle or c.pkgname} Authorization: ${c.pkgtitle or c.pkgname} @@ -23,27 +23,7 @@

    Add Roles for Any User

    -
    - - -

    Update Existing Roles for Authorization Groups

    - -
    - ${authz_form_group_table('authzgroup_form', c.roles, c.authz_groups, c.authz_groups_role_dict)} - -
    -
    - -

    Add Roles for Any Authorization Group

    - -
    - ${authz_add_group_table(c.roles)} - -
    -
    -
    - - + diff --git a/ckan/templates/package/layout.html b/ckan/templates/package/layout.html index d4b65e48aa7..d425e506884 100644 --- a/ckan/templates/package/layout.html +++ b/ckan/templates/package/layout.html @@ -38,7 +38,7 @@
  • ${h.subnav_link(h.icon('page_stack') + _('History'), controller='package', action='history', id=c.pkg.name)}
  • ${h.subnav_link( - h.icon('authorization_group') + _('Followers ({num_followers})').format(num_followers=h.follow_count('dataset', c.pkg_dict.id)), + h.icon('followers') + _('Followers ({num_followers})').format(num_followers=h.follow_count('dataset', c.pkg_dict.id)), controller='package', action='followers', id=c.pkg.name)} diff --git a/ckan/templates/package/new_package_form.html b/ckan/templates/package/new_package_form.html index 29b3c03797c..67a79f151dd 100644 --- a/ckan/templates/package/new_package_form.html +++ b/ckan/templates/package/new_package_form.html @@ -95,14 +95,10 @@

    Errors in form

    Member of: -
    - - - + + +
    @@ -172,7 +168,7 @@

    Errors in form

    - + diff --git a/ckan/templates/user/layout.html b/ckan/templates/user/layout.html index e733d4df336..25140cac6f7 100644 --- a/ckan/templates/user/layout.html +++ b/ckan/templates/user/layout.html @@ -14,7 +14,7 @@
  • Log out
  • ${h.subnav_link( - h.icon('authorization_group') + _('My Followers ({num_followers})').format(num_followers=h.follow_count('user', c.user_dict.id)), + h.icon('followers') + _('My Followers ({num_followers})').format(num_followers=h.follow_count('user', c.user_dict.id)), controller='user', action='followers', id=c.user_dict.name)} @@ -25,7 +25,7 @@
  • View Profile
  • ${h.subnav_link( - h.icon('authorization_group') + _('Followers ({num_followers})').format(num_followers=h.follow_count('user', c.user_dict.id)), + h.icon('followers') + _('Followers ({num_followers})').format(num_followers=h.follow_count('user', c.user_dict.id)), controller='user', action='followers', id=c.user_dict.name)} @@ -41,7 +41,7 @@ - + diff --git a/ckan/tests/__init__.py b/ckan/tests/__init__.py index 4336c893324..721c55f6f49 100644 --- a/ckan/tests/__init__.py +++ b/ckan/tests/__init__.py @@ -93,7 +93,7 @@ def create_package(self, data={}, admins=[], **kwds): @classmethod def create_user(cls, **kwds): - user = model.User(name=kwds['name']) + user = model.User(name=kwds['name']) model.Session.add(user) model.Session.commit() model.Session.remove() @@ -189,8 +189,8 @@ def assert_equal(self, value1, value2): def assert_isinstance(self, value, check): assert isinstance(value, check), 'Not an instance: %s' % ((value, check),) - - def assert_raises(self, exception_class, callable, *args, **kwds): + + def assert_raises(self, exception_class, callable, *args, **kwds): try: callable(*args, **kwds) except exception_class: @@ -265,7 +265,7 @@ def _wait_for_url(url='http://127.0.0.1:5000/', timeout=15): break @staticmethod - def _stop_ckan_server(process): + def _stop_ckan_server(process): pid = process.pid pid = int(pid) if os.system("kill -9 %d" % pid): @@ -292,8 +292,8 @@ class TestSearchIndexer: (create packages) self.tsi.index() (do searching) - ''' - + ''' + def __init__(self): from ckan import plugins if not is_search_supported(): @@ -302,12 +302,12 @@ def __init__(self): @classmethod def index(cls): - pass + pass @classmethod def list(cls): return [model.Package.get(pkg_index.package_id).name for pkg_index in model.Session.query(model.PackageSearch)] - + def setup_test_search_index(): from ckan import plugins if not is_search_supported(): @@ -353,17 +353,15 @@ def clear_flash(res=None): def assert_in(a, b, msg=None): assert a in b, msg or '%r was not in %r' % (a, b) def assert_not_in(a, b, msg=None): - assert a not in b, msg or '%r was in %r' % (a, b) + assert a not in b, msg or '%r was in %r' % (a, b) class TestRoles: @classmethod - def get_roles(cls, domain_object_ref, user_ref=None, authgroup_ref=None, + def get_roles(cls, domain_object_ref, user_ref=None, prettify=True): data_dict = {'domain_object': domain_object_ref} if user_ref: data_dict['user'] = user_ref - if authgroup_ref: - data_dict['authorization_group'] = authgroup_ref role_dicts = get_action('roles_show') \ ({'model': model, 'session': model.Session}, \ data_dict)['roles'] @@ -387,12 +385,12 @@ def prettify_role_dicts(cls, role_dicts, one_per_line=True): pretty_role[key] = value if one_per_line: pretty_role = '"%s" is "%s" on "%s"' % ( - pretty_role.get('user') or pretty_role.get('authorized_group'), + pretty_role.get('user'), pretty_role['role'], - pretty_role.get('package') or pretty_role.get('group') or pretty_role.get('authorization_group') or pretty_role.get('context')) + pretty_role.get('package') or pretty_role.get('group') or pretty_role.get('context')) pretty_roles.append(pretty_role) return pretty_roles - + class StatusCodes: STATUS_200_OK = 200 @@ -401,4 +399,4 @@ class StatusCodes: STATUS_403_ACCESS_DENIED = 403 STATUS_404_NOT_FOUND = 404 STATUS_409_CONFLICT = 409 - + diff --git a/ckan/tests/ckantestplugin/ckantestplugin/__init__.py b/ckan/tests/ckantestplugin/ckantestplugin/__init__.py index a4989b901d4..80ccb91f8e2 100644 --- a/ckan/tests/ckantestplugin/ckantestplugin/__init__.py +++ b/ckan/tests/ckantestplugin/ckantestplugin/__init__.py @@ -43,9 +43,6 @@ class PluginObserverPlugin(MockSingletonPlugin): class AuthorizerPlugin(SingletonPlugin): implements(IAuthorizer, inherit=True) - def get_authorization_groups(self, username): - return [model.AuthorizationGroup(name=u'authz_plugin_group')] - def get_roles(self, username, domain_obj): return [model.authz.Role.ADMIN] diff --git a/ckan/tests/functional/api/test_authorization_group.py b/ckan/tests/functional/api/test_authorization_group.py deleted file mode 100644 index 5702a6bf481..00000000000 --- a/ckan/tests/functional/api/test_authorization_group.py +++ /dev/null @@ -1,58 +0,0 @@ -from nose.tools import assert_equal - -from ckan import model -from ckan.lib.create_test_data import CreateTestData -from ckan.tests import TestController as ControllerTestCase -from ckan.tests import url_for - -class TestAuthorizationGroupApi(ControllerTestCase): - @classmethod - def setup(cls): - CreateTestData.create() - for ag_name in [u'anauthzgroup', u'anotherauthzgroup']: - ag=model.AuthorizationGroup.by_name(ag_name) - if not ag: #may already exist, if not create - ag=model.AuthorizationGroup(name=ag_name) - model.Session.add(ag) - model.Session.commit() - - @classmethod - def teardown(cls): - model.repo.rebuild_db() - - def test_autocomplete(self): - response = self.app.get( - url=url_for(controller='api', action='authorizationgroup_autocomplete', ver=2), - params={ - 'q': u'anauthzgroup', - }, - status=200, - ) - print response.json - assert set(response.json[0].keys()) == set(['id', 'name']) - assert_equal(response.json[0]['name'], u'anauthzgroup') - assert_equal(response.header('Content-Type'), 'application/json;charset=utf-8') - - def test_autocomplete_multiple(self): - response = self.app.get( - url=url_for(controller='api', action='authorizationgroup_autocomplete', ver=2), - params={ - 'q': u'authz', - }, - status=200, - ) - print response.json - assert_equal(len(response.json), 2) - - def test_autocomplete_limit(self): - response = self.app.get( - url=url_for(controller='api', action='authorizationgroup_autocomplete', ver=2), - params={ - 'q': u'authz', - 'limit': 1 - }, - status=200, - ) - print response.json - assert_equal(len(response.json), 1) - diff --git a/ckan/tests/functional/test_admin.py b/ckan/tests/functional/test_admin.py index ad5bf3f21cb..ad6b304ee43 100644 --- a/ckan/tests/functional/test_admin.py +++ b/ckan/tests/functional/test_admin.py @@ -31,17 +31,6 @@ class TestAdminAuthzController(WsgiAppCase): def setup_class(cls): # setup test data including testsysadmin user CreateTestData.create() - # Creating a couple of authorization groups, which are enough to break - # some things just by their existence - for ag_name in [u'anauthzgroup', u'anotherauthzgroup']: - ag=model.AuthorizationGroup.by_name(ag_name) - if not ag: #may already exist, if not create - ag=model.AuthorizationGroup(name=ag_name) - model.Session.add(ag) - model.Session.commit() - #they are especially dangerous if they have a role on the System - ag = model.AuthorizationGroup.by_name(u'anauthzgroup') - model.add_authorization_group_to_role(ag, u'editor', model.System()) model.Session.commit() @classmethod @@ -57,10 +46,6 @@ def get_system_user_roles(): sys_query=model.Session.query(model.SystemRole) return sorted([(x.user.name,x.role) for x in sys_query.all() if x.user]) - def get_system_authzgroup_roles(): - sys_query=model.Session.query(model.SystemRole) - return sorted([(x.authorized_group.name,x.role) for x in sys_query.all() if x.authorized_group]) - def get_response(): response = self.app.get( url_for('ckanadmin', action='authz'), @@ -72,9 +57,6 @@ def get_user_form(): response = get_response() return response.forms['theform'] - def get_authzgroup_form(): - response = get_response() - return response.forms['authzgroup_form'] def check_and_set_checkbox(theform, user, role, should_be, set_to): user_role_string = '%s$%s' % (user, role) @@ -98,63 +80,27 @@ def submit(form): def authz_submit(form): return form.submit('authz_save', extra_environ=as_testsysadmin) - + # get and store the starting state of the system roles original_user_roles = get_system_user_roles() - original_authzgroup_roles = get_system_authzgroup_roles() - - # also keep a copy that we can update as the tests go on - expected_user_roles = get_system_user_roles() - expected_authzgroup_roles = get_system_authzgroup_roles() # before we start changing things, check that the roles on the system are as expected assert original_user_roles == \ [(u'logged_in', u'editor'), (u'testsysadmin', u'admin'), (u'visitor', u'reader')] , \ "original user roles not as expected " + str(original_user_roles) - assert original_authzgroup_roles == [(u'anauthzgroup', u'editor')], \ - "original authzgroup roles not as expected" + str(original_authzgroup_roles) - # visitor is not an admin. check that his admin box is unticked, tick it, and submit submit(check_and_set_checkbox(get_user_form(), u'visitor', u'admin', False, True)) - # update expected state to reflect the change we should just have made - expected_user_roles.append((u'visitor', u'admin')) - expected_user_roles.sort() - - # and check that's the state in the database now - assert get_system_user_roles() == expected_user_roles - assert get_system_authzgroup_roles() == expected_authzgroup_roles - # try again, this time we expect the box to be ticked already submit(check_and_set_checkbox(get_user_form(), u'visitor', u'admin', True, True)) - # performing the action twice shouldn't have changed anything - assert get_system_user_roles() == expected_user_roles - assert get_system_authzgroup_roles() == expected_authzgroup_roles - - # now let's make the authzgroup which already has a system role an admin - authz_submit(check_and_set_checkbox(get_authzgroup_form(), u'anauthzgroup', u'admin', False, True)) - - # update expected state to reflect the change we should just have made - expected_authzgroup_roles.append((u'anauthzgroup', u'admin')) - expected_authzgroup_roles.sort() - - # check that's happened - assert get_system_user_roles() == expected_user_roles - assert get_system_authzgroup_roles() == expected_authzgroup_roles - # put it back how it was submit(check_and_set_checkbox(get_user_form(), u'visitor', u'admin', True, False)) - authz_submit(check_and_set_checkbox(get_authzgroup_form(), u'anauthzgroup', u'admin', True, False)) # should be back to our starting state assert original_user_roles == get_system_user_roles() - assert original_authzgroup_roles == get_system_authzgroup_roles() - - - # now test making multiple changes # change lots of things @@ -162,7 +108,7 @@ def authz_submit(form): check_and_set_checkbox(form, u'visitor', u'editor', False, True) check_and_set_checkbox(form, u'visitor', u'reader', True, False) check_and_set_checkbox(form, u'logged_in', u'editor', True, False) - check_and_set_checkbox(form, u'logged_in', u'reader', False, True) + check_and_set_checkbox(form, u'logged_in', u'reader', False, True) submit(form) roles=get_system_user_roles() @@ -177,9 +123,7 @@ def authz_submit(form): def get_roles_by_name(user=None, group=None): if user: return [y for (x,y) in get_system_user_roles() if x==user] - elif group: - return [y for (x,y) in get_system_authzgroup_roles() if x==group] - else: + else: assert False, 'miscalled' @@ -205,23 +149,6 @@ def get_roles_by_name(user=None, group=None): assert get_roles_by_name(user=u'tester') == ['admin'], \ "tester should be an admin now" - # and similarly for an arbitrary authz group - assert get_roles_by_name(group=u'anotherauthzgroup') == [], \ - "should not have roles" - - form = get_response().forms['authzgroup_addform'] - form.fields['new_user_name'][0].value='anotherauthzgroup' - checkbox = [x for x in form.fields['reader'] \ - if x.__class__.__name__ == 'Checkbox'][0] - assert checkbox.checked == False - checkbox.checked=True - - response = form.submit('authz_add', extra_environ=as_testsysadmin) - assert "Authorization Group Added" in response, "don't see flash message" - - - assert get_roles_by_name(group=u'anotherauthzgroup') == [u'reader'], \ - "should be a reader now" class TestAdminTrashController(WsgiAppCase): @@ -266,7 +193,7 @@ def test_purge_package(self): url = url_for('ckanadmin', action='trash') response = self.app.get(url, extra_environ=as_testsysadmin) assert 'dataset/warandpeace' in response, response - + # Check we get correct error message on attempted purge form = response.forms['form-purge-packages'] response = form.submit('purge-packages', status=[302], diff --git a/ckan/tests/functional/test_authorization_group.py b/ckan/tests/functional/test_authorization_group.py deleted file mode 100644 index 3d223a52a33..00000000000 --- a/ckan/tests/functional/test_authorization_group.py +++ /dev/null @@ -1,440 +0,0 @@ -from nose.plugins.skip import SkipTest -from nose.tools import assert_equal - -from ckan.tests import * -from ckan.authz import Authorizer -import ckan.model as model -from base import FunctionalTestCase -from ckan.tests import search_related - -class TestAuthorizationGroup(FunctionalTestCase): - - @classmethod - def setup_class(self): - model.Session.remove() - model.repo.init_db() - CreateTestData.create() - model.repo.new_revision() - treasury = model.AuthorizationGroup(name=u'treasury') - health = model.AuthorizationGroup(name=u'health') - model.Session.add(treasury) - model.Session.add(health) - model.add_user_to_authorization_group(model.User.by_name(u"russianfan"), - treasury, model.Role.ADMIN) - model.repo.commit_and_remove() - - @classmethod - def teardown_class(self): - model.Session.remove() - model.repo.rebuild_db() - model.Session.remove() - - def test_index(self): - offset = url_for(controller='authorization_group', action='index') - res = self.app.get(offset, extra_environ={'REMOTE_USER': 'russianfan'}) - assert '

    Authorization Groups

    ' in res, res - group_count = Authorizer.authorized_query(u'russianfan', model.AuthorizationGroup).count() - assert 'There are %s authorization groups.' % group_count in self.strip_tags(res), res - authz_groupname = u'treasury' - authz_group = model.AuthorizationGroup.by_name(unicode(authz_groupname)) - group_users_count = len(authz_group.users) - self.check_named_element(res, 'tr', authz_groupname, group_users_count) - #res = res.click(authz_groupname) - #assert authz_groupname in res, res - - def test_read(self): - name = u'treasury' - offset = url_for(controller='authorization_group', action='read', id=name) - res = self.app.get(offset, extra_environ={'REMOTE_USER': 'russianfan'}) - main_res = self.main_div(res) - assert '%s - Authorization Groups' % name in res, res - #assert 'edit' in main_res, main_res - assert name in res, res - - def test_new(self): - offset = url_for(controller='authorization_group', action='index') - res = self.app.get(offset, extra_environ={'REMOTE_USER': 'russianfan'}) - assert 'Create a new authorization group' in res, res - - -class TestEdit(TestController): - groupname = u'treasury' - - @classmethod - def setup_class(self): - model.Session.remove() - CreateTestData.create() - model.repo.new_revision() - treasury = model.AuthorizationGroup(name=u'treasury') - health = model.AuthorizationGroup(name=u'health') - model.Session.add(treasury) - model.Session.add(health) - model.add_user_to_authorization_group(model.User.by_name(u"russianfan"), - treasury, model.Role.ADMIN) - model.repo.commit_and_remove() - - self.username = u'testusr' - model.repo.new_revision() - model.Session.add(model.User(name=self.username)) - model.repo.commit_and_remove() - - @classmethod - def teardown_class(self): - model.Session.remove() - model.repo.rebuild_db() - model.Session.remove() - - def test_0_not_authz(self): - offset = url_for(controller='authorization_group', action='edit', id=self.groupname) - # 401 gets caught by repoze.who and turned into redirect - res = self.app.get(offset, status=[302, 401]) - res = res.follow() - assert res.request.url.startswith('/user/login') - - def test_1_read_allowed_for_admin(self): - raise SkipTest() - offset = url_for(controller='authorization_group', action='edit', id=self.groupname) - res = self.app.get(offset, status=200, extra_environ={'REMOTE_USER': 'russianfan'}) - assert 'Edit Authorization Group: %s' % self.groupname in res, res - - def test_2_edit(self): - raise SkipTest() - offset = url_for(controller='authorization_group', action='edit', id=self.groupname) - res = self.app.get(offset, status=200, extra_environ={'REMOTE_USER': 'russianfan'}) - assert 'Edit Authorization Group: %s' % self.groupname in res, res - - form = res.forms['group-edit'] - group = model.AuthorizationGroup.by_name(self.groupname) - usr = model.User.by_name(self.username) - form['AuthorizationGroupUser--user_name'] = usr.name - - res = form.submit('save', status=302, extra_environ={'REMOTE_USER': 'russianfan'}) - # should be read page - # assert 'Groups - %s' % self.groupname in res, res - - model.Session.remove() - group = model.AuthorizationGroup.by_name(self.groupname) - - # now look at packages - assert len(group.users) == 2 - - -class TestNew(FunctionalTestCase): - groupname = u'treasury' - - @classmethod - def setup_class(self): - CreateTestData.create_user('tester1') - CreateTestData.create_user('tester2') - CreateTestData.create_user('tester3') - - self.extra_environ = {'REMOTE_USER': 'tester1'} - - @classmethod - def teardown_class(self): - model.repo.rebuild_db() - - def test_0_new(self): - offset = url_for(controller='authorization_group', action='new', id=None) - res = self.app.get(offset, status=200, extra_environ=self.extra_environ) - assert 'New Authorization Group' in res, res - - form = res.forms['group-edit'] - form['AuthorizationGroup--name'] = 'testname' - - # can't test users - needs javascript - #form['AuthorizationGroupUser--user_name'] = 'tester2' - - res = form.submit('save', status=302, extra_environ=self.extra_environ) - res = res.follow() - - # should be read page - main_res = self.main_div(res) - assert 'testname' in main_res, main_res - - # test created object - auth_group = model.AuthorizationGroup.by_name('testname') - assert auth_group - assert_equal(auth_group.name, 'testname') - - def test_0_new_without_name(self): - offset = url_for(controller='authorization_group', action='new', id=None) - res = self.app.get(offset, status=200, extra_environ=self.extra_environ) - assert 'New Authorization Group' in res, res - - form = res.forms['group-edit'] - # don't set name - - res = form.submit('save', status=200, extra_environ=self.extra_environ) - assert 'Error' in res, res - assert 'Name: Please enter a value' in res, res - - -class TestAuthorizationGroupWalkthrough(FunctionalTestCase): - - @classmethod - def setup_class(self): - model.Session.remove() - model.repo.init_db() - CreateTestData.create() - model.repo.commit_and_remove() - - - @classmethod - def teardown_class(self): - model.Session.remove() - model.repo.rebuild_db() - model.Session.remove() - - - ## THIS WALKTHROUGH IS NOW COMPLETELY BROKEN BY THE CHANGES I MADE TO THE AUTHZ PAGE - - - # def test_authzgroups_walkthrough(self): - # # very long test sequence repeating the series of things I did to - # # convince myself that the authzgroups system worked as expected, - # # starting off with the default test data - - # # The first thing to notice is that the authzgroup page: - # auth_group_index_url = url_for(controller='/authorization_group', action='index') - # # displays differently for different users. - - # def get_page(url, expect_status, username, assert_text=None, error_text=None): - # res= self.app.get(url, - # status=expect_status, - # extra_environ={'REMOTE_USER': username}) - # if assert_text and assert_text not in res: - # errorstring = error_text + ' ( "' + assert_text + \ - # '" not found in result of getting "' + \ - # url + '" as user "' + username + '" )' - # assert False, errorstring - # return res - - # # testsysadmin sees the true picture, where the test data contains two groups - # get_page(auth_group_index_url, 200, 'testsysadmin', - # 'There are 2 authorization groups', - # 'Should be accurate for testsysadmin') - - # # But if we look at the same page as annafan, who does not have read - # # permissions on these groups, we should see neither - # get_page(auth_group_index_url, 200, 'annafan', - # 'There are 0 authorization groups', - # 'Should lie to annafan about number of groups') - - # # There is a page for each group - # anauthzgroup_url = url_for(controller='/authorization_group', - # action='read', - # id='anauthzgroup') - # # And an edit page - # anauthzgroup_edit_url = url_for(controller='/authorization_group', - # action='edit', - # id='anauthzgroup') - - # # testsysadmin should be able to see this, and check that there are no members - # get_page(anauthzgroup_url, 200, 'testsysadmin', - # 'There are 0 users in this', - # 'should be no users in anauthzgroup') - - # # now testsysadmin adds annafan to anauthzgroup via the edit page - # res = get_page(anauthzgroup_edit_url, 200, 'testsysadmin') - # group_edit_form = res.forms['group-edit'] - # group_edit_form['AuthorizationGroupUser--user_name'] = u'annafan' - # submit_res = group_edit_form.submit('save', - # extra_environ={'REMOTE_USER': 'testsysadmin'}) - - # # adding a user to a group should both make her a member, and give her - # # read permission on the group. We'll check those things have actually - # # happened by looking directly in the model. - # anauthzgroup = model.AuthorizationGroup.by_name('anauthzgroup') - # anauthzgroup_users = [x.name for x in anauthzgroup.users] - # anauthzgroup_user_roles = [(x.user.name, x.role) for x in anauthzgroup.roles if x.user] - # assert anauthzgroup_users == [u'annafan'], \ - # 'anauthzgroup should contain annafan (only)' - # assert anauthzgroup_user_roles == [(u'annafan', u'reader')],\ - # 'annafan should be a reader' - - # # Since annafan has been added to anauthzgroup, which is an admin on - # # anotherauthzgroup, she should now be able to see both the groups. - # get_page(auth_group_index_url, 200, 'annafan', - # 'There are 2 auth', - # "annafan should now be able to see both groups") - - # # When annafan looks at the page for anauthzgroup now - # # She should see that there's one user: - # get_page(anauthzgroup_url, 200,'annafan', - # 'There are 1 users in this', - # 'annafan should be able to see the list of members') - - # # Which is her, so her name should be in there somewhere: - # get_page(anauthzgroup_url, 200,'annafan', - # 'annafan', - # 'annafan should be listed as a member') - - # # But she shouldn't be able to see the edit page for that group. - - # # The behaviour of the test setup here is a bit weird, since in the - # # browser she gets redirected to the login page, but from these tests, - # # she just gets a 401, with no apparent redirect. Sources inform me - # # that this is normal, and to do with repoze being in the application - # # stack but not in the test stack. - # get_page(anauthzgroup_edit_url, 401, 'annafan', - # 'not authorized to edit', - # 'annafan should not be able to edit the list of members') - # # this behaviour also means that we get a flash message left over, which appears on - # # whatever the next page is. - - # # I'm going to assert that behaviour here, just to note it. It's most - # # definitely not required functionality! We'll do a dummy fetch of the - # # main page for anauthzgroup, which will have the errant flash message - # get_page(anauthzgroup_url, 200, 'annafan', - # 'not authorized to edit', - # 'flash message should carry over to next fetch') - - # # But if we do the dummy fetch twice, the flash message should have gone - # res = get_page(anauthzgroup_url, 200, 'annafan') - # assert 'not authorized to edit' not in res, 'flash message should have gone' - - # # Since annafan is now a member of anauthzgroup, she should have admin privileges - # # on anotherauthzgroup - # anotherauthzgroup_edit_url = url_for(controller='/authorization_group', - # action='edit', - # id='anotherauthzgroup') - - # # Which means that she can go to the edit page: - # res = get_page(anotherauthzgroup_edit_url, 200, 'annafan', - # 'There are no users', - # "There shouldn't be any users in anotherauthzgroup") - - # # And change the name of the group - # # The group name editing box has a name dependent on the id of the group, - # # so we find it by regex in the page. - # import re - # p = re.compile('AuthorizationGroup-.*-name') - # groupnamebox = [ v for k,v in res.forms['group-edit'].fields.items() if p.match(k)][0][0] - # groupnamebox.value = 'annasauthzgroup' - # res = res.forms['group-edit'].submit('save', extra_environ={'REMOTE_USER': 'annafan'}) - # res = res.follow() - - # ## POTENTIAL BUG: - # # note that she could change the name of the group to anauthzgroup, - # # which causes problems due to the name collision. This should be - # # guarded against. - - - # # annafan should still be able to see the admin and edit pages of the - # # newly renamed group by virtue of being a member of anauthzgroup - # annasauthzgroup_authz_url = url_for(controller='/authorization_group', - # action='authz', - # id='annasauthzgroup') - - # annasauthzgroup_edit_url = url_for(controller='/authorization_group', - # action='edit', - # id='annasauthzgroup') - - - # res = get_page(annasauthzgroup_authz_url, 200, 'annafan', - # 'Authorization for authorization group: annasauthzgroup', - # 'should be authz page') - - # # annafan has the power to remove anauthzgroup's admin role on her group - # # The button to remove that role is a link, rather than a submit. I - # # assume there is a better way to do this than searching by regex, but I - # # can't find it. - # import re - # delete_links = re.compile('').findall(res.body) - # assert len(delete_links) == 1, "There should only be one delete link here" - # delete_link = delete_links[0] - - # # Paranoid check, try to follow link without credentials. Should be redirected. - # res = self.app.get(delete_link, status=302) - # res = res.follow() - # assert 'Not authorized to edit authorization for group' in res,\ - # "following link without credentials should result in redirection to login page" - - # # Now follow it as annafan, which should work. - # get_page(delete_link, 200,'annafan', - # "Deleted role 'admin' for authorization group 'anauthzgroup'", - # "Page should mention the deleted role") - - # # Trying it a second time should fail since she's now not an admin. - # get_page(delete_link, 401,'annafan') - - # # No one should now have any rights on annasauthzgroup, including - # # annafan herself. So this should fail too. Again, get a 401 error - # # here, but in the browser we get redirected if we try. - # get_page(annasauthzgroup_authz_url, 401,'annafan') - - # # testsysadmin can put her back. - # # It appears that the select boxes on this form need to be set by id - # anauthzgroupid = model.AuthorizationGroup.by_name(u'anauthzgroup').id - # annafanid = model.User.by_name(u'annafan').id - - # # first try to make both anauthzgroup and annafan editors. This should fail. - # res = get_page(annasauthzgroup_authz_url,200, 'testsysadmin') - # gaf= res.forms['group-authz'] - # gaf['AuthorizationGroupRole--authorized_group_id'] = anauthzgroupid - # gaf['AuthorizationGroupRole--role'] = 'editor' - # gaf['AuthorizationGroupRole--user_id'] = annafanid - # res = gaf.submit('save', status=200, extra_environ={'REMOTE_USER': 'testsysadmin'}) - # assert 'Please select either a user or an authorization group, not both.' in res,\ - # 'request should fail if you change both user and authz group' - - # # settle for just doing one at a time. make anauthzgroup an editor - # res = get_page(annasauthzgroup_authz_url, 200, 'testsysadmin') - # gaf= res.forms['group-authz'] - # gaf['AuthorizationGroupRole--authorized_group_id'] = anauthzgroupid - # gaf['AuthorizationGroupRole--role'] = 'editor' - # res = gaf.submit('save',status=200, extra_environ={'REMOTE_USER': 'testsysadmin'}) - # assert "Added role 'editor' for authorization group 'anauthzgroup'" in res, \ - # "no flash message" - - # # and make annafan a reader - # res = get_page(annasauthzgroup_authz_url, 200, 'testsysadmin') - # gaf= res.forms['group-authz'] - # gaf['AuthorizationGroupRole--user_id'] = annafanid - # gaf['AuthorizationGroupRole--role'] = 'reader' - # res = gaf.submit('save', status=200, extra_environ={'REMOTE_USER': 'testsysadmin'}) - # assert "Added role 'reader' for user 'annafan'" in res, "no flash message" - - # # annafan should now be able to add her friends to annasauthzgroup - # res = get_page(annasauthzgroup_edit_url, 200, 'annafan') - # res.forms['group-edit']['AuthorizationGroupUser--user_name']='tester' - # # this follows the post/redirect/get pattern - # res = res.forms['group-edit'].submit('save', status=302, - # extra_environ={'REMOTE_USER': 'annafan'}) - # res = res.follow(status=200, extra_environ={'REMOTE_USER': 'annafan'}) - # # and she gets redirected to the group view page - # assert 'tester' in res, 'tester not added?' - - # # she needs to do them one by one - # res = get_page(annasauthzgroup_edit_url, 200, 'annafan', - # 'tester', - # 'tester not in edit form') - # res.forms['group-edit']['AuthorizationGroupUser--user_name']='russianfan' - # res = res.forms['group-edit'].submit('save', status=302, extra_environ={'REMOTE_USER': 'annafan'}) - # res = res.follow(status=200, extra_environ={'REMOTE_USER': 'annafan'}) - - # # and finally adds herself - # res = self.app.get(annasauthzgroup_edit_url, status=200, extra_environ={'REMOTE_USER': 'annafan'}) - # assert 'russianfan' in res, 'russianfan not added?' - # res.forms['group-edit']['AuthorizationGroupUser--user_name']='annafan' - # res = res.forms['group-edit'].submit('save', status=302, extra_environ={'REMOTE_USER': 'annafan'}) - # res = res.follow(status=200, extra_environ={'REMOTE_USER': 'annafan'}) - # assert 'annafan' in res, 'annafan not added?' - - # # finally let's check that annafan can create a completely new authzgroup - # new_authzgroup_url = url_for(controller='/authorization_group', action='new') - # res = get_page(new_authzgroup_url, 200,'annafan', - # 'New Authorization Group', - # "wrong page?") - # gef = res.forms['group-edit'] - # gef['AuthorizationGroup--name']="newgroup" - # gef['AuthorizationGroupUser--user_name'] = "russianfan" - # res = gef.submit('save', status=302, extra_environ={'REMOTE_USER': 'annafan'}) - # #post/redirect/get - # res = res.follow(status=200, extra_environ={'REMOTE_USER': 'annafan'}) - - # assert 'newgroup' in res, "should have redirected to the newgroup page" - # assert 'russianfan' in res, "no russianfan" - # assert 'There are 1 users in this authorization group' in res, "missing text" - diff --git a/ckan/tests/functional/test_authz.py b/ckan/tests/functional/test_authz.py index bd8bcb9f11e..cafc3c99dbc 100644 --- a/ckan/tests/functional/test_authz.py +++ b/ckan/tests/functional/test_authz.py @@ -628,7 +628,7 @@ def test_user_pages(self): self._check_logged_in_users_authorized_only('/user') self._check_logged_in_users_authorized_only('/user/' + self.user_name) res = self.app.get('/user/login', extra_environ={}) - assert res.status in [200], res.status + assert res.status in [200, 302], res.status def test_new_package(self): offset = url_for(controller='package', action='new') diff --git a/ckan/tests/functional/test_edit_authz.py b/ckan/tests/functional/test_edit_authz.py index 941332ddb9a..d3c01607990 100644 --- a/ckan/tests/functional/test_edit_authz.py +++ b/ckan/tests/functional/test_edit_authz.py @@ -7,7 +7,7 @@ def check_and_set_checkbox(theform, user, role, should_be, set_to): '''Given an authz form, find the checkbox associated with the strings user and role, assert that it\'s in the state 'should_be', and set it to 'set_to' ''' - user_id = (model.User.get(user) or model.AuthorizationGroup.get(user)).id + user_id = model.User.get(user).id user_role_string = '%s$%s' % (user_id, role) checkboxes = [x for x in theform.fields[user_role_string] \ if x.__class__.__name__ == 'Checkbox'] @@ -30,9 +30,8 @@ class TestEditAuthz(TestController): def setup_class(self): # for the authorization editing tests we set up test data so: # three users, sysadmin , administrator, and another - # one authzgroup, one group, one package + # one group, one package # and administrator is admin on all three - # one extra authzgroup, authzgroup2, with no permissions to start with model.repo.init_db() model.repo.new_revision() @@ -42,15 +41,11 @@ def setup_class(self): admin_user = model.User(name=unicode(self.admin)) self.another = 'another' another_user = model.User(name=unicode(self.another)) - self.authzgroup = 'authzgroup' - authzgroup = model.AuthorizationGroup(name=unicode(self.authzgroup)) self.group = 'group' group = model.Group(name=unicode(self.group)) - self.authzgroup2 = 'authzgroup2' - authzgroup2 = model.AuthorizationGroup(name=unicode(self.authzgroup2)) - for obj in sysadmin_user, admin_user, another_user, authzgroup, group, authzgroup2: + for obj in sysadmin_user, admin_user, another_user, group: model.Session.add(obj) model.add_user_to_role(sysadmin_user, model.Role.ADMIN, model.System()) @@ -67,7 +62,6 @@ def setup_class(self): # setup all three authorization objects to have logged in and visitor as editors, and the admin as admin model.setup_user_roles(pkg, ['editor'], ['editor'], [admin_user]) - model.setup_user_roles(authzgroup, ['editor'], ['editor'], [admin_user]) model.setup_user_roles(group, ['editor'], ['editor'], [admin_user]) model.repo.commit_and_remove() @@ -78,7 +72,7 @@ def teardown_class(self): def test_access_to_authz(self): #for each of the three authz pages, check that the access permissions work correctly - for (c,i) in [('package', self.pkg),('group', self.group),('authorization_group', self.authzgroup)]: + for (c,i) in [('package', self.pkg),('group', self.group)]: offset = url_for(controller=c, action='authz', id=i) # attempt to access the authz pages without credentials should result in getting redirected to the login page @@ -101,9 +95,7 @@ def test_access_to_authz(self): def roles_list(self, authzobj): # get a list of username/roles for a given authorizable object - list = [ (r.user.name, r.role) for r in authzobj.roles if r.user] - list.extend([(r.authorized_group.name, r.role) for r in authzobj.roles if r.authorized_group]) - return list + return [ (r.user.name, r.role) for r in authzobj.roles if r.user] # get the users/roles for the specific objects created in our test data def package_roles(self): @@ -112,14 +104,11 @@ def package_roles(self): def group_roles(self): return self.roles_list(model.Group.by_name(self.group)) - def authzgroup_roles(self): - return self.roles_list(model.AuthorizationGroup.by_name(self.authzgroup)) # check that the authz page for each object contains certain key strings def test_2_read_ok(self): for (c,i,m) in [('package', self.pkg, self.package_roles),\ - ('group', self.group, self.group_roles),\ - ('authorization_group', self.authzgroup, self.authzgroup_roles)]: + ('group', self.group, self.group_roles)]: offset = url_for(controller=c, action='authz', id=i) res = self.app.get(offset, extra_environ={'REMOTE_USER': self.admin}) assert i in res, res @@ -161,9 +150,8 @@ def change_roles(self, user): # loop variables here are the controller string, the name of the object we're changing, and three functions, # the first fn gets the roles which we'd like to change, and the other two get the roles which we'd like to stay the same. - for (c,i,var,const1,const2) in [('package', self.pkg, self.package_roles, self.group_roles, self.authzgroup_roles),\ - ('group', self.group, self.group_roles, self.package_roles, self.authzgroup_roles),\ - ('authorization_group', self.authzgroup, self.authzgroup_roles, self.package_roles, self.group_roles)]: + for (c,i,var,const1) in [('package', self.pkg, self.package_roles, self.group_roles),\ + ('group', self.group, self.group_roles, self.package_roles)]: # load authz page offset = url_for(controller=c, action='authz', id=i) @@ -172,7 +160,6 @@ def change_roles(self, user): self.assert_roles_to_be(var(), normal_roles) self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) #admin makes visitor a reader and logged in an admin form = res.forms['theform'] @@ -186,7 +173,6 @@ def change_roles(self, user): # ensure db was changed self.assert_roles_to_be(var(), changed_roles) self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) # ensure rerender of form is changed offset = url_for(controller=c, action='authz', id=i) @@ -205,10 +191,9 @@ def change_roles(self, user): # ensure db was changed self.assert_roles_to_be(var(), normal_roles) self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) - # do the change roles both as package/group/authzgroup admin, and also as sysadmin. + # do the change roles both as package/group admin, and also as sysadmin. def test_3_admin_changes_role(self): self.change_roles(self.admin) @@ -231,9 +216,8 @@ def delete_role_as(self,user): # loop variables here are the controller string, the name of the object we're changing, and three functions, # the first fn gets the roles which we'd like to change, and the other two get the roles which we'd like to stay the same. - for (c,i,var,const1,const2) in [('package', self.pkg, self.package_roles, self.group_roles, self.authzgroup_roles),\ - ('group', self.group, self.group_roles, self.package_roles, self.authzgroup_roles),\ - ('authorization_group', self.authzgroup, self.authzgroup_roles, self.package_roles, self.group_roles)]: + for (c,i,var,const1) in [('package', self.pkg, self.package_roles, self.group_roles),\ + ('group', self.group, self.group_roles, self.package_roles)]: # get the authz page, check that visitor's in there # remove visitor's role on the package @@ -244,7 +228,6 @@ def delete_role_as(self,user): self.assert_roles_to_be(var(), normal_roles) self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) assert 'visitor' in res assert 'administrator' in res @@ -258,7 +241,6 @@ def delete_role_as(self,user): # ensure db was changed self.assert_roles_to_be(var(), changed_roles) self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) # ensure rerender of form is changed offset = url_for(controller=c, action='authz', id=i) @@ -294,7 +276,6 @@ def delete_role_as(self,user): # check that the roles in the db are back to normal self.assert_roles_to_be(var(), changed_roles2) self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) # now change him back to being an editor form = res.forms['theform'] @@ -310,7 +291,6 @@ def delete_role_as(self,user): # check that the roles in the db are back to normal self.assert_roles_to_be(var(), normal_roles) self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) @@ -321,101 +301,3 @@ def test_4_sysadmin_deletes_role(self): self.delete_role_as(self.sysadmin) - # now a version of the above tests dealing with permissions assigned to authzgroups - # (as opposed to on authzgroups) - def add_change_delete_authzgroup_as(self, user): - - normal_roles=[('administrator', 'admin'), - ('visitor', 'editor'), - ('logged_in', 'editor')] - - changed_roles=[('authzgroup2', 'admin'), - ('administrator', 'admin'), - ('visitor', 'editor'), - ('logged_in', 'editor')] - - changed_roles_2=[('authzgroup2', 'editor'), - ('administrator', 'admin'), - ('visitor', 'editor'), - ('logged_in', 'editor')] - - for (c,i,var,const1,const2) in [('package', self.pkg, self.package_roles, self.group_roles, self.authzgroup_roles),\ - ('group', self.group, self.group_roles, self.package_roles, self.authzgroup_roles),\ - ('authorization_group', self.authzgroup, self.authzgroup_roles, self.package_roles, self.group_roles)]: - - # get the authz page, check that it contains the object name - offset = url_for(controller=c, action='authz', id=i) - res = self.app.get(offset, extra_environ={'REMOTE_USER':user}) - assert i in res - - # check the state of the database - self.assert_roles_to_be(var(), normal_roles) - self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) - - # and that corresponding user strings are in the authz page - # particularly that authzgroup2 isn't there (yet) - assert 'visitor' in res - assert 'administrator' in res - assert 'logged_in' in res - assert 'authzgroup2' not in res - - # add authzgroup2 as an admin - form = res.forms['authzgroup_addform'] - form.fields['new_user_name'][0].value='authzgroup2' - checkbox = [x for x in form.fields['admin'] \ - if x.__class__.__name__ == 'Checkbox'][0] - # check the checkbox is currently unticked - assert checkbox.checked == False - # tick it and submit - checkbox.checked=True - res = form.submit('authz_add', extra_environ={'REMOTE_USER':user}) - assert "User role(s) added" in res, "don't see flash message" - - # examine the new page for user names/authzgroup names - assert 'visitor' in res - assert 'administrator' in res - assert 'logged_in' in res - assert 'authzgroup2' in res - - # and ensure that the database has changed as expected - self.assert_roles_to_be(var(), changed_roles) - self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) - - # check that the checkbox states are what we think they should be - # and change authzgroup2 from admin to editor - form = res.forms['authzgroup_form'] - check_and_set_checkbox(form, u'authzgroup2', u'editor', False, True) - check_and_set_checkbox(form, u'authzgroup2', u'admin', True, False) - res = form.submit('authz_save', extra_environ={'REMOTE_USER': user}) - - #check database has changed. - self.assert_roles_to_be(var(), changed_roles_2) - self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) - - - # now remove authzgroup2 entirely - form = res.forms['authzgroup_form'] - check_and_set_checkbox(form, u'authzgroup2', u'editor', True, False) - check_and_set_checkbox(form, u'authzgroup2', u'admin', False, False) - res = form.submit('authz_save', extra_environ={'REMOTE_USER': user}) - - #check database is back to normal - self.assert_roles_to_be(var(), normal_roles) - self.assert_roles_to_be(const1(), normal_roles) - self.assert_roles_to_be(const2(), normal_roles) - - # and that page contains only the expected strings - assert 'visitor' in res - assert 'administrator' in res - assert 'logged_in' in res - assert 'authzgroup2' not in res - - - def test_5_admin_changes_adds_deletes_authzgroup(self): - self.add_change_delete_authzgroup_as(self.admin) - - def test_5_sysadmin_changes_adds_deletes_authzgroup(self): - self.add_change_delete_authzgroup_as(self.sysadmin) diff --git a/ckan/tests/functional/test_package_edit_authz.py b/ckan/tests/functional/test_package_edit_authz.py index 3dbf6df1a66..e26b06fcb1e 100644 --- a/ckan/tests/functional/test_package_edit_authz.py +++ b/ckan/tests/functional/test_package_edit_authz.py @@ -10,20 +10,17 @@ class TestPackageEditAuthz(TestController): def setup_class(self): # for the authorization editing tests we set up test data so: # three users, madeup-sysadmin , madeup-administrator, and madeup-another - # one authzgroup # two packages test6 and test6a, m-a is admin on both model.repo.init_db() model.repo.new_revision() - + self.sysadmin = 'madeup-sysadmin' sysadmin_user = model.User(name=unicode(self.sysadmin)) self.admin = 'madeup-administrator' admin_user = model.User(name=unicode(self.admin)) self.another = u'madeup-another' another_user = model.User(name=unicode(self.another)) - self.authzgroup = u'madeup-authzgroup' - authzgroup = model.AuthorizationGroup(name=unicode(self.authzgroup)) - for obj in sysadmin_user, admin_user, another_user, authzgroup: + for obj in sysadmin_user, admin_user, another_user: model.Session.add(obj) model.add_user_to_role(sysadmin_user, model.Role.ADMIN, model.System()) @@ -51,7 +48,7 @@ def test_0_nonadmin_cannot_edit_authz(self): res = self.app.get(offset, status=[302, 401]) res = res.follow() assert res.request.url.startswith('/user/login') - + def test_1_admin_has_access(self): offset = url_for(controller='package', action='authz', id=self.pkgname) res = self.app.get(offset, extra_environ={'REMOTE_USER': @@ -61,7 +58,7 @@ def test_1_sysadmin_has_access(self): offset = url_for(controller='package', action='authz', id=self.pkgname) res = self.app.get(offset, extra_environ={'REMOTE_USER': self.sysadmin}) - + def test_2_read_ok(self): offset = url_for(controller='package', action='authz', id=self.pkgname) res = self.app.get(offset, extra_environ={'REMOTE_USER': @@ -77,9 +74,8 @@ def test_2_read_ok(self): def package_roles(self): pkg = model.Package.by_name(self.pkgname) - list = [ (r.user.name, r.role) for r in pkg.roles if r.user] - list.extend([(r.authorized_group.name, r.role) for r in pkg.roles if r.authorized_group]) - return list + return [ (r.user.name, r.role) for r in pkg.roles if r.user] + def assert_package_roles_to_be(self, roles_list): prs=self.package_roles() @@ -215,80 +211,3 @@ def test_4_admin_deletes_role(self): def test_4_sysadmin_deletes_role(self): self.delete_role_as(self.sysadmin) - - def test_5_add_change_delete_authzgroup(self): - user=self.admin - - # get the authz page, check that authzgroup isn't in there - offset = url_for(controller='package', action='authz', id=self.pkgname) - res = self.app.get(offset, extra_environ={'REMOTE_USER':user}) - assert self.pkgname in res - - # check the state of the database - self.assert_package_roles_to_be([ - ('madeup-administrator', 'admin'), - ('visitor', 'reader'), - ('logged_in', 'reader')]) - - # and that corresponding user strings are in the authz page - assert 'visitor' in res - assert 'madeup-administrator' in res - assert 'logged_in' in res - assert 'madeup-authzgroup' not in res - - # add madeup-authzgroup as an admin - form = res.forms['authzgroup_addform'] - form.fields['new_user_name'][0].value='madeup-authzgroup' - checkbox = [x for x in form.fields['admin'] \ - if x.__class__.__name__ == 'Checkbox'][0] - # check the checkbox is currently unticked - assert checkbox.checked == False - # tick it and submit - checkbox.checked=True - res = form.submit('authz_add', extra_environ={'REMOTE_USER':user}) - assert "User role(s) added" in res, "don't see flash message" - - # examine the new page for user names/authzgroup names - assert 'visitor' in res - assert 'madeup-administrator' in res - assert 'logged_in' in res - assert 'madeup-authzgroup' in res - - # and ensure that the database has changed as expected - self.assert_package_roles_to_be([ - ('madeup-authzgroup', 'admin'), - ('madeup-administrator', 'admin'), - ('visitor', 'reader'), - ('logged_in', 'reader')]) - - # check that the checkbox states are what we think they should be - # and change madeup-authzgroup from admin to editor - form = res.forms['authzgroup_form'] - check_and_set_checkbox(form, u'madeup-authzgroup', u'editor', False, True) - check_and_set_checkbox(form, u'madeup-authzgroup', u'admin', True, False) - res = form.submit('authz_save', extra_environ={'REMOTE_USER': user}) - - #check database has changed. - self.assert_package_roles_to_be([ - ('madeup-authzgroup', 'editor'), - ('madeup-administrator', 'admin'), - ('visitor', 'reader'), - ('logged_in', 'reader')]) - - # now remove madeup-authzgroup entirely - form = res.forms['authzgroup_form'] - check_and_set_checkbox(form, u'madeup-authzgroup', u'editor', True, False) - check_and_set_checkbox(form, u'madeup-authzgroup', u'admin', False, False) - res = form.submit('authz_save', extra_environ={'REMOTE_USER': user}) - - #check database is back to normal - self.assert_package_roles_to_be([ - ('madeup-administrator', 'admin'), - ('visitor', 'reader'), - ('logged_in', 'reader')]) - - # and that page contains only the expected strings - assert 'visitor' in res - assert 'madeup-administrator' in res - assert 'logged_in' in res - assert 'madeup-authzgroup' not in res diff --git a/ckan/tests/logic/test_action.py b/ckan/tests/logic/test_action.py index b7735d2bd4e..4933f147046 100644 --- a/ckan/tests/logic/test_action.py +++ b/ckan/tests/logic/test_action.py @@ -866,23 +866,6 @@ def test_34_roles_show_for_user(self): assert set(roles[0].keys()) > set(('user_id', 'package_id', 'role', 'context', 'user_object_role_id')) - def test_34_roles_show_for_authgroup_on_authgroup(self): - anna = model.Package.by_name(u'annakarenina') - annafan = model.User.by_name(u'annafan') - authgroup = model.AuthorizationGroup.by_name(u'anauthzgroup') - authgroup2 = model.AuthorizationGroup.by_name(u'anotherauthzgroup') - - model.add_authorization_group_to_role(authgroup2, 'editor', authgroup) - model.repo.commit_and_remove() - - postparams = '%s=1' % json.dumps({'domain_object': authgroup.id, - 'authorization_group': authgroup2.id}) - res = self.app.post('/api/action/roles_show', params=postparams, - extra_environ={'Authorization': str(annafan.apikey)}, - status=200) - - authgroup_roles = TestRoles.get_roles(authgroup.id, authgroup_ref=authgroup2.name) - assert_equal(authgroup_roles, ['"anotherauthzgroup" is "editor" on "anauthzgroup"']) def test_35_user_role_update(self): anna = model.Package.by_name(u'annakarenina') @@ -912,40 +895,6 @@ def test_35_user_role_update(self): 'user': 'tester'}) assert_equal(results['roles'], roles_after['roles']) - def test_36_user_role_update_for_auth_group(self): - anna = model.Package.by_name(u'annakarenina') - annafan = model.User.by_name(u'annafan') - authgroup = model.AuthorizationGroup.by_name(u'anauthzgroup') - all_roles_before = TestRoles.get_roles(anna.id) - authgroup_roles_before = TestRoles.get_roles(anna.id, authgroup_ref=authgroup.name) - assert_equal(len(authgroup_roles_before), 0) - postparams = '%s=1' % json.dumps({'authorization_group': authgroup.name, - 'domain_object': anna.id, - 'roles': ['editor']}) - - res = self.app.post('/api/action/user_role_update', params=postparams, - extra_environ={'Authorization': str(annafan.apikey)}, - status=200) - - results = json.loads(res.body)['result'] - assert_equal(len(results['roles']), 1) - anna = model.Package.by_name(u'annakarenina') - authgroup = model.AuthorizationGroup.by_name(u'anauthzgroup') - - assert_equal(results['roles'][0]['role'], 'editor') - assert_equal(results['roles'][0]['package_id'], anna.id) - assert_equal(results['roles'][0]['authorized_group_id'], authgroup.id) - - all_roles_after = TestRoles.get_roles(anna.id) - authgroup_roles_after = TestRoles.get_roles(anna.id, authgroup_ref=authgroup.name) - assert_equal(set(all_roles_before) ^ set(all_roles_after), - set([u'"anauthzgroup" is "editor" on "annakarenina"'])) - - roles_after = get_action('roles_show') \ - ({'model': model, 'session': model.Session}, \ - {'domain_object': anna.id, - 'authorization_group': authgroup.name}) - assert_equal(results['roles'], roles_after['roles']) def test_37_user_role_update_disallowed(self): anna = model.Package.by_name(u'annakarenina') diff --git a/ckan/tests/models/test_authz.py b/ckan/tests/models/test_authz.py index 48cb8ace6cd..9c6e0423079 100644 --- a/ckan/tests/models/test_authz.py +++ b/ckan/tests/models/test_authz.py @@ -36,7 +36,7 @@ def test_0_package_role(self): user=mradmin ) model.Session.add(pr) - test0 = model.Package.by_name(u'test0') + test0 = model.Package.by_name(u'test0') prs = model.Session.query(model.PackageRole).filter_by( role=model.Role.ADMIN, package=test0, user=mradmin) @@ -105,7 +105,7 @@ def test_3_group_role(self): pr = model.Session.query(model.GroupRole).filter_by(role=model.Role.ADMIN, group=war) - + assert len(pr.all()) == 1, pr.all() @@ -121,12 +121,12 @@ def teardown_class(self): model.Session.remove() model.repo.rebuild_db() model.Session.remove() - + def is_allowed(self, role, action): action_query = model.Session.query(model.RoleAction).filter_by(role=role, action=action) return action_query.count() > 0 - + def test_read(self): assert self.is_allowed(model.Role.READER, model.Action.READ) assert self.is_allowed(model.Role.ANON_EDITOR, model.Action.READ) @@ -216,8 +216,7 @@ def setup_class(self): mreditor = model.User(name=u'mreditor') mrreader = model.User(name=u'mrreader') tester = model.User(name=u'tester') - anauthzgroup = model.AuthorizationGroup(name=u'anauthzgroup') - for obj in [anna, war, mradmin, mreditor, mrreader, tester, anauthzgroup]: + for obj in [anna, war, mradmin, mreditor, mrreader, tester]: model.Session.add(obj) model.repo.commit_and_remove() @@ -276,7 +275,7 @@ def test_2_is_auth_admin(self): assert len(ra.all()) == 1, ra.all() assert self.authorizer.get_roles(self.mradmin.name, self.anna) - + assert self.authorizer.is_authorized(username=self.mradmin.name, action=model.Action.EDIT, domain_object=self.anna) @@ -304,7 +303,7 @@ def tester_roles(): return [x.role \ for x in model.Session.query(model.PackageRole).all() \ if x.user and x.user.name=='tester' and x.package.name==u'warandpeace'] - + assert len(tester_roles()) == 0, "wrong number of roles for tester" model.add_user_to_role(tester, model.Role.ADMIN, war) model.repo.commit_and_remove() @@ -318,29 +317,6 @@ def tester_roles(): model.remove_user_from_role(tester, model.Role.ADMIN, war) assert len(tester_roles()) == 0, "wrong number of roles for tester" - def test_4_add_twice_remove_twice_for_authzgroups(self): - aag = model.AuthorizationGroup.by_name(u'anauthzgroup') - war = model.Package.by_name(u'warandpeace') - - def aag_roles(): - return [x.role \ - for x in model.Session.query(model.PackageRole).all() \ - if x.authorized_group and x.authorized_group.name=='anauthzgroup' and x.package.name==u'warandpeace'] - - assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup" - model.add_authorization_group_to_role(aag, model.Role.ADMIN, war) - model.repo.commit_and_remove() - assert len(aag_roles()) == 1, "wrong number of roles for anauthzgroup" - model.add_authorization_group_to_role(aag, model.Role.ADMIN, war) - model.repo.commit_and_remove() - - assert len(aag_roles()) == 1, "wrong number of roles for anauthzgroup" - model.remove_authorization_group_from_role(aag, model.Role.ADMIN, war) - assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup" - model.remove_authorization_group_from_role(aag, model.Role.ADMIN, war) - assert len(aag_roles()) == 0, "wrong number of roles for anauthzgroup" - - class TestMigrate: @@ -369,13 +345,13 @@ def test_give_default_permissions(self): # make changes anna = model.Package.by_name(u'annakarenina') - rev = model.repo.new_revision() + rev = model.repo.new_revision() rev.author = u'warauthor1' anna.title = u'title1' model.repo.commit_and_remove() anna = model.Package.by_name(u'annakarenina') - rev = model.repo.new_revision() + rev = model.repo.new_revision() rev.author = u'warauthor2' anna.title = u'title2' model.repo.commit_and_remove() @@ -409,7 +385,7 @@ def setup_class(self): john = model.User(name=u'john') model.Session.add(john) - + # setup annakarenina with default roles anna = model.Package.by_name(u'annakarenina') model.clear_user_roles(anna) @@ -552,5 +528,5 @@ def test_15_user_reads_vrestricted_package(self): action=model.Action.READ, domain_object=self.vrestricted), self.authorizer.get_domain_object_roles_printable(self.vrestricted) - + diff --git a/ckan/tests/models/test_repo.py b/ckan/tests/models/test_repo.py index fa740c5f15e..bec6f808d6a 100644 --- a/ckan/tests/models/test_repo.py +++ b/ckan/tests/models/test_repo.py @@ -9,19 +9,18 @@ '', '', '', - '', '', '', '', '', - '', + '', '', '', '', '', '', '', - '', + '', '', '', '', @@ -75,7 +74,7 @@ def teardown_class(cls): model.repo.rebuild_db() class DbFromMigrationTestCase(object): - + @classmethod def setup_class(cls): if not is_migration_supported(): @@ -103,7 +102,7 @@ def setup_class(cls): raise SkipTest('Search not supported') # delete all objects manually - rev = model.repo.new_revision() + rev = model.repo.new_revision() users = model.Session.query(model.User).all() uors = model.Session.query(model.UserObjectRole).all() ras = model.Session.query(model.RoleAction).all() @@ -114,14 +113,14 @@ def setup_class(cls): # db will already be on the latest version so # this should only reinstate the constant objects model.repo.init_const_data() - + @classmethod def teardown_class(cls): model.repo.rebuild_db() def test_user_consts(self): users = model.Session.query(model.User).all() - users_names = [user.name for user in users] + users_names = [user.name for user in users] user_differences = set(users_names) ^ set(const_user_names) assert not user_differences, 'Expected %r but got %r' % \ (const_user_names, users_names) diff --git a/ckan/tests/test_authz.py b/ckan/tests/test_authz.py index 02f819286b9..1a21451fbbb 100644 --- a/ckan/tests/test_authz.py +++ b/ckan/tests/test_authz.py @@ -55,7 +55,7 @@ def setup_class(self): model.Session.add(model.User(name=u'testadmin')) # Cannot setup testsysadmin user as it is alreade done in # the default test data. - #model.Session.add(model.User(name=u'testsysadmin')) + #model.Session.add(model.User(name=u'testsysadmin')) model.Session.add(model.User(name=u'notadmin')) model.Session.add(model.Group(name=u'testgroup')) model.Session.add(model.Group(name=u'testgroup2')) @@ -156,7 +156,7 @@ def test_revision_purge(self): def test_authorized_query(self): assert self.authorizer.is_authorized(self.notadmin.name, model.Action.READ, self.pkg) assert not self.authorizer.is_authorized(self.notadmin.name, model.Action.READ, self.private_pkg) - + q = self.authorizer.authorized_query(self.notadmin.name, model.Package) pkgs = set([pkg.name for pkg in q.all()]) expected_pkgs = set([u'testpkg', u'testpkg2', u'annakarenina', u'warandpeace']) @@ -196,7 +196,7 @@ def setup_class(self): for role in q: model.Session.delete(role) model.repo.commit_and_remove() - model.repo.new_revision() + model.repo.new_revision() model.Session.add(model.Package(name=u'testpkg')) model.Session.add(model.Package(name=u'testpkg2')) model.Session.add(model.User(name=u'testadmin')) @@ -240,12 +240,12 @@ def test_pkg_create(self): assert self.authorizer.is_authorized(self.notadmin.name, action, model.System()) assert not self.authorizer.is_authorized(u'blah', action, model.System()) assert not self.authorizer.is_authorized(u'visitor', action, model.System()) - + def test_pkg_edit(self): - #reproduce a bug + #reproduce a bug action = model.Action.EDIT assert self.authorizer.is_authorized(self.notadmin.name, action, model.System()) - + def test_pkg_admin(self): action = model.Action.PURGE assert self.authorizer.is_authorized(self.admin.name, action, self.pkg) @@ -258,110 +258,3 @@ def test_grp_sys_admin(self): assert self.authorizer.is_authorized(self.sysadmin.name, action, self.grp2) assert not self.authorizer.is_authorized(u'blah', action, self.grp) - -class TestAuthorizationGroups(object): - - @classmethod - def setup_class(self): - CreateTestData.create() - model.repo.new_revision() - model.Session.add(model.Package(name=u'testpkgag')) - model.Session.add(model.Group(name=u'testgroupag')) - model.Session.add(model.User(name=u'ag_member')) - model.Session.add(model.User(name=u'ag_admin')) - model.Session.add(model.User(name=u'ag_notmember')) - model.Session.add(model.AuthorizationGroup(name=u'authz_group')) - model.repo.commit_and_remove() - - pkg = model.Package.by_name(u'testpkgag') - grp = model.Group.by_name(u'testgroupag') - authzgrp = model.AuthorizationGroup.by_name(u'authz_group') - member = model.User.by_name(u'ag_member') - admin = model.User.by_name(u'ag_admin') - - model.setup_default_user_roles(authzgrp, [admin]) - model.add_authorization_group_to_role(authzgrp, model.Role.ADMIN, pkg) - model.add_authorization_group_to_role(authzgrp, model.Role.ADMIN, grp) - model.add_user_to_authorization_group(member, authzgrp, model.Role.EDITOR) - model.repo.commit_and_remove() - - self.authorizer = ckan.authz.Authorizer() - self.pkg = model.Package.by_name(u'testpkgag') - self.grp = model.Group.by_name(u'testgroupag') - self.member = model.User.by_name(u'ag_member') - self.admin = model.User.by_name(u'ag_admin') - self.notmember = model.User.by_name(u'ag_notmember') - self.authzgrp = model.AuthorizationGroup.by_name(u'authz_group') - - @classmethod - def teardown_class(self): - model.Session.remove() - model.repo.rebuild_db() - model.Session.remove() - - authorizer = ckan.authz.Authorizer() - - def test_get_authorization_groups(self): - assert self.authzgrp.id == self.authorizer.get_authorization_groups(self.member.name)[0].id - assert not self.authorizer.get_authorization_groups(self.notmember.name) - - @uses_example_auth_plugin - def test_get_groups_with_plugin(self): - groups = self.authorizer.get_authorization_groups(self.member.name) - assert len(groups) == 2, len(groups) - - def test_edit_via_grp(self): - action = model.Action.EDIT - assert not self.authorizer.is_authorized(self.notmember.name, action, self.pkg) - assert not self.authorizer.is_authorized(self.notmember.name, action, self.grp) - assert self.authorizer.is_authorized(self.member.name, action, self.pkg) - assert self.authorizer.is_authorized(self.member.name, action, self.grp) - - def test_add_to_authzgrp(self): - model.Session.add(model.User(name=u'ag_joiner')) - model.repo.new_revision() - model.repo.commit_and_remove() - user = model.User.by_name(u'ag_joiner') - assert not model.user_in_authorization_group(user, self.authzgrp), user - model.add_user_to_authorization_group(user, self.authzgrp, model.Role.ADMIN) - model.repo.new_revision() - model.repo.commit_and_remove() - assert model.user_in_authorization_group(user, self.authzgrp) - - def test_remove_from_authzgrp(self): - model.Session.add(model.User(name=u'ag_leaver')) - model.repo.new_revision() - model.repo.commit_and_remove() - user = model.User.by_name(u'ag_leaver') - model.add_user_to_authorization_group(user, self.authzgrp, model.Role.ADMIN) - model.repo.new_revision() - model.repo.commit_and_remove() - assert model.user_in_authorization_group(user, self.authzgrp) - model.remove_user_from_authorization_group(user, self.authzgrp) - model.repo.new_revision() - model.repo.commit_and_remove() - assert not model.user_in_authorization_group(user, self.authzgrp) - - def test_authzgrp_edit_rights(self): - assert self.authorizer.is_authorized(self.member.name, model.Action.READ, self.authzgrp) - assert self.authorizer.is_authorized(self.notmember.name, model.Action.READ, self.authzgrp) - assert self.authorizer.is_authorized(self.member.name, model.Action.EDIT, self.authzgrp) - assert not self.authorizer.is_authorized(self.member.name, model.Action.PURGE, self.authzgrp) - assert self.authorizer.is_authorized(self.admin.name, model.Action.PURGE, self.authzgrp) - assert not self.authorizer.is_authorized(self.notmember.name, model.Action.EDIT, self.authzgrp) - - def test_authorized_query(self): - assert not self.authorizer.is_authorized(self.notmember.name, model.Action.READ, self.pkg) - assert self.authorizer.is_authorized(self.member.name, model.Action.READ, self.pkg) - - q = self.authorizer.authorized_query(self.notmember.name, model.Package) - q = q.filter(model.Package.name==self.pkg.name) - assert not len(q.all()) - - q = self.authorizer.authorized_query(self.member.name, model.Package) - q = q.filter(model.Package.name==self.pkg.name) - assert len(q.all()) == 1 - - @uses_example_auth_plugin - def test_authorized_query_with_plugin(self): - assert self.authorizer.is_authorized(self.notmember.name, model.Action.READ, self.pkg)