def test_not_losing_inactives(self): u1 = User.testing_create() u2 = User.testing_create() u2.inactive_flag = True g = Group.testing_create() g.users = [u2] db.sess.commit() topost = { 'approved_permissions': [], 'assigned_users': [u1.id], 'denied_permissions': [], 'group-submit-flag': u'submitted', 'name': g.name, 'submit': u'Submit' } req, resp = self.c.post('groups/edit/{0}'.format(g.id), data=topost, follow_redirects=True) assert resp.status_code == 200, resp.status assert '/groups/manage' in req.url, req.url db.sess.expire(g) eq_(len(g.users), 2) assert u1 in g.users assert u2 in g.users
def add_administrative_user(allow_profile_defaults=True): from getpass import getpass from compstack.auth.model.orm import User input_function = input if six.PY2: input_function = raw_input # noqa defaults = settings.components.auth.admin # add a default administrative user if allow_profile_defaults and defaults.username and defaults.password and defaults.email: ulogin = defaults.username uemail = defaults.email p1 = defaults.password else: ulogin = input_function("User's Login id:\n> ") uemail = input_function("User's email:\n> ") while True: p1 = getpass("User's password:\n> ") p2 = getpass("confirm password:\n> ") if p1 == p2: break User.add_iu( login_id=six.text_type(ulogin), email_address=six.text_type(uemail), password=p1, super_user=True, reset_required=False, pass_reset_ok=False, )
def test_user_validate(): u = create_user_with_permissions() u.password = u'testpass123' db.sess.commit() assert User.validate(u.login_id, u'bad_password') is None assert User.validate(u'bad_login', u'testpass123') is None assert User.validate(u.login_id, u'testpass123').id == u.id
def auth_calculate(self, objid=None): CrudBase.auth_calculate(self, objid=objid) # prevent non-super users from editing super users if objid and session_user.is_authenticated: sess_user_obj = orm_User.get(session_user.id) edited_user_obj = orm_User.get(objid) if edited_user_obj and edited_user_obj.super_user and not sess_user_obj.super_user: self.is_authorized = False
def form_on_valid(self): formvals = self.form.get_values() # assigned groups and permissions stay the same for profile submissions formvals['assigned_groups'] = self.objinst.group_ids formvals['approved_permissions'], formvals['denied_permissions'] = \ self.objinst.assigned_permission_ids formvals['pass_reset_ok'] = False orm_User.edit(self.objid, **formvals) session_user.add_message('notice', 'profile updated succesfully')
def test_user_update(): u = create_user_with_permissions() current_hash = u.pass_hash u = User.edit(u.id, pass_hash=u'123456') assert u.pass_hash == current_hash u.reset_required = False db.sess.commit() u = User.edit(u.id, email_notify=True) assert not u.reset_required u = User.edit(u.id, password='******') assert u.reset_required
def post(self): if self.form.is_valid(): orm_User.get(session_user.id).update_password(self.form.elements.password.value) session_user.reset_required = False session_user.add_message('notice', 'Your password has been changed successfully.') url = after_login_url() if rg.request.url == url_for('auth:ChangePassword') \ else rg.request.url redirect(url) elif self.form.is_submitted(): # form was submitted, but invalid self.form.assign_user_errors() self.default()
def test_user_group_assignment(): g1 = Group.add_iu(name=u'group_for_testing_%s' % randchars(15)) g2 = Group.add_iu(name=u'group_for_testing_%s' % randchars(15)) u = create_user_with_permissions() assert u.groups == [] User.edit(u.id, assigned_groups=[g1.id, g2.id]) assert len(u.groups) == 2 assert len(g1.users) == len(g2.users) == 1 User.edit(u.id, assigned_groups=g2.id) assert len(u.groups) == 1 assert u.groups[0].id == g2.id
def test_user_permission_map(self): permissions_approved = [ 'ugp_approved', 'ugp_approved_grp'] # test user perms map perm_map = User.get(self.user.id).permission_map for rec in perm_map: assert rec['resulting_approval'] == (rec['permission_name'] in permissions_approved)
def test_fields_load(self): """ make sure fields load with data currently in db """ r = self.c.get('users/profile') assert r.status_code == 200, r.status user = User.get(self.userid) assert user.email_address.encode() in r.data assert user.login_id.encode() in r.data r = self.c.post('users/profile', data=self.get_to_post()) assert r.status_code == 200, r.status user = User.get(self.userid) assert user.email_address.encode() in r.data assert user.login_id.encode() in r.data assert b'usersfirstname' in r.data assert b'userslastname' in r.data assert b'profile updated succesfully' in r.data
def post(self): if self.form.is_valid(): em_address = self.form.elements.email_address.value user_obj = orm_User.reset_password(em_address) if user_obj: if send_reset_password_email(user_obj): session_user.add_message( 'notice', 'An email with a link to reset your password has been sent.' ) else: session_user.add_message( 'error', 'An error occurred while sending the notification email. Your ' 'password has not been reset.' ) url = current_url(root_only=True) redirect(url) else: session_user.add_message( 'error', 'Did not find a user with email address: %s' % em_address ) elif self.form.is_submitted(): # form was submitted, but invalid self.form.assign_user_errors() self.default()
def post(self): if self.form.is_valid(): user = orm_User.validate( self.form.els.login_id.value, self.form.els.password.value ) if user: if user.inactive: session_user.add_message('error', 'That user is inactive.') else: load_session_user(user) log.application('user %s logged in; session id: %s; remote_ip: %s', user.login_id, rg.session.id, rg.request.remote_addr) session_user.add_message('notice', 'You logged in successfully!') if user.reset_required: url = url_for('auth:ChangePassword') else: url = after_login_url() redirect(url) else: log.application('user login failed; user login: %s; session id: %s; remote_ip: %s', self.form.elements.login_id.value, rg.session.id, rg.request.remote_addr) session_user.add_message('error', 'Login failed! Please try again.') elif self.form.is_submitted(): # form was submitted, but invalid self.form.assign_user_errors() self.default()
def test_email_dups(self): user2 = User.get(self.userid2) topost = self.get_to_post() topost['email_address'] = user2.email_address r = self.c.post('users/profile', data=topost) assert r.status_code == 200, r.status assert b'Email: a user with that email address already exists' in r.data
def update(cls, oid=None, **kwargs): from compstack.auth.model.orm import User if oid is None: g = cls() db.sess.add(g) else: g = cls.get(oid) for k, v in six.iteritems(kwargs): try: # some values can not be set directly if k in ('assigned_users', 'approved_permissions', 'denied_permissions'): pass else: setattr(g, k, v) except AttributeError: pass g.users = [ User.get(uid) for uid in tolist(kwargs.get('assigned_users', [])) ] db.sess.flush() g.assign_permissions(kwargs.get('approved_permissions', []), kwargs.get('denied_permissions', [])) return g
def test_login_id_dups(self): user2 = User.get(self.userid2) topost = self.get_to_post() topost['login_id'] = user2.login_id r = self.c.post('users/profile', data=topost) assert r.status_code == 200, r.status assert b'Login Id: that user already exists' in r.data
def test_password_changes(self): user = User.get(self.userid) pass_hash = user.pass_hash r = self.c.post('users/profile', data=self.get_to_post()) assert r.status_code == 200, r.status user = User.get(self.userid) assert user.pass_hash == pass_hash topost = self.get_to_post() topost['password'] = '******' topost['password-confirm'] = 'newpass' r = self.c.post('users/profile', data=topost) assert r.status_code == 200, r.status db.sess.expire(user) assert user.pass_hash != pass_hash
def test_perm_changes(self): p1 = Permission.get_by(name=u'prof-test-1').id p2 = Permission.get_by(name=u'prof-test-2').id # add user to group user = User.get(self.userid) gp = Group.add_iu(name=u'test-group', approved_permissions=[], denied_permissions=[], assigned_users=[user.id]).id r = self.c.post('users/profile', data=self.get_to_post()) assert r.status_code == 200, r.status user = User.get(self.userid) approved, denied = user.assigned_permission_ids assert p1 in approved assert p2 in denied assert gp in [g.id for g in user.groups]
def is_group_fk_present(): g = Group.testing_create() u = User.testing_create(groups=g) gid = g.id # delete the group with delete_where() because .delete() loads the ORM # object and then calls <session>.delete(). That method will trigger SA # to issue a DELETE statement on the map table. Therefore, using # .delete() would allow this test to pass even if our FK was not # configured correctly. Group.delete_where(Group.id == gid) # if there are no records left, then the FK is present try: return db.sess.query(tbl_ugm).filter( tbl_ugm.c.auth_group_id == gid).count() == 0 finally: db.sess.execute(tbl_ugm.delete().where(tbl_ugm.c.auth_group_id == gid)) User.delete(u.id)
def get_to_post(self): user = User.get(self.userid) topost = { 'name_first': 'usersfirstname', 'name_last': 'userslastname', 'login_id': user.login_id, 'email_address': user.email_address, 'user-profile-form-submit-flag': 'submitted' } return topost
def test_user_get_by_permissions(self): # user directly approved users_approved = User.get_by_permissions(u'ugp_approved') assert users_approved[0] is self.user assert users_approved[1] is self.user2 assert len(users_approved) == 2 # user approved by group association assert User.get_by_permissions(u'ugp_approved_grp')[0] is self.user # user denial and group approval assert User.get_by_permissions(u'ugp_denied') == [] # no approval assert User.get_by_permissions(u'ugp_not_approved') == [] # approved by one group denied by another, denial takes precedence assert User.get_by_permissions(u'ugp_denied_grp') == []
def test_non_existing_id(self): non_existing_id = 9999 while User.get(non_existing_id): non_existing_id += 1000 req, resp = self.c.get('users/edit/%s' % non_existing_id, follow_redirects=True) assert req.url.endswith('/users/edit/%s' % non_existing_id), req.url assert resp.status_code == 404, resp.status req, resp = self.c.get('users/delete/%s' % non_existing_id, follow_redirects=True) assert req.url.endswith('users/delete/%s' % non_existing_id), req.url assert resp.status_code == 404, resp.status
def form_orm_edit(self): # form does not list inactive users. But, such users should remain in # their respective groups in case of reactivation. Pull them into # the list here d = self.form.get_values() existing_inactives = orm_User.query().join(orm_User.groups).filter( self.ormcls.id == self.objid, orm_User.inactive == sa.true(), ).all() d['assigned_users'] += [u.id for u in existing_inactives] return self.ormcls.edit(self.objid, **d)
def test_no_exc_with_user_permissions(self): u = User.testing_create() ap = Permission.testing_create() dp = Permission.testing_create() u.assign_permissions([ap.id], [dp.id]) db.sess.commit() resp = self.tam.get('/users/permissions/{0}'.format(u.id)) assert b'<h1>Permissions for: ' in resp d = resp.pyq assert str(d('td.approved a[href="/users/edit/{0}"]'.format(u.id))) assert str(d('td.denied a[href="/users/edit/{0}"]'.format(u.id)))
def add_user_membership_section(self): self.add_header('group_membership_header', 'Users In Group') # list only active users, using the "inactive" hybrid property to account # for all cases users = orm_User.list_where( orm_User.inactive == sa.false(), order_by=[orm_User.name, orm_User.login_id]) user_opts = [ (u.id, '{0} ({1})'.format(u.name, u.login_id) if u.name else u.login_id) for u in users ] self.add_mselect('assigned_users', user_opts, 'Assign', choose=None)
def test_no_exc_with_group_permissions(self): g = Group.testing_create() ap = Permission.testing_create() dp = Permission.testing_create() g.assign_permissions([ap.id], [dp.id]) u = User.testing_create(groups=g) resp = self.tam.get('/users/permissions/{0}'.format(u.id)) assert b'<h1>Permissions for: ' in resp d = resp.pyq db.sess.add(g) assert str(d('td.approved a[href="/groups/edit/{0}"]'.format(g.id))) assert str(d('td.denied a[href="/groups/edit/{0}"]'.format(g.id)))
def test_loginid_unique(self): user = User.get(self.userid) topost = { 'login_id': user.login_id, 'password': '******', 'email_address': '*****@*****.**', 'password-confirm': 'testtest', 'user-submit-flag': 'submitted', 'inactive_flag': False, 'inactive_date': '', 'name_first': '', 'name_last': '' } r = self.c.post('users/add', data=topost) assert r.status_code == 200, r.status assert b'Login Id: that user already exists' in r.data
def test_fields_saved(self): ap = Permission.get_by(name=u'users-test1').id dp = Permission.get_by(name=u'users-test2').id gp = Group.get_by(name=u'test-group') or Group.add_iu( name=u'test-group', approved_permissions=[], denied_permissions=[], assigned_users=[]) gp = gp.id topost = { 'login_id': 'usersavedsu', 'password': '******', 'email_address': '*****@*****.**', 'password-confirm': 'testtest', 'email': '*****@*****.**', 'user-submit-flag': 'submitted', 'approved_permissions': ap, 'denied_permissions': dp, 'assigned_groups': gp, 'super_user': 1, 'inactive_flag': False, 'inactive_date': '', 'name_first': '', 'name_last': '' } req, r = self.c.post('users/add', data=topost, follow_redirects=True) assert r.status_code == 200, r.status assert b'User added' in r.data assert req.url.endswith('users/manage') user = User.get_by_email(u'*****@*****.**') assert user.login_id == 'usersavedsu' assert user.reset_required assert user.super_user assert user.pass_hash assert user.groups[0].name == 'test-group' assert len(user.groups) == 1 found = 3 for permrow in user.permission_map: if permrow['permission_name'] == u'users-test1': assert permrow['resulting_approval'] found -= 1 if permrow['permission_name'] in (u'users-test2', u'auth-manage'): assert not permrow['resulting_approval'] found -= 1 assert found == 0
def setup_view(self, login_id, key): # this probably should never happen, but doesn't hurt to check if not key or not login_id: self.abort() user = orm_User.get_by(login_id=login_id) if not user or user.inactive: self.abort() if key != user.pass_reset_key: self.abort() expires_on = user.pass_reset_ts + datetime.timedelta( hours=settings.components.auth.password_rest_expires_after ) if datetime.datetime.utcnow() > expires_on: self.abort('password reset link expired') self.user = user self.form = NewPasswordForm()
def test_user_permission_map_groups(self): # test group perms map perm_map = User.get(self.user.id).permission_map_groups assert not Permission.get_by(name=u'ugp_approved').id in perm_map assert not Permission.get_by(name=u'ugp_not_approved').id in perm_map assert len(perm_map[self.perm_approved_grp.id]['approved']) == 1 assert perm_map[self.perm_approved_grp.id]['approved'][0]['id'] == self.g1.id assert len(perm_map[self.perm_approved_grp.id]['denied']) == 0 assert len(perm_map[self.perm_denied.id]['approved']) == 1 assert perm_map[self.perm_denied.id]['approved'][0]['id'] == self.g1.id assert len(perm_map[self.perm_denied.id]['denied']) == 0 assert len(perm_map[self.perm_denied_grp.id]['approved']) == 1 assert perm_map[self.perm_denied_grp.id]['approved'][0]['id'] == self.g1.id assert len(perm_map[self.perm_denied_grp.id]['denied']) == 1 assert perm_map[self.perm_denied_grp.id]['denied'][0]['id'] == self.g2.id
def add_user(login_id, email, password=None, super_user=False, send_email=True): """ Creates a new user and optionally sends out the welcome email """ from compstack.auth.model.orm import User from compstack.auth.helpers import send_new_user_email u = User.add(login_id=login_id, email_address=email, password=password or randchars(8), super_user=super_user) if send_email: email_sent = send_new_user_email(u) else: email_sent = False return u, email_sent