def test_enforce_groups(pre_existing, regular_should_be, external_should_be, groups, expected, backend_hg): # TODO: anderson: adding backend_hg fixture so it sets up the database # for when running this file alone _delete_all_user_groups() user = User.get_by_username(TEST_USER_REGULAR_LOGIN) for gr in pre_existing: gr = fixture.create_user_group(gr) Session().commit() # make sure use is just in those groups for gr in regular_should_be: gr = fixture.create_user_group(gr) Session().commit() UserGroupModel().add_user_to_group(gr, user) Session().commit() # now special external groups created by auth plugins for gr in external_should_be: gr = fixture.create_user_group( gr, user_group_data={'extern_type': 'container'}) Session().commit() UserGroupModel().add_user_to_group(gr, user) Session().commit() UserGroupModel().enforce_groups(user, groups, 'container') Session().commit() user = User.get_by_username(TEST_USER_REGULAR_LOGIN) in_groups = user.group_member expected.sort() assert (expected == sorted(x.users_group.users_group_name for x in in_groups))
def action_logger(user, action, repo, ipaddr='', sa=None, commit=False): """ Action logger for various actions made by users :param user: user that made this action, can be a unique username string or object containing user_id attribute :param action: action to log, should be on of predefined unique actions for easy translations :param repo: string name of repository or object containing repo_id, that action was made on :param ipaddr: optional ip address from what the action was made :param sa: optional sqlalchemy session """ if not sa: sa = meta.Session() # if we don't get explicit IP address try to get one from registered user # in tmpl context var if not ipaddr: ipaddr = getattr(get_current_rhodecode_user(), 'ip_addr', '') try: if getattr(user, 'user_id', None): user_obj = User.get(user.user_id) elif isinstance(user, basestring): user_obj = User.get_by_username(user) else: raise Exception('You have to provide a user object or a username') if getattr(repo, 'repo_id', None): repo_obj = Repository.get(repo.repo_id) repo_name = repo_obj.repo_name elif isinstance(repo, basestring): repo_name = repo.lstrip('/') repo_obj = Repository.get_by_repo_name(repo_name) else: repo_obj = None repo_name = '' user_log = UserLog() user_log.user_id = user_obj.user_id user_log.username = user_obj.username action = safe_unicode(action) user_log.action = action[:1200000] user_log.repository = repo_obj user_log.repository_name = repo_name user_log.action_date = datetime.datetime.now() user_log.user_ip = ipaddr sa.add(user_log) log.info('Logging action:`%s` on repo:`%s` by user:%s ip:%s', action, safe_unicode(repo), user_obj, ipaddr) if commit: sa.commit() except Exception: log.error(traceback.format_exc()) raise
def log_pull_action(ui, repo, **kwargs): """ Logs user last pull action :param ui: :param repo: """ ex = _extract_extras() user = User.get_by_username(ex.username) action = 'pull' action_logger(user, action, ex.repository, ex.ip, commit=True) # extension hook call from rhodecode import EXTENSIONS callback = getattr(EXTENSIONS, 'PULL_HOOK', None) if isfunction(callback): kw = {} kw.update(ex) callback(**kw) if ex.make_lock is not None and ex.make_lock: Repository.lock(Repository.get_by_repo_name(ex.repository), user.user_id) #msg = 'Made lock on repo `%s`' % repository #sys.stdout.write(msg) if ex.locked_by[0]: locked_by = User.get(ex.locked_by[0]).username _http_ret = HTTPLockedRC(ex.repository, locked_by) if str(_http_ret.code).startswith('2'): #2xx Codes don't raise exceptions sys.stdout.write(_http_ret.title) return 0
def post_pull(extras): """Hook executed after client pulls the code.""" user = User.get_by_username(extras.username) action = 'pull' action_logger(user, action, extras.repository, extras.ip, commit=True) # extension hook call post_pull_extension(**extras) output = '' # make lock is a tri state False, True, None. We only make lock on True if extras.make_lock is True: Repository.lock(Repository.get_by_repo_name(extras.repository), user.user_id, lock_reason=Repository.LOCK_PULL) msg = 'Made lock on repo `%s`' % (extras.repository, ) output += msg if extras.locked_by[0]: locked_by = User.get(extras.locked_by[0]).username reason = extras.locked_by[2] _http_ret = HTTPLockedRC( _locked_by_explanation(extras.repository, locked_by, reason)) if str(_http_ret.code).startswith('2'): # 2xx Codes don't raise exceptions output += _http_ret.title return HookResponse(0, output)
def test_delete(self): self.log_user() cur_user = self._get_logged_user() u1 = UserModel().create_or_update(username='******', password='******', email='*****@*****.**', firstname='u1', lastname='u1') u2 = UserModel().create_or_update(username='******', password='******', email='*****@*****.**', firstname='u2', lastname='u2') # make notifications notification = NotificationModel().create(created_by=cur_user, subject=u'test', body=u'hi there', recipients=[cur_user, u1, u2]) self.Session().commit() u1 = User.get(u1.user_id) u2 = User.get(u2.user_id) # check DB get_notif = lambda un: [x.notification for x in un] self.assertEqual(get_notif(cur_user.notifications), [notification]) self.assertEqual(get_notif(u1.notifications), [notification]) self.assertEqual(get_notif(u2.notifications), [notification]) cur_usr_id = cur_user.user_id response = self.app.delete(url('notification', notification_id= notification.notification_id)) cur_user = User.get(cur_usr_id) self.assertEqual(cur_user.notifications, [])
def test_extra_email_map(self): usr = UserModel().create_or_update(username=u'test_user', password=u'qweqwe', email=u'*****@*****.**', firstname=u'u1', lastname=u'u1') Session().commit() m = UserEmailMap() m.email = u'*****@*****.**' m.user = usr Session().add(m) Session().commit() u = User.get_by_email(email='*****@*****.**') self.assertEqual(usr.user_id, u.user_id) self.assertEqual(usr.username, u.username) u = User.get_by_email(email='*****@*****.**') self.assertEqual(usr.user_id, u.user_id) self.assertEqual(usr.username, u.username) u = User.get_by_email(email='*****@*****.**') self.assertEqual(None, u) UserModel().delete(usr.user_id) Session().commit()
def test_my_account_remove_auth_token(self): # TODO: without this cleanup it fails when run with the whole # test suite, so there must be some interference with other tests. UserApiKeys.query().delete() usr = self.log_user('test_regular2', 'test12') User.get(usr['user_id']) response = self.app.post(url('my_account_auth_tokens'), { 'description': 'desc', 'lifetime': -1, 'csrf_token': self.csrf_token }) assert_session_flash(response, 'Auth token successfully created') response = response.follow() # now delete our key keys = UserApiKeys.query().all() assert 1 == len(keys) response = self.app.post( url('my_account_auth_tokens'), { '_method': 'delete', 'del_auth_token': keys[0].api_key, 'csrf_token': self.csrf_token }) assert_session_flash(response, 'Auth token successfully deleted') keys = UserApiKeys.query().all() assert 0 == len(keys)
def update_object_permissions(self, form_result): if 'perm_user_id' in form_result: perm_user = User.get(safe_int(form_result['perm_user_id'])) else: # used mostly to do lookup for default user perm_user = User.get_by_username(form_result['perm_user_name']) try: # stage 2 reset defaults and set them from form data self._set_new_user_perms( perm_user, form_result, preserve=[ 'default_repo_group_create', 'default_user_group_create', 'default_repo_create_on_write', 'default_repo_create', 'default_fork_create', 'default_inherit_default_permissions', 'default_register', 'default_extern_activate' ]) # overwrite default repo permissions if form_result['overwrite_default_repo']: _def_name = form_result['default_repo_perm'].split( 'repository.')[-1] _def = Permission.get_by_key('repository.' + _def_name) for r2p in self.sa.query(UserRepoToPerm)\ .filter(UserRepoToPerm.user == perm_user)\ .all(): # don't reset PRIVATE repositories if not r2p.repository.private: r2p.permission = _def self.sa.add(r2p) # overwrite default repo group permissions if form_result['overwrite_default_group']: _def_name = form_result['default_group_perm'].split( 'group.')[-1] _def = Permission.get_by_key('group.' + _def_name) for g2p in self.sa.query(UserRepoGroupToPerm)\ .filter(UserRepoGroupToPerm.user == perm_user)\ .all(): g2p.permission = _def self.sa.add(g2p) # overwrite default user group permissions if form_result['overwrite_default_user_group']: _def_name = form_result['default_user_group_perm'].split( 'usergroup.')[-1] # user groups _def = Permission.get_by_key('usergroup.' + _def_name) for g2p in self.sa.query(UserUserGroupToPerm)\ .filter(UserUserGroupToPerm.user == perm_user)\ .all(): g2p.permission = _def self.sa.add(g2p) self.sa.commit() except (DatabaseError, ): log.exception('Failed to set default object permissions') self.sa.rollback() raise
def pre_push(ui, repo, **kwargs): # pre push function, currently used to ban pushing when # repository is locked try: rc_extras = json.loads(os.environ.get('RC_SCM_DATA', "{}")) except: rc_extras = {} extras = dict(repo.ui.configitems('rhodecode_extras')) if 'username' in extras: username = extras['username'] repository = extras['repository'] scm = extras['scm'] locked_by = extras['locked_by'] elif 'username' in rc_extras: username = rc_extras['username'] repository = rc_extras['repository'] scm = rc_extras['scm'] locked_by = rc_extras['locked_by'] else: raise Exception('Missing data in repo.ui and os.environ') usr = User.get_by_username(username) if locked_by[0] and usr.user_id != int(locked_by[0]): locked_by = User.get(locked_by[0]).username raise HTTPLockedRC(repository, locked_by)
def test_create_notification(self): self.assertEqual([], Notification.query().all()) self.assertEqual([], UserNotification.query().all()) usrs = [self.u1, self.u2] notification = NotificationModel().create(created_by=self.u1, subject=u'subj', body=u'hi there', recipients=usrs) Session().commit() u1 = User.get(self.u1) u2 = User.get(self.u2) u3 = User.get(self.u3) notifications = Notification.query().all() self.assertEqual(len(notifications), 1) self.assertEqual(notifications[0].recipients, [u1, u2]) self.assertEqual(notification.notification_id, notifications[0].notification_id) unotification = UserNotification.query()\ .filter(UserNotification.notification == notification).all() self.assertEqual(len(unotification), len(usrs)) self.assertEqual(set([x.user.user_id for x in unotification]), set(usrs))
def pre_push(extras): """ Hook executed before pushing code. It bans pushing when the repository is locked. """ usr = User.get_by_username(extras.username) output = '' if extras.locked_by[0] and usr.user_id != int(extras.locked_by[0]): locked_by = User.get(extras.locked_by[0]).username reason = extras.locked_by[2] # this exception is interpreted in git/hg middlewares and based # on that proper return code is server to client _http_ret = HTTPLockedRC( _locked_by_explanation(extras.repository, locked_by, reason)) if str(_http_ret.code).startswith('2'): # 2xx Codes don't raise exceptions output = _http_ret.title else: raise _http_ret # Calling hooks after checking the lock, for consistent behavior pre_push_extension(repo_store_path=Repository.base_path(), **extras) return HookResponse(0, output)
def edit_advanced(self, user_id): user_id = safe_int(user_id) user = c.user = User.get_or_404(user_id) if user.username == User.DEFAULT_USER: h.flash(_("You can't edit this user"), category='warning') return redirect(url('users')) c.active = 'advanced' c.perm_user = AuthUser(user_id=user_id, ip_addr=self.ip_addr) c.personal_repo_group = RepoGroup.get_by_group_name(user.username) c.first_admin = User.get_first_super_admin() defaults = user.get_dict() # Interim workaround if the user participated on any pull requests as a # reviewer. has_review = bool(PullRequestReviewers.query().filter( PullRequestReviewers.user_id == user_id).first()) c.can_delete_user = not has_review c.can_delete_user_message = _( 'The user participates as reviewer in pull requests and ' 'cannot be deleted. You can set the user to ' '"inactive" instead of deleting it.') if has_review else '' return htmlfill.render(render('admin/users/user_edit.html'), defaults=defaults, encoding="UTF-8", force_defaults=False)
def test_delete(self): self.log_user() cur_user = self._get_logged_user() u1 = UserModel().create_or_update( username="******", password="******", email="*****@*****.**", firstname="u1", lastname="u1" ) u2 = UserModel().create_or_update( username="******", password="******", email="*****@*****.**", firstname="u2", lastname="u2" ) # make notifications notification = NotificationModel().create( created_by=cur_user, subject=u"test", body=u"hi there", recipients=[cur_user, u1, u2] ) Session().commit() u1 = User.get(u1.user_id) u2 = User.get(u2.user_id) # check DB get_notif = lambda un: [x.notification for x in un] self.assertEqual(get_notif(cur_user.notifications), [notification]) self.assertEqual(get_notif(u1.notifications), [notification]) self.assertEqual(get_notif(u2.notifications), [notification]) cur_usr_id = cur_user.user_id response = self.app.delete(url("notification", notification_id=notification.notification_id)) self.assertEqual(response.body, "ok") cur_user = User.get(cur_usr_id) self.assertEqual(cur_user.notifications, [])
def test_add_delete_ips(self): self.log_user() clear_all_caches() # ADD default_user_id = User.get_default_user().user_id response = self.app.post(url('edit_user_ips', user_id=default_user_id), params={ 'new_ip': '127.0.0.0/24', '_method': 'put', 'csrf_token': self.csrf_token }) response = self.app.get(url('admin_permissions_ips')) response.mustcontain('127.0.0.0/24') response.mustcontain('127.0.0.0 - 127.0.0.255') # DELETE default_user_id = User.get_default_user().user_id del_ip_id = UserIpMap.query().filter( UserIpMap.user_id == default_user_id).first().ip_id response = self.app.post(url('edit_user_ips', user_id=default_user_id), params={ '_method': 'delete', 'del_ip_id': del_ip_id, 'csrf_token': self.csrf_token }) clear_all_caches() response = self.app.get(url('admin_permissions_ips')) response.mustcontain('All IP addresses are allowed') response.mustcontain(no=['127.0.0.0/24']) response.mustcontain(no=['127.0.0.0 - 127.0.0.255'])
def create_test_user(force=True): print '\tcreating test user' user = User.get_by_username(USER) if force and user is not None: print '\tremoving current user' for repo in Repository.query().filter(Repository.user == user).all(): sa.delete(repo) sa.delete(user) sa.commit() if user is None or force: print '\tcreating new one' new_usr = User() new_usr.username = USER new_usr.password = get_crypt_password(PASS) new_usr.email = '*****@*****.**' new_usr.name = 'test' new_usr.lastname = 'lasttestname' new_usr.active = True new_usr.admin = True sa.add(new_usr) sa.commit() print '\tdone'
def test_delete(self): self.log_user() cur_user = self._get_logged_user() u1 = UserModel().create_or_update(username='******', password='******', email='*****@*****.**', firstname='u1', lastname='u1') u2 = UserModel().create_or_update(username='******', password='******', email='*****@*****.**', firstname='u2', lastname='u2') # make notifications notification = NotificationModel().create(created_by=cur_user, subject=u'test', body=u'hi there', recipients=[cur_user, u1, u2]) Session().commit() u1 = User.get(u1.user_id) u2 = User.get(u2.user_id) # check DB get_notif = lambda un: [x.notification for x in un] self.assertEqual(get_notif(cur_user.notifications), [notification]) self.assertEqual(get_notif(u1.notifications), [notification]) self.assertEqual(get_notif(u2.notifications), [notification]) cur_usr_id = cur_user.user_id response = self.app.delete(url('notification', notification_id= notification.notification_id)) self.assertEqual(response.body, 'ok') cur_user = User.get(cur_usr_id) self.assertEqual(cur_user.notifications, [])
def update_application_permissions(self, form_result): if 'perm_user_id' in form_result: perm_user = User.get(safe_int(form_result['perm_user_id'])) else: # used mostly to do lookup for default user perm_user = User.get_by_username(form_result['perm_user_name']) try: # stage 1 set anonymous access if perm_user.username == User.DEFAULT_USER: perm_user.active = str2bool(form_result['anonymous']) self.sa.add(perm_user) # stage 2 reset defaults and set them from form data self._set_new_user_perms(perm_user, form_result, preserve=[ 'default_repo_perm', 'default_group_perm', 'default_user_group_perm', 'default_repo_group_create', 'default_user_group_create', 'default_repo_create_on_write', 'default_repo_create', 'default_fork_create', 'default_inherit_default_permissions', ]) self.sa.commit() except (DatabaseError, ): log.error(traceback.format_exc()) self.sa.rollback() raise
def action_logger(user, action, repo, ipaddr='', sa=None, commit=False): """ Action logger for various actions made by users :param user: user that made this action, can be a unique username string or object containing user_id attribute :param action: action to log, should be on of predefined unique actions for easy translations :param repo: string name of repository or object containing repo_id, that action was made on :param ipaddr: optional ip address from what the action was made :param sa: optional sqlalchemy session """ if not sa: sa = meta.Session() # if we don't get explicit IP address try to get one from registered user # in tmpl context var if not ipaddr: ipaddr = getattr(get_current_rhodecode_user(), 'ip_addr', '') try: if hasattr(user, 'user_id'): user_obj = User.get(user.user_id) elif isinstance(user, basestring): user_obj = User.get_by_username(user) else: raise Exception('You have to provide a user object or a username') if hasattr(repo, 'repo_id'): repo_obj = Repository.get(repo.repo_id) repo_name = repo_obj.repo_name elif isinstance(repo, basestring): repo_name = repo.lstrip('/') repo_obj = Repository.get_by_repo_name(repo_name) else: repo_obj = None repo_name = '' user_log = UserLog() user_log.user_id = user_obj.user_id user_log.username = user_obj.username user_log.action = safe_unicode(action) user_log.repository = repo_obj user_log.repository_name = repo_name user_log.action_date = datetime.datetime.now() user_log.user_ip = ipaddr sa.add(user_log) log.info('Logging action:%s on %s by user:%s ip:%s' % (action, safe_unicode(repo), user_obj, ipaddr)) if commit: sa.commit() except Exception: log.error(traceback.format_exc()) raise
def set_anonymous_access(enable=True): user = User.get_by_username(User.DEFAULT_USER) user.active = enable Session().add(user) Session().commit() print '\tanonymous access is now:', enable if enable != User.get_by_username(User.DEFAULT_USER).active: raise Exception('Cannot set anonymous access')
def set_anonymous_access(enable=True): user = User.get_by_username('default') user.active = enable sa.add(user) sa.commit() print '\tanonymous access is now:', enable if enable != User.get_by_username('default').active: raise Exception('Cannot set anonymous access')
def to_python(self, value, state): try: User.query().filter(User.active == True)\ .filter(User.username == value).one() except Exception: raise formencode.Invalid(_('This username is not valid'), value, state) return value
def set_anonymous_access(enabled): """(Dis)allows anonymous access depending on parameter `enabled`""" user = User.get_default_user() user.active = enabled Session().add(user) Session().commit() log.info('anonymous access is now: %s', enabled) assert enabled == User.get_default_user().active, ( 'Cannot set anonymous access')
def validate_python(self, value, state): try: User.query().filter(User.active == True)\ .filter(User.username == value).one() except Exception: msg = M(self, 'invalid_username', state, username=value) raise formencode.Invalid(msg, value, state, error_dict=dict(username=msg) )
def create_ldap(self, username, password, user_dn, attrs): """ Checks if user is in database, if not creates this user marked as ldap user :param username: :param password: :param user_dn: :param attrs: """ from rhodecode.lib.auth import get_crypt_password log.debug('Checking for such ldap account in RhodeCode database') if self.get_by_username(username, case_insensitive=True) is None: try: new_user = User() # add ldap account always lowercase new_user.username = username.lower() new_user.password = get_crypt_password(password) new_user.api_key = generate_api_key(username) new_user.email = attrs['email'] new_user.active = True new_user.ldap_dn = safe_unicode(user_dn) new_user.name = attrs['name'] new_user.lastname = attrs['lastname'] self.sa.add(new_user) self.sa.commit() return True except (DatabaseError,): log.error(traceback.format_exc()) self.sa.rollback() raise log.debug('this %s user exists skipping creation of ldap account', username) return False
def create_for_container_auth(self, username, attrs): """ Creates the given user if it's not already in the database :param username: :param attrs: """ if self.get_by_username(username, case_insensitive=True) is None: # autogenerate email for container account without one generate_email = lambda usr: '******' % usr try: new_user = User() new_user.username = username new_user.password = None new_user.api_key = generate_api_key(username) new_user.email = attrs['email'] new_user.active = attrs.get('active', True) new_user.name = attrs['name'] or generate_email(username) new_user.lastname = attrs['lastname'] self.sa.add(new_user) return new_user except (DatabaseError, ): log.error(traceback.format_exc()) self.sa.rollback() raise log.debug( 'User %s already exists. Skipping creation of account' ' for container auth.', username) return None
def create_user(self, username, password, email='', admin=False): log.info('creating administrator user %s', username) form_data = dict(username=username, password=password, active=True, admin=admin, name='RhodeCode', lastname='Admin', email=email) User.create(form_data)
def create_user(self, name, **kwargs): if 'skip_if_exists' in kwargs: del kwargs['skip_if_exists'] user = User.get_by_username(name) if user: return user form_data = self._get_user_create_params(name, **kwargs) user = UserModel().create(form_data) Session().commit() user = User.get_by_username(user.username) return user
def create(self, form_data): try: new_user = User() for k, v in form_data.items(): setattr(new_user, k, v) new_user.api_key = generate_api_key(form_data['username']) self.sa.add(new_user) return new_user except: log.error(traceback.format_exc()) raise
def create_default_user(self): log.info('creating default user') #create default user for handling default permissions. form_data = dict(username='******', password=str(uuid.uuid1())[:8], active=False, admin=False, name='Anonymous', lastname='User', email='*****@*****.**') User.create(form_data)
def create_for_container_auth(self, username, attrs, cur_user=None): """ Creates the given user if it's not already in the database :param username: :param attrs: :param cur_user: """ if not cur_user: cur_user = getattr(get_current_rhodecode_user(), 'username', None) if self.get_by_username(username, case_insensitive=True) is None: # autogenerate email for container account without one generate_email = lambda usr: '******' % usr firstname = attrs['name'] lastname = attrs['lastname'] active = attrs.get('active', True) email = attrs['email'] or generate_email(username) from rhodecode.lib.hooks import log_create_user, check_allowed_create_user user_data = { 'username': username, 'password': None, 'email': email, 'firstname': firstname, 'lastname': lastname, 'active': attrs.get('active', True), 'admin': False } # raises UserCreationError if it's not allowed check_allowed_create_user(user_data, cur_user) try: new_user = User() new_user.username = username new_user.password = None new_user.api_key = generate_api_key(username) new_user.email = email new_user.active = active new_user.name = firstname new_user.lastname = lastname self.sa.add(new_user) log_create_user(new_user.get_dict(), cur_user) return new_user except (DatabaseError, ): log.error(traceback.format_exc()) self.sa.rollback() raise log.debug( 'User %s already exists. Skipping creation of account' ' for container auth.', username) return None
def test_forgot_password(self): response = self.app.get( url(controller='login', action='password_reset')) self.assertEqual(response.status, '200 OK') username = '******' password = '******' email = '*****@*****.**' name = 'passwd' lastname = 'reset' new = User() new.username = username new.password = password new.email = email new.name = name new.lastname = lastname new.api_key = generate_api_key(username) self.Session().add(new) self.Session().commit() response = self.app.post( url(controller='login', action='password_reset'), { 'email': email, }) self.checkSessionFlash(response, 'Your password reset link was sent') response = response.follow() # BAD KEY key = "bad" response = self.app.get( url(controller='login', action='password_reset_confirmation', key=key)) self.assertEqual(response.status, '302 Found') self.assertTrue(response.location.endswith(url('reset_password'))) # GOOD KEY key = User.get_by_username(username).api_key response = self.app.get( url(controller='login', action='password_reset_confirmation', key=key)) self.assertEqual(response.status, '302 Found') self.assertTrue(response.location.endswith(url('login_home'))) self.checkSessionFlash(response, ('Your password reset was successful, ' 'new password has been sent to your email')) response = response.follow()
def create_for_container_auth(self, username, attrs): """ Creates the given user if it's not already in the database :param username: :param attrs: """ if self.get_by_username(username, case_insensitive=True) is None: # autogenerate email for container account without one generate_email = lambda usr: '******' % usr try: new_user = User() new_user.username = username new_user.password = None new_user.api_key = generate_api_key(username) new_user.email = attrs['email'] new_user.active = attrs.get('active', True) new_user.name = attrs['name'] or generate_email(username) new_user.lastname = attrs['lastname'] self.sa.add(new_user) return new_user except (DatabaseError,): log.error(traceback.format_exc()) self.sa.rollback() raise log.debug('User %s already exists. Skipping creation of account' ' for container auth.', username) return None
def test_index_with_anonymous_access_disabled(self): anon = User.get_by_username('default') anon.active = False Session().add(anon) Session().commit() time.sleep(1.5) # must sleep for cache (1s to expire) try: response = self.app.get(url(controller='home', action='index'), status=302) assert 'login' in response.location finally: anon = User.get_by_username('default') anon.active = True Session().add(anon) Session().commit()
def test_index_with_anonymous_access_disabled(self): anon = User.get_default_user() anon.active = False Session().add(anon) Session().commit() time.sleep(1.5) # must sleep for cache (1s to expire) try: response = self.app.get(url(controller='home', action='index'), status=302) assert 'login' in response.location finally: anon = User.get_default_user() anon.active = True Session().add(anon) Session().commit()
def my_account_update(self): """PUT /_admin/my_account_update: Update an existing item""" # Forms posted to this method should contain a hidden field: # <input type="hidden" name="_method" value="PUT" /> # Or using helpers: # h.form(url('admin_settings_my_account_update'), # method='put') # url('admin_settings_my_account_update', id=ID) user_model = UserModel() uid = self.rhodecode_user.user_id _form = UserForm(edit=True, old_data={'user_id': uid, 'email': self.rhodecode_user.email})() form_result = {} try: form_result = _form.to_python(dict(request.POST)) user_model.update_my_account(uid, form_result) h.flash(_('Your account was updated successfully'), category='success') Session.commit() except formencode.Invalid, errors: c.user = User.get(self.rhodecode_user.user_id) all_repos = self.sa.query(Repository)\ .filter(Repository.user_id == c.user.user_id)\ .order_by(func.lower(Repository.repo_name))\ .all() c.user_repos = ScmModel().get_repos(all_repos) return htmlfill.render( render('admin/users/user_edit_my_account.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8")
def my_account(self): """ GET /_admin/my_account Displays info about my account """ # url('admin_settings_my_account') c.user = User.get(self.rhodecode_user.user_id) all_repos = self.sa.query(Repository)\ .filter(Repository.user_id == c.user.user_id)\ .order_by(func.lower(Repository.repo_name)).all() c.user_repos = ScmModel().get_repos(all_repos) if c.user.username == 'default': h.flash(_("You can't edit this user since it's" " crucial for entire application"), category='warning') return redirect(url('users')) defaults = c.user.get_dict() return htmlfill.render( render('admin/users/user_edit_my_account.html'), defaults=defaults, encoding="UTF-8", force_defaults=False )
def _extract_mentions(self, s): user_objects = [] for username in extract_mentioned_users(s): user_obj = User.get_by_username(username, case_insensitive=True) if user_obj: user_objects.append(user_obj) return user_objects
def validate_python(self, value, state): user = User.get_by_email(value, case_insensitive=True) if user is None: msg = M(self, 'non_existing_email', state, email=value) raise formencode.Invalid(msg, value, state, error_dict=dict(email=msg) )
def _load_data(self, id): c.users_group.permissions = { 'repositories': {}, 'repositories_groups': {} } ugroup_repo_perms = UsersGroupRepoToPerm.query()\ .options(joinedload(UsersGroupRepoToPerm.permission))\ .options(joinedload(UsersGroupRepoToPerm.repository))\ .filter(UsersGroupRepoToPerm.users_group_id == id)\ .all() for gr in ugroup_repo_perms: c.users_group.permissions['repositories'][gr.repository.repo_name] \ = gr.permission.permission_name ugroup_group_perms = UsersGroupRepoGroupToPerm.query()\ .options(joinedload(UsersGroupRepoGroupToPerm.permission))\ .options(joinedload(UsersGroupRepoGroupToPerm.group))\ .filter(UsersGroupRepoGroupToPerm.users_group_id == id)\ .all() for gr in ugroup_group_perms: c.users_group.permissions['repositories_groups'][gr.group.group_name] \ = gr.permission.permission_name c.group_members_obj = [x.user for x in c.users_group.members] c.group_members = [(x.user_id, x.username) for x in c.group_members_obj] c.available_members = [(x.user_id, x.username) for x in User.query().all()]
def _load_data(self, id): c.users_group.permissions = { 'repositories': {}, 'repositories_groups': {} } ugroup_repo_perms = UserGroupRepoToPerm.query()\ .options(joinedload(UserGroupRepoToPerm.permission))\ .options(joinedload(UserGroupRepoToPerm.repository))\ .filter(UserGroupRepoToPerm.users_group_id == id)\ .all() for gr in ugroup_repo_perms: c.users_group.permissions['repositories'][gr.repository.repo_name] \ = gr.permission.permission_name ugroup_group_perms = UserGroupRepoGroupToPerm.query()\ .options(joinedload(UserGroupRepoGroupToPerm.permission))\ .options(joinedload(UserGroupRepoGroupToPerm.group))\ .filter(UserGroupRepoGroupToPerm.users_group_id == id)\ .all() for gr in ugroup_group_perms: c.users_group.permissions['repositories_groups'][gr.group.group_name] \ = gr.permission.permission_name c.group_members_obj = sorted((x.user for x in c.users_group.members), key=lambda u: u.username.lower()) c.group_members = [(x.user_id, x.username) for x in c.group_members_obj] c.available_members = sorted( ((x.user_id, x.username) for x in User.query().all()), key=lambda u: u[1].lower())
def repo_public_journal(self, repo_name): """ Set's this repository to be visible in public journal, in other words assing default user to follow this repo :param repo_name: """ cur_token = request.POST.get('auth_token') token = get_token() if cur_token == token: try: repo_id = Repository.get_by_repo_name(repo_name).repo_id user_id = User.get_by_username('default').user_id self.scm_model.toggle_following_repo(repo_id, user_id) h.flash(_('Updated repository visibility in public journal'), category='success') Session().commit() except Exception: h.flash(_('An error occurred during setting this' ' repository in public journal'), category='error') else: h.flash(_('Token mismatch'), category='error') return redirect(url('edit_repo', repo_name=repo_name))
def repo_public_journal(self, repo_name): """ Set's this repository to be visible in public journal, in other words assing default user to follow this repo :param repo_name: """ cur_token = request.POST.get('auth_token') token = get_token() if cur_token == token: try: repo_id = Repository.get_by_repo_name(repo_name).repo_id user_id = User.get_by_username('default').user_id self.scm_model.toggle_following_repo(repo_id, user_id) h.flash(_('Updated repository visibility in public journal'), category='success') Session.commit() except: h.flash(_('An error occurred during setting this' ' repository in public journal'), category='error') else: h.flash(_('Token mismatch'), category='error') return redirect(url('edit_repo', repo_name=repo_name))
def edit(self, id, format='html'): """GET /users/id/edit: Form to edit an existing item""" # url('edit_user', id=ID) c.user = User.get_or_404(id) if c.user.username == 'default': h.flash(_("You can't edit this user"), category='warning') return redirect(url('users')) c.perm_user = AuthUser(user_id=id, ip_addr=self.ip_addr) c.user.permissions = {} c.granted_permissions = UserModel().fill_perms(c.user)\ .permissions['global'] c.user_email_map = UserEmailMap.query()\ .filter(UserEmailMap.user == c.user).all() c.user_ip_map = UserIpMap.query()\ .filter(UserIpMap.user == c.user).all() user_model = UserModel() c.ldap_dn = c.user.ldap_dn defaults = c.user.get_dict() defaults.update({ 'create_repo_perm': user_model.has_perm(id, 'hg.create.repository'), 'fork_repo_perm': user_model.has_perm(id, 'hg.fork.repository'), }) return htmlfill.render( render('admin/users/user_edit.html'), defaults=defaults, encoding="UTF-8", force_defaults=False )
def test_update(self, name, expected): self.log_user() uname = 'testme' usr = UserModel().create_or_update(username=uname, password='******', email='*****@*****.**') self.Session().commit() params = usr.get_api_data() params.update({name: expected}) params.update({'password_confirmation': ''}) params.update({'new_password': ''}) if name == 'email': params['emails'] = [expected] if name == 'ldap_dn': #cannot update this via form params['ldap_dn'] = None try: response = self.app.put(url('user', id=usr.user_id), params) self.checkSessionFlash(response, '''User updated successfully''') updated_user = User.get_by_username(uname) updated_params = updated_user.get_api_data() updated_params.update({'password_confirmation': ''}) updated_params.update({'new_password': ''}) self.assertEqual(params, updated_params) finally: UserModel().delete('testme')
def edit(self, id, format='html'): """GET /users_groups/id/edit: Form to edit an existing item""" # url('edit_users_group', id=ID) c.users_group = UsersGroup.get_or_404(id) c.users_group.permissions = {} c.group_members_obj = [x.user for x in c.users_group.members] c.group_members = [(x.user_id, x.username) for x in c.group_members_obj] c.available_members = [(x.user_id, x.username) for x in User.query().all()] ug_model = UsersGroupModel() defaults = c.users_group.get_dict() defaults.update({ 'create_repo_perm': ug_model.has_perm(c.users_group, 'hg.create.repository'), 'fork_repo_perm': ug_model.has_perm(c.users_group, 'hg.fork.repository'), }) return htmlfill.render( render('admin/users_groups/users_group_edit.html'), defaults=defaults, encoding="UTF-8", force_defaults=False )
def _get_permission_for_user(user, repo): perm = UserRepoToPerm.query()\ .filter(UserRepoToPerm.repository == Repository.get_by_repo_name(repo))\ .filter(UserRepoToPerm.user == User.get_by_username(user))\ .all() return perm
def test_update(self, name, expected): self.log_user() uname = "testme" usr = UserModel().create_or_update(username=uname, password="******", email="*****@*****.**") self.Session().commit() params = usr.get_api_data() params.update({name: expected}) params.update({"password_confirmation": ""}) params.update({"new_password": ""}) if name == "email": params["emails"] = [expected] if name == "ldap_dn": # cannot update this via form params["ldap_dn"] = None try: response = self.app.put(url("user", id=usr.user_id), params) self.checkSessionFlash(response, """User updated successfully""") updated_user = User.get_by_username(uname) updated_params = updated_user.get_api_data() updated_params.update({"password_confirmation": ""}) updated_params.update({"new_password": ""}) self.assertEqual(params, updated_params) finally: UserModel().delete("testme")
def test_subgrouping_with_repo(self): g1 = _make_group('g1') g2 = _make_group('g2') # create new repo form_data = dict(repo_name='john', repo_name_full='john', fork_name=None, description=None, repo_group=None, private=False, repo_type='hg', clone_uri=None) cur_user = User.get_by_username(TEST_USER_ADMIN_LOGIN) r = RepoModel().create(form_data, cur_user) self.assertEqual(r.repo_name, 'john') # put repo into group form_data = form_data form_data['repo_group'] = g1.group_id form_data['perms_new'] = [] form_data['perms_updates'] = [] RepoModel().update(r.repo_name, form_data) self.assertEqual(r.repo_name, 'g1/john') self.__update_group(g1.group_id, 'g1', parent_id=g2.group_id) self.assertTrue(self.__check_path('g2', 'g1')) # test repo self.assertEqual(r.repo_name, RepoGroup.url_sep().join(['g2', 'g1', r.just_name]))
def index(self): # Return a rendered template p = int(request.params.get('page', 1)) c.user = User.get(self.rhodecode_user.user_id) all_repos = self.sa.query(Repository)\ .filter(Repository.user_id == c.user.user_id)\ .order_by(func.lower(Repository.repo_name)).all() c.user_repos = ScmModel().get_repos(all_repos) c.following = self.sa.query(UserFollowing)\ .filter(UserFollowing.user_id == self.rhodecode_user.user_id)\ .options(joinedload(UserFollowing.follows_repository))\ .all() journal = self._get_journal_data(c.following) c.journal_pager = Page(journal, page=p, items_per_page=20) c.journal_day_aggreagate = self._get_daily_aggregate(c.journal_pager) c.journal_data = render('journal/journal_data.html') if request.environ.get('HTTP_X_PARTIAL_XHR'): return c.journal_data return render('journal/journal.html')
def my_account(self): """ GET /_admin/my_account Displays info about my account """ # url('admin_settings_my_account') c.user = User.get(self.rhodecode_user.user_id) c.perm_user = AuthUser(user_id=self.rhodecode_user.user_id, ip_addr=self.ip_addr) c.ldap_dn = c.user.ldap_dn if c.user.username == 'default': h.flash(_("You can't edit this user since it's" " crucial for entire application"), category='warning') return redirect(url('users')) #json used to render the grid c.data = self._load_my_repos_data() defaults = c.user.get_dict() c.form = htmlfill.render( render('admin/users/user_edit_my_account_form.html'), defaults=defaults, encoding="UTF-8", force_defaults=False ) return render('admin/users/user_edit_my_account.html')