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 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 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 add_user_to_users_group(self, apiuser, group_name, username): """" Add a user to a users group :param apiuser: :param group_name: :param username: """ try: users_group = UsersGroup.get_by_group_name(group_name) if not users_group: raise JSONRPCError('unknown users group %s' % group_name) user = User.get_by_username(username) if user is None: raise JSONRPCError('unknown user %s' % username) ugm = UsersGroupModel().add_user_to_group(users_group, user) success = True if ugm != True else False msg = 'added member %s to users group %s' % (username, group_name) msg = msg if success else 'User is already in that group' Session.commit() return dict( id=ugm.users_group_member_id if ugm != True else None, success=success, msg=msg ) except Exception: log.error(traceback.format_exc()) raise JSONRPCError('failed to add users group member')
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 edit(self, id, format='html'): """GET /permissions/id/edit: Form to edit an existing item""" #url('edit_permission', id=ID) #this form can only edit default user permissions if id == 'default': c.user = default_user = User.get_by_username('default') defaults = {'anonymous': default_user.active} c.perm_user = AuthUser(user_id=default_user.user_id) c.user_ip_map = UserIpMap.query()\ .filter(UserIpMap.user == default_user).all() for p in default_user.user_perms: if p.permission.permission_name.startswith('repository.'): defaults['default_repo_perm'] = p.permission.permission_name if p.permission.permission_name.startswith('group.'): defaults['default_group_perm'] = p.permission.permission_name if p.permission.permission_name.startswith('hg.register.'): defaults['default_register'] = p.permission.permission_name if p.permission.permission_name.startswith('hg.create.'): defaults['default_create'] = p.permission.permission_name if p.permission.permission_name.startswith('hg.fork.'): defaults['default_fork'] = p.permission.permission_name return htmlfill.render( render('admin/permissions/permissions.html'), defaults=defaults, encoding="UTF-8", force_defaults=False ) else: return redirect(url('admin_home'))
def test_push_unlocks_repository_git(self, rc_web_server, tmpdir): # Note: Did a first debugging session. Seems that # Repository.get_locking_state is called twice. The second call # has the action "pull" and does not reset the lock. # enable locking r = Repository.get_by_repo_name(GIT_REPO) r.enable_locking = True Session().add(r) Session().commit() clone_url = rc_web_server.repo_clone_url(GIT_REPO) stdout, stderr = Command('/tmp').execute( 'git clone', clone_url, tmpdir.strpath) _check_proper_clone(stdout, stderr, 'git') # check for lock repo after clone r = Repository.get_by_repo_name(GIT_REPO) assert r.locked[0] == User.get_by_username( TEST_USER_ADMIN_LOGIN).user_id # push is ok and repo is now unlocked stdout, stderr = _add_files_and_push( 'git', tmpdir.strpath, clone_url=clone_url) _check_proper_git_push(stdout, stderr) # assert ('remote: Released lock on repo `%s`' % GIT_REPO) in stdout # we need to cleanup the Session Here ! Session.remove() r = Repository.get_by_repo_name(GIT_REPO) assert r.locked == [None, None, None]
def register(self): user_model = UserModel() c.auto_active = False for perm in User.get_by_username("default").user_perms: if perm.permission.permission_name == "hg.register.auto_activate": c.auto_active = True break if request.POST: register_form = RegisterForm()() try: form_result = register_form.to_python(dict(request.POST)) form_result["active"] = c.auto_active user_model.create_registration(form_result) h.flash(_("You have successfully registered into rhodecode"), category="success") return redirect(url("login_home")) except formencode.Invalid, errors: return htmlfill.render( render("/register.html"), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8", )
def _store_user_in_session(session, username, remember=False): user = User.get_by_username(username, case_insensitive=True) auth_user = AuthUser(user.user_id) auth_user.set_authenticated() cs = auth_user.get_cookie_store() session['rhodecode_user'] = cs user.update_lastlogin() Session().commit() # If they want to be remembered, update the cookie if remember: _year = (datetime.datetime.now() + datetime.timedelta(seconds=60 * 60 * 24 * 365)) session._set_cookie_expires(_year) session.save() log.info('user %s is now authenticated and stored in ' 'session, session attrs %s', username, cs) # dumps session attrs back to cookie session._update_cookie_out() # we set new cookie headers = None if session.request['set_cookie']: # send set-cookie headers back to response to update cookie headers = [('Set-Cookie', session.request['cookie_out'])] return headers
def revoke_user_permission(self, apiuser, repo_name, username): """ Revoke permission for user on given repository :param repo_name: :param username: """ try: repo = Repository.get_by_repo_name(repo_name) if repo is None: raise JSONRPCError('unknown repository %s' % repo) user = User.get_by_username(username) if user is None: raise JSONRPCError('unknown user %s' % username) RepoModel().revoke_user_permission(repo=repo_name, user=username) Session.commit() return dict( msg='Revoked perm for user: %s in repo: %s' % ( username, repo_name ) ) except Exception: log.error(traceback.format_exc()) raise JSONRPCError( 'failed to edit permission %(repo)s for %(user)s' % dict( user=username, repo=repo_name ) )
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 test_login_admin_ok_password_migration(self, real_crypto_backend): from rhodecode.lib import auth # create new user, with sha256 password temp_user = '******' user = fixture.create_user(temp_user) user.password = auth._RhodeCodeCryptoSha256().hash_create(b'test123') Session().add(user) Session().commit() self.destroy_users.add(temp_user) response = self.app.post(login_url, { 'username': temp_user, 'password': '******' }) assert response.status == '302 Found' session = get_session_from_response(response) username = session['rhodecode_user'].get('username') assert username == temp_user response = response.follow() response.mustcontain('/%s' % HG_REPO) # new password should be bcrypted, after log-in and transfer user = User.get_by_username(temp_user) assert user.password.startswith('$')
def test_push_on_locked_repo_by_other_user_hg(self, rc_web_server, tmpdir): clone_url = rc_web_server.repo_clone_url(HG_REPO) stdout, stderr = Command('/tmp').execute('hg clone', clone_url, tmpdir.strpath) # lock repo r = Repository.get_by_repo_name(HG_REPO) # let this user actually push ! RepoModel().grant_user_permission(repo=r, user=TEST_USER_REGULAR_LOGIN, perm='repository.write') Session().commit() Repository.lock(r, User.get_by_username(TEST_USER_ADMIN_LOGIN).user_id) # push fails repo is locked by other user ! push_url = rc_web_server.repo_clone_url(HG_REPO, user=TEST_USER_REGULAR_LOGIN, passwd=TEST_USER_REGULAR_PASS) stdout, stderr = _add_files_and_push('hg', tmpdir.strpath, clone_url=push_url) msg = ( """abort: HTTP Error 400: Repository `%s` locked by user `%s`""" % (HG_REPO, TEST_USER_ADMIN_LOGIN)) assert msg in stderr
def update(self, user_group, form_data): user_group = self._get_user_group(user_group) if 'users_group_name' in form_data: user_group.users_group_name = form_data['users_group_name'] if 'users_group_active' in form_data: user_group.users_group_active = form_data['users_group_active'] if 'user_group_description' in form_data: user_group.user_group_description = form_data[ 'user_group_description'] # handle owner change if 'user' in form_data: owner = form_data['user'] if isinstance(owner, basestring): owner = User.get_by_username(form_data['user']) if not isinstance(owner, User): raise ValueError('invalid owner for user group: %s' % form_data['user']) user_group.user = owner if 'users_group_members' in form_data: members_id_list = self._clean_members_data( form_data['users_group_members']) self._update_members_from_user_ids(user_group, members_id_list) self.sa.add(user_group)
def edit(self, id, format='html'): """GET /permissions/id/edit: Form to edit an existing item""" #url('edit_permission', id=ID) #this form can only edit default user permissions if id == 'default': default_user = User.get_by_username('default') defaults = {'_method': 'put', 'anonymous': default_user.active} for p in default_user.user_perms: if p.permission.permission_name.startswith('repository.'): defaults['default_perm'] = p.permission.permission_name if p.permission.permission_name.startswith('hg.register.'): defaults['default_register'] = p.permission.permission_name if p.permission.permission_name.startswith('hg.create.'): defaults['default_create'] = p.permission.permission_name if p.permission.permission_name.startswith('hg.fork.'): defaults['default_fork'] = p.permission.permission_name return htmlfill.render( render('admin/permissions/permissions.html'), defaults=defaults, encoding="UTF-8", force_defaults=True, ) else: return redirect(url('admin_home'))
def remove_user_from_users_group(self, apiuser, group_name, username): """ Remove user from a group :param apiuser :param group_name :param username """ try: users_group = UsersGroup.get_by_group_name(group_name) if not users_group: raise JSONRPCError('unknown users group %s' % group_name) user = User.get_by_username(username) if user is None: raise JSONRPCError('unknown user %s' % username) success = UsersGroupModel().remove_user_from_group(users_group, user) msg = 'removed member %s from users group %s' % (username, group_name) msg = msg if success else "User wasn't in group" Session.commit() return dict(success=success, msg=msg) except Exception: log.error(traceback.format_exc()) raise JSONRPCError('failed to remove user from group')
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 grant_user_permission(self, apiuser, repo_name, username, perm): """ Grant permission for user on given repository, or update existing one if found :param repo_name: :param username: :param perm: """ try: repo = Repository.get_by_repo_name(repo_name) if repo is None: raise JSONRPCError('unknown repository %s' % repo) user = User.get_by_username(username) if user is None: raise JSONRPCError('unknown user %s' % username) RepoModel().grant_user_permission(repo=repo, user=user, perm=perm) Session.commit() return dict( msg='Granted perm: %s for user: %s in repo: %s' % ( perm, username, repo_name ) ) except Exception: log.error(traceback.format_exc()) raise JSONRPCError( 'failed to edit permission %(repo)s for %(user)s' % dict( user=username, repo=repo_name ) )
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 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 register(self): c.auto_active = False for perm in User.get_by_username('default').user_perms: if perm.permission.permission_name == 'hg.register.auto_activate': c.auto_active = True break if request.POST: register_form = RegisterForm()() try: form_result = register_form.to_python(dict(request.POST)) form_result['active'] = c.auto_active UserModel().create_registration(form_result) h.flash(_('You have successfully registered into rhodecode'), category='success') Session().commit() return redirect(url('login_home')) except formencode.Invalid, errors: return htmlfill.render( render('/register.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8")
def edit(self, id, format='html'): """GET /permissions/id/edit: Form to edit an existing item""" #url('edit_permission', id=ID) c.perms_choices = self.perms_choices c.register_choices = self.register_choices c.create_choices = self.create_choices if id == 'default': default_user = User.get_by_username('default') defaults = {'_method': 'put', 'anonymous': default_user.active} for p in default_user.user_perms: if p.permission.permission_name.startswith('repository.'): defaults['default_perm'] = p.permission.permission_name if p.permission.permission_name.startswith('hg.register.'): defaults['default_register'] = p.permission.permission_name if p.permission.permission_name.startswith('hg.create.'): defaults['default_create'] = p.permission.permission_name return htmlfill.render( render('admin/permissions/permissions.html'), defaults=defaults, encoding="UTF-8", force_defaults=True, ) else: return redirect(url('admin_home'))
def test_subgrouping_with_repo(self): g1 = _make_group('g1') g2 = _make_group('g2') # create new repo form_data = _get_repo_create_params(repo_name='john') 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 test_my_account_my_emails_add_remove(self): self.log_user() response = self.app.get(url('my_account_emails')) response.mustcontain('No additional emails specified') response = self.app.post(url('my_account_emails'), { 'new_email': '*****@*****.**', 'csrf_token': self.csrf_token }) response = self.app.get(url('my_account_emails')) from rhodecode.model.db import UserEmailMap email_id = UserEmailMap.query().filter( UserEmailMap.user == User.get_by_username(TEST_USER_ADMIN_LOGIN) ).filter(UserEmailMap.email == '*****@*****.**').one().email_id response.mustcontain('*****@*****.**') response.mustcontain('<input id="del_email_id" name="del_email_id" ' 'type="hidden" value="%s" />' % email_id) response = self.app.post( url('my_account_emails'), { 'del_email_id': email_id, '_method': 'delete', 'csrf_token': self.csrf_token }) assert_session_flash(response, 'Removed email address from user account') response = self.app.get(url('my_account_emails')) response.mustcontain('No additional emails specified')
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 update(self, repo_group, form_data): try: repo_group = self._get_repo_group(repo_group) old_path = repo_group.full_path # change properties if 'group_description' in form_data: repo_group.group_description = form_data['group_description'] if 'enable_locking' in form_data: repo_group.enable_locking = form_data['enable_locking'] if 'group_parent_id' in form_data: parent_group = ( self._get_repo_group(form_data['group_parent_id'])) repo_group.group_parent_id = ( parent_group.group_id if parent_group else None) repo_group.parent_group = parent_group # mikhail: to update the full_path, we have to explicitly # update group_name group_name = form_data.get('group_name', repo_group.name) repo_group.group_name = repo_group.get_new_name(group_name) new_path = repo_group.full_path if 'user' in form_data: repo_group.user = User.get_by_username(form_data['user']) self.sa.add(repo_group) # iterate over all members of this groups and do fixes # set locking if given # if obj is a repoGroup also fix the name of the group according # to the parent # if obj is a Repo fix it's name # this can be potentially heavy operation for obj in repo_group.recursive_groups_and_repos(): # set the value from it's parent obj.enable_locking = repo_group.enable_locking if isinstance(obj, RepoGroup): new_name = obj.get_new_name(obj.name) log.debug('Fixing group %s to new name %s', obj.group_name, new_name) obj.group_name = new_name elif isinstance(obj, Repository): # we need to get all repositories from this new group and # rename them accordingly to new group path new_name = obj.get_new_name(obj.just_name) log.debug('Fixing repo %s to new name %s', obj.repo_name, new_name) obj.repo_name = new_name self.sa.add(obj) self._rename_group(old_path, new_path) return repo_group except Exception: log.error(traceback.format_exc()) raise
def register(self): c.auto_active = False for perm in User.get_by_username('default').user_perms: if perm.permission.permission_name == 'hg.register.auto_activate': c.auto_active = True break if request.POST: register_form = RegisterForm()() try: form_result = register_form.to_python(dict(request.POST)) form_result['active'] = c.auto_active UserModel().create_registration(form_result) h.flash(_('You have successfully registered into rhodecode'), category='success') Session.commit() return redirect(url('login_home')) except formencode.Invalid, errors: return htmlfill.render(render('/register.html'), defaults=errors.value, errors=errors.error_dict or {}, prefix_error=False, encoding="UTF-8")
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 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 update(self, repo, **kwargs): try: cur_repo = self._get_repo(repo) source_repo_name = cur_repo.repo_name if 'user' in kwargs: cur_repo.user = User.get_by_username(kwargs['user']) if 'repo_group' in kwargs: cur_repo.group = RepoGroup.get(kwargs['repo_group']) log.debug('Updating repo %s with params:%s', cur_repo, kwargs) update_keys = [(1, 'repo_enable_downloads'), (1, 'repo_description'), (1, 'repo_enable_locking'), (1, 'repo_landing_rev'), (1, 'repo_private'), (1, 'repo_enable_statistics'), (0, 'clone_uri'), (0, 'fork_id')] for strip, k in update_keys: if k in kwargs: val = kwargs[k] if strip: k = remove_prefix(k, 'repo_') if k == 'clone_uri': from rhodecode.model.validators import Missing _change = kwargs.get('clone_uri_change') if _change in [Missing, 'OLD']: # we don't change the value, so use original one val = cur_repo.clone_uri setattr(cur_repo, k, val) new_name = cur_repo.get_new_name(kwargs['repo_name']) cur_repo.repo_name = new_name # if private flag is set, reset default permission to NONE if kwargs.get('repo_private'): EMPTY_PERM = 'repository.none' RepoModel().grant_user_permission(repo=cur_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM) # handle extra fields for field in filter(lambda k: k.startswith(RepositoryField.PREFIX), kwargs): k = RepositoryField.un_prefix_key(field) ex_field = RepositoryField.get_by_key_name(key=k, repo=cur_repo) if ex_field: ex_field.field_value = kwargs[field] self.sa.add(ex_field) self.sa.add(cur_repo) if source_repo_name != new_name: # rename repository self._rename_filesystem_repo(old=source_repo_name, new=new_name) return cur_repo except Exception: log.error(traceback.format_exc()) raise
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_subgrouping_with_repo(self): g1 = self.__make_group('g1') g2 = self.__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, os.path.join('g2', 'g1', r.just_name))
def test_update(self, name, expected): self.log_user() uname = 'testme' usr = UserModel().create_or_update(username=uname, password='******', email='*****@*****.**') 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 add_user_to_users_group(self, apiuser, group_name, user_name): """" Add a user to a group :param apiuser :param group_name :param user_name """ try: users_group = UsersGroup.get_by_group_name(group_name) if not users_group: raise JSONRPCError('unknown users group %s' % group_name) try: user = User.get_by_username(user_name) except NoResultFound: raise JSONRPCError('unknown user %s' % user_name) ugm = UsersGroupModel().add_user_to_group(users_group, user) return dict(id=ugm.users_group_member_id, msg='created new users group member') except Exception: log.error(traceback.format_exc()) raise JSONRPCError('failed to create users group member')
def add_user_to_repo(self, apiuser, repo_name, user_name, perm): """ Add permission for a user to a repository :param apiuser :param repo_name :param user_name :param perm """ try: try: repo = Repository.get_by_repo_name(repo_name) except NoResultFound: raise JSONRPCError('unknown repository %s' % repo) try: user = User.get_by_username(user_name) except NoResultFound: raise JSONRPCError('unknown user %s' % user) RepositoryPermissionModel()\ .update_or_delete_user_permission(repo, user, perm) except Exception: log.error(traceback.format_exc()) raise JSONRPCError('failed to edit permission %(repo)s for %(user)s' % dict(user=user_name, repo=repo_name))
def create_user(self, apiuser, username, password, firstname, lastname, email, active=True, admin=False, ldap_dn=None): """ Create new user :param apiuser: :param username: :param password: :param name: :param lastname: :param email: :param active: :param admin: :param ldap_dn: """ if User.get_by_username(username): raise JSONRPCError("user %s already exist" % username) try: form_data = dict(username=username, password=password, active=active, admin=admin, name=firstname, lastname=lastname, email=email, ldap_dn=ldap_dn) UserModel().create_ldap(username, password, ldap_dn, form_data) return dict(msg='created new user %s' % username) except Exception: log.error(traceback.format_exc()) raise JSONRPCError('failed to create user %s' % username)
def test_usergroup_escape(self): user = User.get_by_username('test_admin') user.name = '<img src="/image1" onload="alert(\'Hello, World!\');">' user.lastname = ( '<img src="/image2" onload="alert(\'Hello, World!\');">') Session().add(user) Session().commit() self.log_user() users_group_name = 'samplegroup' data = { 'users_group_name': users_group_name, 'user_group_description': ('<strong onload="alert();">DESC</strong>'), 'active': True, 'csrf_token': self.csrf_token } response = self.app.post(url('users_groups'), data) response = self.app.get(url('users_groups')) response.mustcontain('<strong onload="alert();">' 'DESC</strong>') response.mustcontain('<img src="/image2" onload="' 'alert('Hello, World!');">')
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 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 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 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 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 is_following_user(self, username, user_id, cache=False): u = User.get_by_username(username) f = self.sa.query(UserFollowing)\ .filter(UserFollowing.follows_user == u)\ .filter(UserFollowing.user_id == user_id).scalar() return f is not None
def _create_default_perms(self, new_group): # create default permission repo_group_to_perm = UserRepoGroupToPerm() default_perm = 'group.read' for p in User.get_by_username('default').user_perms: if p.permission.permission_name.startswith('group.'): default_perm = p.permission.permission_name break repo_group_to_perm.permission_id = self.sa.query(Permission)\ .filter(Permission.permission_name == default_perm)\ .one().permission_id repo_group_to_perm.group = new_group repo_group_to_perm.user_id = User.get_by_username('default').user_id self.sa.add(repo_group_to_perm)
def test_clone_after_repo_was_locked_git(self): #lock repo r = Repository.get_by_repo_name(GIT_REPO) Repository.lock(r, User.get_by_username(TEST_USER_ADMIN_LOGIN).user_id) #pull fails since repo is locked clone_url = _construct_url(GIT_REPO) stdout, stderr = Command('/tmp').execute('git clone', clone_url) msg = ("""The requested URL returned error: 423""") assert msg in stderr
def update(self, form_result): perm_user = User.get_by_username(username=form_result['perm_user_name']) u2p = self.sa.query(UserToPerm).filter(UserToPerm.user == perm_user).all() try: def _make_new(usr, perm_name): new = UserToPerm() new.user = usr new.permission = Permission.get_by_key(perm_name) return new # clear current entries, to make this function idempotent # it will fix even if we define more permissions or permissions # are somehow missing for p in u2p: self.sa.delete(p) #create fresh set of permissions for def_perm_key in ['default_repo_perm', 'default_group_perm', 'default_register', 'default_create', 'default_fork']: p = _make_new(perm_user, form_result[def_perm_key]) self.sa.add(p) #stage 2 update all default permissions for repos if checked if form_result['overwrite_default_repo'] == True: _def_name = form_result['default_repo_perm'].split('repository.')[-1] _def = Permission.get_by_key('repository.' + _def_name) # repos 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) if form_result['overwrite_default_group'] == True: _def_name = form_result['default_group_perm'].split('group.')[-1] # groups _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) # stage 3 set anonymous access if perm_user.username == 'default': perm_user.active = str2bool(form_result['anonymous']) self.sa.add(perm_user) self.sa.commit() except (DatabaseError,): log.error(traceback.format_exc()) self.sa.rollback() raise
def test_clone_after_repo_was_locked_hg(self): #lock repo r = Repository.get_by_repo_name(HG_REPO) Repository.lock(r, User.get_by_username(TEST_USER_ADMIN_LOGIN).user_id) #pull fails since repo is locked clone_url = _construct_url(HG_REPO) stdout, stderr = Command('/tmp').execute('hg clone', clone_url) msg = ("""abort: HTTP Error 423: Repository `%s` locked by user `%s`""" % (HG_REPO, TEST_USER_ADMIN_LOGIN)) assert msg in stderr