def test_works_with_auth(self): session = DBSession() root = get_root() child = root[u'child'] = Node() session.flush() request = DummyRequest() auth = CallbackAuthenticationPolicy() auth.unauthenticated_userid = lambda *args: 'bob' auth.callback = list_groups_callback request.context = root self.assertEqual( # user doesn't exist yet auth.effective_principals(request), ['system.Everyone'] ) get_principals()[u'bob'] = dict(name=u'bob') self.assertEqual( auth.effective_principals(request), ['system.Everyone', 'system.Authenticated', 'bob'] ) # Define that bob belongs to bobsgroup on the root level: set_groups('bob', root, ['group:bobsgroup']) request.context = child self.assertEqual( set(auth.effective_principals(request)), set([ 'system.Everyone', 'system.Authenticated', 'bob', 'group:bobsgroup' ]) ) # define that bob belongs to franksgroup in the user db: get_principals()[u'bob'].groups = [u'group:franksgroup'] set_groups('group:franksgroup', child, ['group:anothergroup']) self.assertEqual( set(auth.effective_principals(request)), set([ 'system.Everyone', 'system.Authenticated', 'bob', 'group:bobsgroup', 'group:franksgroup', 'group:anothergroup', ]) ) # And lastly test that circular group defintions are not a # problem here either: get_principals()[u'group:franksgroup'] = dict( name=u'group:franksgroup', title=u"Frank's group", groups=[u'group:funnygroup', u'group:bobsgroup'], ) self.assertEqual( set(auth.effective_principals(request)), set([ 'system.Everyone', 'system.Authenticated', 'bob', 'group:bobsgroup', 'group:franksgroup', 'group:anothergroup', 'group:funnygroup', ]) )
def test_works_with_auth(self, db_session, root): from kotti.resources import Node from kotti.security import get_principals from kotti.security import list_groups_callback from kotti.security import set_groups child = root[u'child'] = Node() db_session.flush() request = DummyRequest() auth = CallbackAuthenticationPolicy() auth.unauthenticated_userid = lambda *args: 'bob' auth.callback = list_groups_callback request.context = root assert ( # user doesn't exist yet auth.effective_principals(request) == ['system.Everyone']) get_principals()[u'bob'] = dict(name=u'bob') assert (auth.effective_principals(request) == [ 'system.Everyone', 'system.Authenticated', 'bob' ]) # Define that bob belongs to bobsgroup on the root level: set_groups('bob', root, ['group:bobsgroup']) request.context = child assert (set(auth.effective_principals(request)) == set([ 'system.Everyone', 'system.Authenticated', 'bob', 'group:bobsgroup' ])) # define that bob belongs to franksgroup in the user db: get_principals()[u'bob'].groups = [u'group:franksgroup'] set_groups('group:franksgroup', child, ['group:anothergroup']) assert (set(auth.effective_principals(request)) == set([ 'system.Everyone', 'system.Authenticated', 'bob', 'group:bobsgroup', 'group:franksgroup', 'group:anothergroup', ])) # And lastly test that circular group defintions are not a # problem here either: get_principals()[u'group:franksgroup'] = dict( name=u'group:franksgroup', title=u"Frank's group", groups=[u'group:funnygroup', u'group:bobsgroup'], ) assert (set(auth.effective_principals(request)) == set([ 'system.Everyone', 'system.Authenticated', 'bob', 'group:bobsgroup', 'group:franksgroup', 'group:anothergroup', 'group:funnygroup', ]))
def add_user_success(self, appstruct): appstruct.pop('csrf_token', None) name = appstruct['name'] = appstruct['name'].lower() appstruct['email'] = appstruct['email'] and appstruct['email'].lower() get_principals()[name] = appstruct email_set_password(get_principals()[name], self.request) self.request.session.flash( _(u'The registration mail sent to ${email}.', mapping=dict(email=appstruct['email'])), 'success') return HTTPFound(location='/')
def add_user(context, request, appstruct): _massage_groups_in(appstruct) name = appstruct['name'].lower() send_email = appstruct.pop('send_email', False) get_principals()[name] = appstruct if send_email: send_set_password(get_principals()[name], request) request.session.flash(u'%s added.' % appstruct['title'], 'success') location = request.url.split('?')[0] + '?' + urlencode({'extra': name}) return HTTPFound(location=location)
def test_list_groups_callback_with_groups(self): # Although group definitions are also in the user database, # we're not allowed to authenticate with a group id: get_principals()[u'bob'] = dict(name=u'bob') get_principals()[u'group:bobsgroup'] = dict(name=u'group:bobsgroup') request = DummyRequest() self.assertEqual(list_groups_callback(u'bob', request), []) self.assertEqual( list_groups_callback(u'group:bobsgroup', request), None)
def add_user(context, request, appstruct): _massage_groups_in(appstruct) name = appstruct["name"].lower() send_email = appstruct.pop("send_email", False) get_principals()[name] = appstruct if send_email: send_set_password(get_principals()[name], request) request.session.flash(u"%s added." % appstruct["title"], "success") location = request.url.split("?")[0] + "?" + urlencode({"extra": name}) return HTTPFound(location=location)
def test_list_groups_callback_with_groups(self, db_session): from kotti.security import list_groups_callback from kotti.security import get_principals # Although group definitions are also in the user database, # we're not allowed to authenticate with a group id: get_principals()[u'bob'] = dict(name=u'bob') get_principals()[u'group:bobsgroup'] = dict(name=u'group:bobsgroup') request = DummyRequest() assert list_groups_callback(u'bob', request) == [] assert list_groups_callback(u'group:bobsgroup', request) is None
def test_list_groups_callback_with_groups(self, db_session): from kotti.security import list_groups_callback from kotti.security import get_principals # Although group definitions are also in the user database, # we're not allowed to authenticate with a group id: get_principals()["bob"] = dict(name="bob") get_principals()["group:bobsgroup"] = dict(name="group:bobsgroup") request = DummyRequest() assert list_groups_callback("bob", request) == [] assert list_groups_callback("group:bobsgroup", request) is None
def test_list_groups_callback_with_groups(self): from kotti.security import list_groups_callback from kotti.security import get_principals # Although group definitions are also in the user database, # we're not allowed to authenticate with a group id: get_principals()[u'bob'] = dict(name=u'bob') get_principals()[u'group:bobsgroup'] = dict(name=u'group:bobsgroup') request = DummyRequest() self.assertEqual(list_groups_callback(u'bob', request), []) self.assertEqual(list_groups_callback(u'group:bobsgroup', request), None)
def add_user_success(self, appstruct): appstruct.pop('csrf_token', None) _massage_groups_in(appstruct) name = appstruct['name'] = appstruct['name'].lower() appstruct['email'] = appstruct['email'] and appstruct['email'].lower() send_email = appstruct.pop('send_email', False) get_principals()[name] = appstruct if send_email: email_set_password(get_principals()[name], self.request) self.request.session.flash(_(u'${title} added.', mapping=dict(title=appstruct['title'])), 'success') location = self.request.url.split('?')[0] + '?' + urlencode( {'extra': name}) return HTTPFound(location=location)
def add_user_success(self, appstruct): appstruct.pop("csrf_token", None) _massage_groups_in(appstruct) name = appstruct["name"] = appstruct["name"].lower() appstruct["email"] = appstruct["email"] and appstruct["email"].lower() send_email = appstruct.pop("send_email", False) get_principals()[name] = appstruct if send_email: email_set_password(get_principals()[name], self.request) self.request.session.flash( _("${title} was added.", mapping=dict(title=appstruct["title"])), "success" ) location = self.request.url.split("?")[0] + "?" + urlencode({"extra": name}) return HTTPFound(location=location)
def add_user_success(self, appstruct): appstruct.pop('csrf_token', None) _massage_groups_in(appstruct) name = appstruct['name'].lower() send_email = appstruct.pop('send_email', False) get_principals()[name] = appstruct if send_email: send_set_password(get_principals()[name], self.request) self.request.session.flash(_(u'${title} added.', mapping=dict(title=appstruct['title'])), 'success') location = self.request.url.split('?')[0] + '?' + urlencode( {'extra': name}) return HTTPFound(location=location)
def add_user_success(self, appstruct): appstruct.pop("csrf_token", None) _massage_groups_in(appstruct) name = appstruct["name"] = appstruct["name"].lower() appstruct["email"] = appstruct["email"] and appstruct["email"].lower() send_email = appstruct.pop("send_email", False) get_principals()[name] = appstruct if send_email: email_set_password(get_principals()[name], self.request) self.request.session.flash( _("${title} was added.", mapping=dict(title=appstruct["title"])), "success") location = self.request.url.split("?")[0] + "?" + urlencode( {"extra": name}) return HTTPFound(location=location)
def test_deleted_group_removed_in_usergroups(self, events, extra_principals, root): from kotti.security import get_principals from kotti.views.users import user_delete request = DummyRequest() bob = get_principals()[u'bob'] bob.groups = [u'group:bobsgroup'] assert bob.groups == [u'group:bobsgroup'] request.params['name'] = u'group:bobsgroup' request.params['delete'] = u'delete' user_delete(root, request) with pytest.raises(KeyError): get_principals()[u'group:bobsgroup'] assert bob.groups == []
def test_search(self): from kotti.resources import get_root from kotti.security import get_principals from kotti.tests.test_node_views import TestNodeShare from kotti.views.users import users_manage root = get_root() request = DummyRequest() P = get_principals() TestNodeShare.add_some_principals() request.params['search'] = u'' request.params['query'] = u'Joe' entries = users_manage(root, request)['entries'] self.assertEqual(len(entries), 0) self.assertEqual(request.session.pop_flash('info'), [u'No users or groups found.']) request.params['query'] = u'Bob' entries = users_manage(root, request)['entries'] self.assertEqual(entries[0][0], P['bob']) self.assertEqual(entries[0][1], ([], [])) self.assertEqual(entries[1][0], P['group:bobsgroup']) self.assertEqual(entries[1][1], ([], [])) P[u'bob'].groups = [u'group:bobsgroup'] P[u'group:bobsgroup'].groups = [u'role:admin'] entries = users_manage(root, request)['entries'] self.assertEqual(entries[0][1], (['group:bobsgroup', 'role:admin'], ['role:admin'])) self.assertEqual(entries[1][1], (['role:admin'], []))
def search_principals(request, context=None, ignore=None, extra=()): flash = request.session.flash principals = get_principals() if ignore is None: ignore = set() entries = [] for principal_name in extra: if principal_name not in ignore: p = principals[principal_name] entries.append((p, list_groups_ext(principal_name, context))) ignore.add(principal_name) if "search" in request.POST: query = "*%s*" % request.params["query"] found = False for p in principals.search(name=query, title=query, email=query): found = True if p.name not in ignore: entries.append((p, list_groups_ext(p.name, context))) if not found: flash(u"No users or groups found.", "notice") return entries
def search_principals(request, context=None, ignore=None, extra=()): flash = request.session.flash principals = get_principals() if ignore is None: ignore = set() entries = [] for principal_name in extra: if principal_name not in ignore: p = principals[principal_name] entries.append((p, list_groups_ext(principal_name, context))) ignore.add(principal_name) postdata = request.POST if request.method == 'POST' and request.is_xhr: postdata = request.json if 'search' in postdata: if request.is_xhr: query = '*{0}*'.format(postdata['query']) else: query = '*{0}*'.format(request.params['query']) found = False for p in principals.search(name=query, title=query, email=query): found = True if p.name not in ignore: entries.append((p, list_groups_ext(p.name, context))) if not found: flash(_('No users or groups were found.'), 'info') return entries
def user_delete(context, request): principals = get_principals() if 'name' in request.params and request.params['name']: user_or_group = request.params['name'] principal = principals.search(name=user_or_group).first() if principal is None: request.session.flash(_('User was not found.'), 'error') else: is_group = user_or_group.startswith("group:") principal_type = _("Group") if is_group else _("User") # We already coming from the confirmation page. if 'delete' in request.POST: principals.__delitem__(principal.name) notify(UserDeleted(principal, request)) request.session.flash( _('${principal_type} ${title} was deleted.', mapping=dict(principal_type=principal_type, title=principal.title)), 'info') location = '{0}/@@setup-users'.format(request.application_url) return HTTPFound(location=location) api = template_api( context, request, page_title=_("Delete ${principal_type} ${title}", mapping=dict(principal_type=principal_type, title=principal.title)), principal_type=principal_type, principal=principal) return {'api': api, } else: request.session.flash(_('No name was given.'), 'error') return {'api': template_api(context, request), }
def __init__(self, name, password=None, confirm_token=None, title=u"", email=None, groups=(), city_name='', real_name='', birth_date=None, school=u"", school_year=0, company=u"", industry=u"", special_skill=u"", interest=u"", between=u"", introduction=u"", **kwargs): self.name = name if password is not None: password = get_principals().hash_password(password) self.password = password self.confirm_token = confirm_token self.title = title self.email = email self.groups = groups self.creation_date = datetime.now(tz=None) self.last_login_date = None if city_name: self.city_name = city_name else: # default city_name self.city_name = u'深圳' self.real_name = real_name self.birth_date = birth_date self.school = school self.school_year = school_year self.company = company self.industry = industry self.special_skill = special_skill self.between = between self.introduction = introduction super(MbaUser, self).__init__(**kwargs)
def _find_user(login): print login principals = get_principals() if phone_reg.match(login): print 'match' for p in principals.search(phone=login): return p else: principal = principals.get(login) if principal is not None: return principal else: try: Email().to_python(login) except Exception: pass else: for p in principals.search(email=login): return p
def set_password(context, request, success_msg=_(u"You've reset your password successfully.")): form = Form(SetPasswordSchema(), buttons=(Button('submit', _(u'Submit')), )) rendered_form = None if 'submit' in request.POST: try: appstruct = form.validate(request.POST.items()) except ValidationFailure, e: request.session.flash(_(u"There was an error."), 'error') rendered_form = e.render() else: token = appstruct['token'] email = appstruct['email'] user = _find_user(email) if (user is not None and validate_token(user, token) and token == user.confirm_token): password = appstruct['password'] user.password = get_principals().hash_password(password) user.confirm_token = None headers = remember(request, user.name) location = (appstruct['continue_to'] or resource_url(context, request)) request.session.flash(success_msg, 'success') return HTTPFound(location=location, headers=headers) else: request.session.flash( _(u"Your password reset token may have expired."), 'error')
def get_recepients(context, permission="state_change"): """ Get a list of principals that have the permission in context and a email. :param context: Object for that the permission is needed. :type context: :class:`kotti.resources.Node` :param permission: :type permission: str :result: List of principals. :rtype: set """ principal_db = get_principals() recepients = [] for p in principals_allowed_by_permission(context, permission): # set(['role:owner', 'role:editor']) for principal in principal_db.search(groups=u'*%s*' % p).all(): recepients.append(principal) for principal in map_principals_with_local_roles(context): # [ # ( # <Principal u'disko'>, # ( # [u'role:owner', u'group:admins', u'role:admin'], # [u'role:owner', u'group:admins', u'role:admin']))] if p in principal[1][0] or p in principal[1][1]: recepients.append(principal[0]) return set([r for r in recepients if r.email])
def test_apply(self): from kotti.resources import get_root from kotti.security import get_principals from kotti.security import list_groups from kotti.tests.test_node_views import TestNodeShare from kotti.views.users import users_manage root = get_root() request = DummyRequest() TestNodeShare.add_some_principals() bob = get_principals()[u'bob'] request.params['apply'] = u'' users_manage(root, request) self.assertEqual(request.session.pop_flash('info'), [u'No changes made.']) self.assertEqual(list_groups('bob'), []) bob.groups = [u'role:special'] request.params['role::bob::role:owner'] = u'1' request.params['role::bob::role:editor'] = u'1' request.params['orig-role::bob::role:owner'] = u'' request.params['orig-role::bob::role:editor'] = u'' users_manage(root, request) self.assertEqual(request.session.pop_flash('success'), [u'Your changes have been saved.']) self.assertEqual(set(list_groups('bob')), set(['role:owner', 'role:editor', 'role:special']))
def test_apply(self, extra_principals): from kotti.resources import get_root from kotti.security import get_principals from kotti.security import list_groups from kotti.views.users import users_manage root = get_root() request = DummyRequest() bob = get_principals()[u'bob'] request.params['apply'] = u'' users_manage(root, request) assert (request.session.pop_flash('info') == [u'No changes made.']) assert list_groups('bob') == [] bob.groups = [u'role:special'] request.params['role::bob::role:owner'] = u'1' request.params['role::bob::role:editor'] = u'1' request.params['orig-role::bob::role:owner'] = u'' request.params['orig-role::bob::role:editor'] = u'' users_manage(root, request) assert (request.session.pop_flash('success') == [u'Your changes have been saved.']) assert ( set(list_groups('bob')) == set(['role:owner', 'role:editor', 'role:special']) )
def user_manage(context, request): username = request.params["name"] principal = get_principals()[username] api = template_api( context, request, page_title=u"Edit User - %s" % context.title, cp_links=CONTROL_PANEL_LINKS, principal=principal, ) def edit_principal(context, request, appstruct): _massage_groups_in(appstruct) for key, value in appstruct.items(): setattr(context, key, value) request.session.flash(u"Your changes have been saved.", "success") return HTTPFound(location=request.url) uschema = user_schema() del uschema["name"] del uschema["password"] user_form = Form(uschema, buttons=("save", "cancel")) user_fc = FormController( user_form, appstruct=lambda p: _massage_groups_out(p.__dict__.copy()), edit_item=edit_principal ) form = user_fc(principal, request) if request.is_response(form): return form return {"api": api, "form": form}
def login(context, request): principals = get_principals() came_from = request.params.get("came_from", request.resource_url(context)) login, password = u"", u"" if "submit" in request.POST: login = request.params["login"].lower() password = request.params["password"] user = _find_user(login) if user is not None and user.active and principals.validate_password(password, user.password): headers = remember(request, login) request.session.flash(_(u"Welcome, ${user}!", mapping=dict(user=user.title or user.name)), "success") user.last_login_date = datetime.now() return HTTPFound(location=came_from, headers=headers) request.session.flash(_(u"Login failed."), "error") if "reset-password" in request.POST: login = request.params["login"] user = _find_user(login) if user is not None: send_set_password(user, request, templates="reset-password") request.session.flash( _(u"You should receive an email with a link to reset your " u"password momentarily."), "success" ) else: request.session.flash(_(u"That username or email is not known to us."), "error") return {"url": request.application_url + "/@@login", "came_from": came_from, "login": login, "password": password}
def test_map_principals_with_local_roles(self): from kotti.resources import get_root from kotti.security import get_principals from kotti.security import map_principals_with_local_roles self.test_principals_with_local_roles() root = get_root() child = root[u'child'] P = get_principals() # No users are defined in P, thus we get the empty list: self.assertEqual(map_principals_with_local_roles(root), []) P['bob'] = {'name': u'bob'} P['group:bobsgroup'] = {'name': u'group:bobsgroup'} value = map_principals_with_local_roles(root) self.assertEqual(len(value), 1) bob, (bob_all, bob_inherited) = value[0] self.assertEqual(bob_all, ['group:bobsgroup']) self.assertEqual(bob_inherited, []) value = map_principals_with_local_roles(child) self.assertEqual(len(value), 2) bob, (bob_all, bob_inherited) = value[0] bobsgroup, (bobsgroup_all, bobsgroup_inherited) = value[1] self.assertEqual(set(bob_all), set(['group:bobsgroup', 'role:editor'])) self.assertEqual(set(bob_inherited), set(['group:bobsgroup', 'role:editor'])) self.assertEqual(bobsgroup_all, ['role:editor']) self.assertEqual(bobsgroup_inherited, [])
def test_search(self, extra_principals, root): from kotti.security import get_principals from kotti.views.users import UsersManage request = DummyRequest() P = get_principals() request.params['search'] = '' request.params['query'] = 'Joe' entries = UsersManage(root, request)()['entries'] assert len(entries) == 0 assert (request.session.pop_flash('info') == [ 'No users or groups were found.' ]) request.params['query'] = 'Bob' entries = UsersManage(root, request)()['entries'] assert entries[0][0] == P['bob'] assert entries[0][1] == ([], []) assert entries[1][0] == P['group:bobsgroup'] assert entries[1][1] == ([], []) P['bob'].groups = ['group:bobsgroup'] P['group:bobsgroup'].groups = ['role:admin'] entries = UsersManage(root, request)()['entries'] # assert entries[0][1] == (['group:bobsgroup', 'role:admin'], ['role:admin']) # noqa assert set(entries[0][1][0]) == {'group:bobsgroup', 'role:admin'} assert entries[0][1][1] == ['role:admin'] assert entries[1][1] == (['role:admin'], [])
def test_apply(self): from kotti.resources import get_root from kotti.security import get_principals from kotti.security import list_groups from kotti.tests.test_node_views import TestNodeShare from kotti.views.users import users_manage root = get_root() request = DummyRequest() TestNodeShare.add_some_principals() bob = get_principals()[u'bob'] request.params['apply'] = u'' users_manage(root, request) self.assertEqual(request.session.pop_flash('info'), [u'No changes made.']) self.assertEqual(list_groups('bob'), []) bob.groups = [u'role:special'] request.params['role::bob::role:owner'] = u'1' request.params['role::bob::role:editor'] = u'1' request.params['orig-role::bob::role:owner'] = u'' request.params['orig-role::bob::role:editor'] = u'' users_manage(root, request) self.assertEqual(request.session.pop_flash('success'), [u'Your changes have been saved.']) self.assertEqual( set(list_groups('bob')), set(['role:owner', 'role:editor', 'role:special']) )
def set_password(context, request, success_msg=u"You've reset your password successfully."): form = Form(SetPasswordSchema(), buttons=('submit',)) rendered_form = None if 'submit' in request.POST: try: appstruct = form.validate(request.POST.items()) except ValidationFailure, e: request.session.flash(u"There was an error.", 'error') rendered_form = e.render() else: token = appstruct['token'] email = appstruct['email'] user = _find_user(email) if (user is not None and validate_token(user, token) and token == user.confirm_token): password = appstruct['password'] user.password = get_principals().hash_password(password) user.confirm_token = None headers = remember(request, user.name) location = (appstruct['continue_to'] or resource_url(context, request)) request.session.flash(success_msg, 'success') return HTTPFound(location=location, headers=headers) else: request.session.flash( u"Your password reset token may have expired.", 'error')
def test_search(self, extra_principals, root): from kotti.security import get_principals from kotti.views.users import UsersManage request = DummyRequest() P = get_principals() request.params["search"] = "" request.params["query"] = "Joe" entries = UsersManage(root, request)()["entries"] assert len(entries) == 0 assert request.session.pop_flash("info") == ["No users or groups were found."] request.params["query"] = "Bob" entries = UsersManage(root, request)()["entries"] assert entries[0][0] == P["bob"] assert entries[0][1] == ([], []) assert entries[1][0] == P["group:bobsgroup"] assert entries[1][1] == ([], []) P["bob"].groups = ["group:bobsgroup"] P["group:bobsgroup"].groups = ["role:admin"] entries = UsersManage(root, request)()["entries"] # assert entries[0][1] == (['group:bobsgroup', 'role:admin'], ['role:admin']) # noqa assert set(entries[0][1][0]) == {"group:bobsgroup", "role:admin"} assert entries[0][1][1] == ["role:admin"] assert entries[1][1] == (["role:admin"], [])
def test_search(self, extra_principals): from kotti.resources import get_root from kotti.security import get_principals from kotti.views.users import users_manage root = get_root() request = DummyRequest() P = get_principals() request.params['search'] = u'' request.params['query'] = u'Joe' entries = users_manage(root, request)['entries'] assert len(entries) == 0 assert (request.session.pop_flash('info') == [u'No users or groups found.']) request.params['query'] = u'Bob' entries = users_manage(root, request)['entries'] assert entries[0][0] == P['bob'] assert entries[0][1] == ([], []) assert entries[1][0] == P['group:bobsgroup'] assert entries[1][1] == ([], []) P[u'bob'].groups = [u'group:bobsgroup'] P[u'group:bobsgroup'].groups = [u'role:admin'] entries = users_manage(root, request)['entries'] assert (entries[0][1] == (['group:bobsgroup', 'role:admin'], ['role:admin'])) assert entries[1][1] == (['role:admin'], [])
def test_search(self, extra_principals, root): from kotti.security import get_principals from kotti.views.users import UsersManage request = DummyRequest() P = get_principals() request.params["search"] = "" request.params["query"] = "Joe" entries = UsersManage(root, request)()["entries"] assert len(entries) == 0 assert request.session.pop_flash("info") == [ "No users or groups were found." ] request.params["query"] = "Bob" entries = UsersManage(root, request)()["entries"] assert entries[0][0] == P["bob"] assert entries[0][1] == ([], []) assert entries[1][0] == P["group:bobsgroup"] assert entries[1][1] == ([], []) P["bob"].groups = ["group:bobsgroup"] P["group:bobsgroup"].groups = ["role:admin"] entries = UsersManage(root, request)()["entries"] # assert entries[0][1] == (['group:bobsgroup', 'role:admin'], ['role:admin']) # noqa assert set(entries[0][1][0]) == {"group:bobsgroup", "role:admin"} assert entries[0][1][1] == ["role:admin"] assert entries[1][1] == (["role:admin"], [])
def test_map_principals_with_local_roles(self, db_session, root): from kotti.security import get_principals from kotti.security import map_principals_with_local_roles self.test_principals_with_local_roles(db_session, root) child = root[u'child'] P = get_principals() # No users are defined in P, thus we get the empty list: assert map_principals_with_local_roles(root) == [] P['bob'] = {'name': u'bob'} P['group:bobsgroup'] = {'name': u'group:bobsgroup'} value = map_principals_with_local_roles(root) assert len(value) == 1 bob, (bob_all, bob_inherited) = value[0] assert bob_all == ['group:bobsgroup'] assert bob_inherited == [] value = map_principals_with_local_roles(child) assert len(value) == 2 bob, (bob_all, bob_inherited) = value[0] bobsgroup, (bobsgroup_all, bobsgroup_inherited) = value[1] assert (set(bob_all) == {'group:bobsgroup', 'role:editor'}) assert (set(bob_inherited) == {'group:bobsgroup', 'role:editor'}) assert bobsgroup_all == ['role:editor'] assert bobsgroup_inherited == []
def test_apply(self, extra_principals, root): from kotti.security import get_principals from kotti.security import list_groups from kotti.views.users import UsersManage request = DummyRequest() bob = get_principals()["bob"] request.params["apply"] = "" UsersManage(root, request)() assert request.session.pop_flash("info") == ["No changes were made."] assert list_groups("bob") == [] bob.groups = ["role:special"] request.params["role::bob::role:owner"] = "1" request.params["role::bob::role:editor"] = "1" request.params["orig-role::bob::role:owner"] = "" request.params["orig-role::bob::role:editor"] = "" UsersManage(root, request)() assert request.session.pop_flash("success") == [ "Your changes have been saved." ] assert set(list_groups("bob")) == { "role:owner", "role:editor", "role:special" }
def test_map_principals_with_local_roles(self, db_session, root): from kotti.security import get_principals from kotti.security import map_principals_with_local_roles self.test_principals_with_local_roles(db_session, root) child = root["child"] P = get_principals() # No users are defined in P, thus we get the empty list: assert map_principals_with_local_roles(root) == [] P["bob"] = {"name": "bob"} P["group:bobsgroup"] = {"name": "group:bobsgroup"} value = map_principals_with_local_roles(root) assert len(value) == 1 bob, (bob_all, bob_inherited) = value[0] assert bob_all == ["group:bobsgroup"] assert bob_inherited == [] value = map_principals_with_local_roles(child) assert len(value) == 2 bob, (bob_all, bob_inherited) = value[0] bobsgroup, (bobsgroup_all, bobsgroup_inherited) = value[1] assert set(bob_all) == {"group:bobsgroup", "role:editor"} assert set(bob_inherited) == {"group:bobsgroup", "role:editor"} assert bobsgroup_all == ["role:editor"] assert bobsgroup_inherited == []
def search_principals(request, context=None, ignore=None, extra=()): flash = request.session.flash principals = get_principals() if ignore is None: ignore = set() entries = [] for principal_name in extra: if principal_name not in ignore: p = principals[principal_name] entries.append((p, list_groups_ext(principal_name, context))) ignore.add(principal_name) postdata = request.POST if request.method == "POST" and request.is_xhr: postdata = request.json if "search" in postdata: if request.is_xhr: query = "*{}*".format(postdata["query"]) else: query = "*{}*".format(request.params["query"]) found = False for p in principals.search(name=query, title=query, email=query): found = True if p.name not in ignore: entries.append((p, list_groups_ext(p.name, context))) if not found: flash(_("No users or groups were found."), "info") return entries
def user_delete(context, request): principals = get_principals() if 'name' in request.params and request.params['name']: user_or_group = request.params['name'] principal = principals.search(name=user_or_group).first() if principal is None: request.session.flash(_(u'User was not found.'), 'error') else: is_group = user_or_group.startswith("group:") principal_type = _(u"Group") if is_group else _(u"User") # We already coming from the confirmation page. if 'delete' in request.POST: principals.__delitem__(principal.name) notify(UserDeleted(principal, request)) request.session.flash( _(u'${principal_type} ${title} was deleted.', mapping=dict(principal_type=principal_type, title=principal.title)), 'info') location = "%s/@@setup-users" % request.application_url return HTTPFound(location=location) api = template_api( context, request, page_title=_(u"Delete ${principal_type} ${title}", mapping=dict(principal_type=principal_type, title=principal.title)), principal_type=principal_type, principal=principal) return {'api': api, } else: request.session.flash(_(u'No name was given.'), 'error') return {'api': template_api(context, request), }
def __call__(self): user_or_group = self.request.params["name"] principal = get_principals()[user_or_group] is_group = user_or_group.startswith("group:") principal_type = _("Group") if is_group else _("User") api = template_api( self.context, self.request, page_title=_( "Edit ${principal_type} ${title}", mapping=dict(principal_type=principal_type, title=self.context.title), ), cp_links=CONTROL_PANEL_LINKS, principal=principal, ) form_view = self.GroupManageFormView if is_group else self.UserManageFormView form = form_view(principal, self.request)() if self.request.is_response(form): return form return {"api": api, "form": form["form"]}
def test_map_principals_with_local_roles(self, db_session, root): from kotti.security import get_principals from kotti.security import map_principals_with_local_roles self.test_principals_with_local_roles(db_session, root) child = root[u'child'] P = get_principals() # No users are defined in P, thus we get the empty list: assert map_principals_with_local_roles(root) == [] P['bob'] = {'name': u'bob'} P['group:bobsgroup'] = {'name': u'group:bobsgroup'} value = map_principals_with_local_roles(root) assert len(value) == 1 bob, (bob_all, bob_inherited) = value[0] assert bob_all == ['group:bobsgroup'] assert bob_inherited == [] value = map_principals_with_local_roles(child) assert len(value) == 2 bob, (bob_all, bob_inherited) = value[0] bobsgroup, (bobsgroup_all, bobsgroup_inherited) = value[1] assert (set(bob_all) == set(['group:bobsgroup', 'role:editor'])) assert (set(bob_inherited) == set(['group:bobsgroup', 'role:editor'])) assert bobsgroup_all == ['role:editor'] assert bobsgroup_inherited == []
def test_apply(self, extra_principals, root): from kotti.security import get_principals from kotti.security import list_groups from kotti.views.users import UsersManage request = DummyRequest() bob = get_principals()[u'bob'] request.params['apply'] = u'' UsersManage(root, request)() assert (request.session.pop_flash('info') == [u'No changes were made.']) assert list_groups('bob') == [] bob.groups = [u'role:special'] request.params['role::bob::role:owner'] = u'1' request.params['role::bob::role:editor'] = u'1' request.params['orig-role::bob::role:owner'] = u'' request.params['orig-role::bob::role:editor'] = u'' UsersManage(root, request)() assert (request.session.pop_flash('success') == [u'Your changes have been saved.']) assert ( set(list_groups('bob')) == {'role:owner', 'role:editor', 'role:special'} )
def search_principals(request, context=None, ignore=None, extra=()): flash = request.session.flash principals = get_principals() if ignore is None: ignore = set() entries = [] for principal_name in extra: if principal_name not in ignore: p = principals[principal_name] entries.append((p, list_groups_ext(principal_name, context))) ignore.add(principal_name) if 'search' in request.POST: query = '*%s*' % request.params['query'] found = False for p in principals.search(name=query, title=query, email=query): found = True if p.name not in ignore: entries.append((p, list_groups_ext(p.name, context))) if not found: flash(_(u'No users or groups were found.'), 'info') return entries
def test_search(self, extra_principals, root): from kotti.security import get_principals from kotti.views.users import UsersManage request = DummyRequest() P = get_principals() request.params['search'] = u'' request.params['query'] = u'Joe' entries = UsersManage(root, request)()['entries'] assert len(entries) == 0 assert (request.session.pop_flash('info') == [u'No users or groups were found.']) request.params['query'] = u'Bob' entries = UsersManage(root, request)()['entries'] assert entries[0][0] == P['bob'] assert entries[0][1] == ([], []) assert entries[1][0] == P['group:bobsgroup'] assert entries[1][1] == ([], []) P[u'bob'].groups = [u'group:bobsgroup'] P[u'group:bobsgroup'].groups = [u'role:admin'] entries = UsersManage(root, request)()['entries'] assert (entries[0][1] == (['group:bobsgroup', 'role:admin'], ['role:admin'])) assert entries[1][1] == (['role:admin'], [])
def search_principals(request, context=None, ignore=None, extra=()): flash = request.session.flash principals = get_principals() if ignore is None: ignore = set() entries = [] for principal_name in extra: if principal_name not in ignore: p = principals[principal_name] entries.append((p, list_groups_ext(principal_name, context))) ignore.add(principal_name) if 'search' in request.POST: query = '*%s*' % request.params['query'] found = False for p in principals.search(name=query, title=query, email=query): found = True if p.name not in ignore: entries.append((p, list_groups_ext(p.name, context))) if not found: flash(_(u'No users or groups found.'), 'info') return entries
def user_manage(context, request): user_or_group = request.params['name'] principal = get_principals()[user_or_group] is_group = user_or_group.startswith("group:") principal_type = _(u"Group") if is_group else _(u"User") api = template_api( context, request, page_title=_(u"Edit ${principal_type} - ${title}", mapping=dict(principal_type=principal_type, title=context.title)), cp_links=CONTROL_PANEL_LINKS, principal=principal, ) form_view = GroupManageFormView if is_group else UserManageFormView form = form_view(principal, request)() if request.is_response(form): return form return { 'api': api, 'form': form['form'], }
def __call__(self): user_or_group = self.request.params['name'] principal = get_principals()[user_or_group] is_group = user_or_group.startswith("group:") principal_type = _(u"Group") if is_group else _(u"User") api = template_api( self.context, self.request, page_title=_(u"Edit ${principal_type} ${title}", mapping=dict(principal_type=principal_type, title=self.context.title)), cp_links=CONTROL_PANEL_LINKS, principal=principal) form_view = self.GroupManageFormView if is_group \ else self.UserManageFormView form = form_view(principal, self.request)() if self.request.is_response(form): return form return { 'api': api, 'form': form['form'], }
def test_apply(self, extra_principals, root): from kotti.security import get_principals from kotti.security import list_groups from kotti.views.users import UsersManage request = DummyRequest() bob = get_principals()['bob'] request.params['apply'] = '' UsersManage(root, request)() assert (request.session.pop_flash('info') == ['No changes were made.']) assert list_groups('bob') == [] bob.groups = ['role:special'] request.params['role::bob::role:owner'] = '1' request.params['role::bob::role:editor'] = '1' request.params['orig-role::bob::role:owner'] = '' request.params['orig-role::bob::role:editor'] = '' UsersManage(root, request)() assert (request.session.pop_flash('success') == [ 'Your changes have been saved.' ]) assert (set(list_groups('bob')) == { 'role:owner', 'role:editor', 'role:special' })
def save_success(self, appstruct): if appstruct.get('password'): hashed = get_principals().hash_password(appstruct['password']) appstruct['password'] = hashed else: appstruct.pop('password', None) _massage_groups_in(appstruct) return super(UserEditFormView, self).save_success(appstruct)
def extra_principals(db_session): from kotti.security import get_principals P = get_principals() P[u'bob'] = dict(name=u'bob', title=u"Bob") P[u'frank'] = dict(name=u'frank', title=u"Frank") P[u'group:bobsgroup'] = dict(name=u'group:bobsgroup', title=u"Bob's Group") P[u'group:franksgroup'] = dict(name=u'group:franksgroup', title=u"Frank's Group")
def save_success(self, appstruct): if appstruct.get("password"): hashed = get_principals().hash_password(appstruct["password"]) appstruct["password"] = hashed else: appstruct.pop("password", None) _massage_groups_in(appstruct) return super().save_success(appstruct)
def add_some_principals(): from kotti.security import get_principals P = get_principals() P[u"bob"] = {"name": u"bob", "title": u"Bob"} P[u"frank"] = {"name": u"frank", "title": u"Frank"} P[u"group:bobsgroup"] = {"name": u"group:bobsgroup", "title": u"Bob's Group"} P[u"group:franksgroup"] = {"name": u"group:franksgroup", "title": u"Frank's Group"}
def save_success(self, appstruct): if appstruct.get('password'): hashed = get_principals().hash_password(appstruct['password']) appstruct['password'] = hashed else: appstruct.pop('password', None) _massage_groups_in(appstruct) return super(UserManageFormView, self).save_success(appstruct)
def populate_users(): principals = get_principals() if u'admin' not in principals: principals[u'admin'] = { 'name': u'admin', 'password': get_settings()['kotti.secret'], 'title': u"Administrator", 'groups': [u'role:admin'], }
def __call__(self): api = template_api(self.context, self.request, cp_links=CONTROL_PANEL_LINKS) api.page_title = _("User Management") principals = get_principals() def groups_lister(principal_name, context): return principals[principal_name].groups # Handling the user/roles matrix: changed = roles_form_handler(self.context, self.request, USER_MANAGEMENT_ROLES, groups_lister) if changed: changed_names = [] for (principal_name, context, groups) in changed: principal = principals[principal_name] principal.groups = list(groups) changed_names.append(principal_name) location = (self.request.url.split("?")[0] + "?" + urlencode({"extra": ",".join(changed_names)})) return HTTPFound(location=location) extra = self.request.params.get("extra") or () if isinstance(extra, str): extra = extra.split(",") search_entries = search_principals(self.request, extra=extra) available_roles = [ ROLES[role_name] for role_name in USER_MANAGEMENT_ROLES ] # Add forms: user_addform = self.UserAddFormView(self.context, self.request)() if self.request.is_response(user_addform): return user_addform group_addform = self.GroupAddFormView(self.context, self.request)() if self.request.is_response(group_addform): return group_addform if self.request.params.get("add_user"): active_tab = "add_user" elif self.request.params.get("add_group"): active_tab = "add_group" else: active_tab = "search" return { "api": api, "entries": search_entries, "available_roles": available_roles, "user_addform": user_addform["form"], "group_addform": group_addform["form"], "active_tab": active_tab, }
def __call__(self): api = template_api(self.context, self.request, cp_links=CONTROL_PANEL_LINKS) api.page_title = _(u"User Management") principals = get_principals() def groups_lister(principal_name, context): return principals[principal_name].groups # Handling the user/roles matrix: changed = roles_form_handler(self.context, self.request, USER_MANAGEMENT_ROLES, groups_lister) if changed: changed_names = [] for (principal_name, context, groups) in changed: principal = principals[principal_name] principal.groups = list(groups) changed_names.append(principal_name) location = self.request.url.split('?')[0] + '?' + urlencode( {'extra': ','.join(changed_names)}) return HTTPFound(location=location) extra = self.request.params.get('extra') or () if isinstance(extra, string_types): extra = extra.split(',') search_entries = search_principals(self.request, extra=extra) available_roles = [ ROLES[role_name] for role_name in USER_MANAGEMENT_ROLES ] # Add forms: user_addform = self.UserAddFormView(self.context, self.request)() if self.request.is_response(user_addform): return user_addform group_addform = self.GroupAddFormView(self.context, self.request)() if self.request.is_response(group_addform): return group_addform if self.request.params.get('add_user'): active_tab = 'add_user' elif self.request.params.get('add_group'): active_tab = 'add_group' else: active_tab = 'search' return { 'api': api, 'entries': search_entries, 'available_roles': available_roles, 'user_addform': user_addform['form'], 'group_addform': group_addform['form'], 'active_tab': active_tab, }
def test_deleted_group_removed_in_usergroups(self, events, extra_principals, root, db_session): from kotti.security import get_principals from kotti.views.users import user_delete request = DummyRequest() bob = get_principals()['bob'] bob.groups = ['group:bobsgroup'] assert bob.groups == ['group:bobsgroup'] request.params['name'] = 'group:bobsgroup' request.params['delete'] = 'delete' user_delete(root, request) db_session.expire(bob) with pytest.raises(KeyError): # noinspection PyStatementEffect get_principals()['group:bobsgroup'] assert bob.groups == []