def create_permissions(self): #module.(access|create|change|delete)_[name] #module.(read|write|owner) perms = [('repository.none', 'Repository no access'), ('repository.read', 'Repository read access'), ('repository.write', 'Repository write access'), ('repository.admin', 'Repository admin access'), ('hg.admin', 'Hg Administrator'), ('hg.create.repository', 'Repository create'), ('hg.create.none', 'Repository creation disabled'), ('hg.register.none', 'Register disabled'), ('hg.register.manual_activate', 'Register new user with ' 'RhodeCode without manual' 'activation'), ('hg.register.auto_activate', 'Register new user with ' 'RhodeCode without auto ' 'activation'), ] for p in perms: new_perm = Permission() new_perm.permission_name = p[0] new_perm.permission_longname = p[1] try: self.sa.add(new_perm) self.sa.commit() except: self.sa.rollback() raise
def update_perm(self, id): """PUT /users_perm/id: Update an existing item""" # url('user_perm', id=ID, method='put') grant_perm = request.POST.get('create_repo_perm', False) user_model = UserModel() if grant_perm: perm = Permission.get_by_key('hg.create.none') user_model.revoke_perm(id, perm) perm = Permission.get_by_key('hg.create.repository') user_model.grant_perm(id, perm) h.flash(_("Granted 'repository create' permission to user"), category='success') Session.commit() else: perm = Permission.get_by_key('hg.create.repository') user_model.revoke_perm(id, perm) perm = Permission.get_by_key('hg.create.none') user_model.grant_perm(id, perm) h.flash(_("Revoked 'repository create' permission to user"), category='success') Session.commit() return redirect(url('edit_user', id=id))
def test_revoke_perm_fork_repo(self): self.log_user() perm_none = Permission.get_by_key("hg.fork.none") perm_fork = Permission.get_by_key("hg.fork.repository") user = UserModel().create_or_update( username="******", password="******", email="dummy", firstname="a", lastname="b" ) Session().commit() uid = user.user_id try: # User should have None permission on creation repository self.assertEqual(UserModel().has_perm(user, perm_none), False) self.assertEqual(UserModel().has_perm(user, perm_fork), False) response = self.app.post(url("user_perm", id=uid), params=dict(_method="put")) perm_none = Permission.get_by_key("hg.create.none") perm_create = Permission.get_by_key("hg.create.repository") # User should have None permission on creation repository self.assertEqual(UserModel().has_perm(uid, perm_none), True) self.assertEqual(UserModel().has_perm(uid, perm_create), False) finally: UserModel().delete(uid) Session().commit()
def create_permissions(self): # module.(access|create|change|delete)_[name] # module.(none|read|write|admin) perms = [ ('repository.none', 'Repository no access'), ('repository.read', 'Repository read access'), ('repository.write', 'Repository write access'), ('repository.admin', 'Repository admin access'), ('group.none', 'Repositories Group no access'), ('group.read', 'Repositories Group read access'), ('group.write', 'Repositories Group write access'), ('group.admin', 'Repositories Group admin access'), ('hg.admin', 'Hg Administrator'), ('hg.create.repository', 'Repository create'), ('hg.create.none', 'Repository creation disabled'), ('hg.register.none', 'Register disabled'), ('hg.register.manual_activate', 'Register new user with RhodeCode ' 'without manual activation'), ('hg.register.auto_activate', 'Register new user with RhodeCode ' 'without auto activation'), ] for p in perms: if not Permission.get_by_key(p[0]): new_perm = Permission() new_perm.permission_name = p[0] new_perm.permission_longname = p[1] self.sa.add(new_perm)
def test_revoke_perm_fork_repo(self): self.log_user() perm_none = Permission.get_by_key('hg.fork.none') perm_fork = Permission.get_by_key('hg.fork.repository') user = UserModel().create_or_update(username='******', password='******', email='dummy', firstname='a', lastname='b') Session().commit() uid = user.user_id try: #User should have None permission on creation repository self.assertEqual(UserModel().has_perm(user, perm_none), False) self.assertEqual(UserModel().has_perm(user, perm_fork), False) response = self.app.post(url('user_perm', id=uid), params=dict(_method='put')) perm_none = Permission.get_by_key('hg.create.none') perm_create = Permission.get_by_key('hg.create.repository') #User should have None permission on creation repository self.assertEqual(UserModel().has_perm(uid, perm_none), True) self.assertEqual(UserModel().has_perm(uid, perm_create), False) finally: UserModel().delete(uid) Session().commit()
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_perm(self, id): """PUT /users_perm/id: Update an existing item""" # url('users_group_perm', id=ID, method='put') grant_perm = request.POST.get('create_repo_perm', False) if grant_perm: perm = Permission.get_by_key('hg.create.none') UsersGroupModel().revoke_perm(id, perm) perm = Permission.get_by_key('hg.create.repository') UsersGroupModel().grant_perm(id, perm) h.flash(_("Granted 'repository create' permission to user"), category='success') Session.commit() else: perm = Permission.get_by_key('hg.create.repository') UsersGroupModel().revoke_perm(id, perm) perm = Permission.get_by_key('hg.create.none') UsersGroupModel().grant_perm(id, perm) h.flash(_("Revoked 'repository create' permission to user"), category='success') Session.commit() return redirect(url('edit_users_group', id=id))
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 create_permissions(self): # module.(access|create|change|delete)_[name] # module.(none|read|write|admin) for p in Permission.PERMS: if not Permission.get_by_key(p[0]): new_perm = Permission() new_perm.permission_name = p[0] new_perm.permission_longname = p[0] self.sa.add(new_perm)
def create_permissions(self): """ Create permissions for whole system """ for p in Permission.PERMS: if not Permission.get_by_key(p[0]): new_perm = Permission() new_perm.permission_name = p[0] new_perm.permission_longname = p[0] #translation err with p[1] self.sa.add(new_perm)
def tearDown(self): perm = Permission.query().all() for p in perm: UserModel().revoke_perm(self.u1, p) UserModel().delete(self.u1) Session().commit()
def update(self, id): """PUT /users/id: 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('update_user', id=ID), # method='put') # url('user', id=ID) user_model = UserModel() c.user = user_model.get(id) _form = UserForm(edit=True, old_data={'user_id': id, 'email': c.user.email})() form_result = {} try: form_result = _form.to_python(dict(request.POST)) user_model.update(id, form_result) h.flash(_('User updated successfully'), category='success') Session.commit() except formencode.Invalid, errors: e = errors.error_dict or {} perm = Permission.get_by_key('hg.create.repository') e.update({'create_repo_perm': user_model.has_perm(id, perm)}) return htmlfill.render( render('admin/users/user_edit.html'), defaults=errors.value, errors=e, prefix_error=False, encoding="UTF-8")
def tearDown(self): perm = Permission.query().all() for p in perm: UserModel().revoke_perm(self.u1, p) UserModel().delete(self.u1) Session.commit()
def update(self, id): """PUT /users/id: 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('update_user', id=ID), # method='put') # url('user', id=ID) user_model = UserModel() c.user = user_model.get(id) _form = UserForm(edit=True, old_data={ 'user_id': id, 'email': c.user.email })() form_result = {} try: form_result = _form.to_python(dict(request.POST)) user_model.update(id, form_result) h.flash(_('User updated successfully'), category='success') Session.commit() except formencode.Invalid, errors: e = errors.error_dict or {} perm = Permission.get_by_key('hg.create.repository') e.update({'create_repo_perm': user_model.has_perm(id, perm)}) return htmlfill.render(render('admin/users/user_edit.html'), defaults=errors.value, errors=e, prefix_error=False, encoding="UTF-8")
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 = self.sa.query(UsersGroup).get(id) if not c.users_group: return redirect(url('users_groups')) 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 self.sa.query(User).all()] defaults = c.users_group.get_dict() perm = Permission.get_by_key('hg.create.repository') defaults.update({ 'create_repo_perm': UsersGroupModel().has_perm(c.users_group, perm) }) return htmlfill.render( render('admin/users_groups/users_group_edit.html'), defaults=defaults, encoding="UTF-8", force_defaults=False)
def test_enable_repository_read_on_group(self): self.log_user() users_group_name = TEST_USERS_GROUP + 'another2' response = self.app.post(url('users_groups'), {'users_group_name': users_group_name, 'active':True}) response.follow() ug = UsersGroup.get_by_group_name(users_group_name) self.checkSessionFlash(response, 'created users group %s' % users_group_name) response = self.app.put(url('users_group_perm', id=ug.users_group_id), {'create_repo_perm': True}) response.follow() ug = UsersGroup.get_by_group_name(users_group_name) p = Permission.get_by_key('hg.create.repository') # check if user has this perm perms = UsersGroupToPerm.query()\ .filter(UsersGroupToPerm.users_group == ug).all() perms = [[x.__dict__['users_group_id'], x.__dict__['permission_id'],] for x in perms] self.assertEqual( perms, [[ug.users_group_id, p.permission_id]] ) # DELETE ! ug = UsersGroup.get_by_group_name(users_group_name) ugid = ug.users_group_id response = self.app.delete(url('users_group', id=ug.users_group_id)) response = response.follow() gr = self.Session.query(UsersGroup)\ .filter(UsersGroup.users_group_name == users_group_name).scalar() self.assertEqual(gr, None) p = Permission.get_by_key('hg.create.repository') perms = UsersGroupToPerm.query()\ .filter(UsersGroupToPerm.users_group_id == ugid).all() perms = [[x.__dict__['users_group_id'], x.__dict__['permission_id'],] for x in perms] self.assertEqual( perms, [] )
def test_set_default_permissions_after_modification(self, perm, modify_to): PermissionModel().create_default_user_permissions(user=self.u1) self._test_def_user_perm_equal(user=self.u1) old = Permission.get_by_key(perm) new = Permission.get_by_key(modify_to) assert old is not None assert new is not None # now modify permissions p = UserToPerm.query().filter(UserToPerm.user == self.u1).filter( UserToPerm.permission == old).one() p.permission = new Session().add(p) Session().commit() PermissionModel().create_default_user_permissions(user=self.u1) self._test_def_user_perm_equal(user=self.u1)
def test_revoke_perm(test_user): perm = Permission.query().all()[0] UserModel().grant_perm(test_user, perm) Session().commit() assert UserModel().has_perm(test_user, perm) # revoke UserModel().revoke_perm(test_user, perm) Session().commit() assert not UserModel().has_perm(test_user, perm)
def get_perm_or_error(permid): """ Get permission by id or name or return JsonRPCError if not found :param userid: """ perm = Permission.get_by_key(permid) if perm is None: raise JSONRPCError('permission `%s` does not exist' % (permid)) return perm
def test_revoke_perm(self): perm = Permission.query().all()[0] UserModel().grant_perm(self.u1, perm) Session.commit() self.assertEqual(UserModel().has_perm(self.u1, perm), True) #revoke UserModel().revoke_perm(self.u1, perm) Session.commit() self.assertEqual(UserModel().has_perm(self.u1, perm), False)
def cleanup(): if UserModel().get_user(usr.user_id) is None: return perm = Permission.query().all() for p in perm: UserModel().revoke_perm(usr, p) UserModel().delete(usr.user_id) Session().commit()
def test_revoke_perm(self): perm = Permission.query().all()[0] UserModel().grant_perm(self.u1, perm) Session().commit() self.assertEqual(UserModel().has_perm(self.u1, perm), True) #revoke UserModel().revoke_perm(self.u1, perm) Session().commit() self.assertEqual(UserModel().has_perm(self.u1, perm), False)
def test_set_default_permissions_after_modification(self, perm, modify_to): PermissionModel().create_default_permissions(user=self.u1) self._test_def_perm_equal(user=self.u1) old = Permission.get_by_key(perm) new = Permission.get_by_key(modify_to) self.assertNotEqual(old, None) self.assertNotEqual(new, None) #now modify permissions p = UserToPerm.query()\ .filter(UserToPerm.user == self.u1)\ .filter(UserToPerm.permission == old)\ .one() p.permission = new Session().add(p) Session().commit() PermissionModel().create_default_permissions(user=self.u1) self._test_def_perm_equal(user=self.u1)
def test_revoke_perm_create_repo(self): self.log_user() perm_none = Permission.get_by_key('hg.create.none') perm_create = Permission.get_by_key('hg.create.repository') user = User.get_by_username(TEST_USER_REGULAR2_LOGIN) #User should have None permission on creation repository self.assertEqual(UserModel().has_perm(user, perm_none), False) self.assertEqual(UserModel().has_perm(user, perm_create), False) response = self.app.post(url('user_perm', id=user.user_id), params=dict(_method='put')) perm_none = Permission.get_by_key('hg.create.none') perm_create = Permission.get_by_key('hg.create.repository') user = User.get_by_username(TEST_USER_REGULAR2_LOGIN) #User should have None permission on creation repository self.assertEqual(UserModel().has_perm(user, perm_none), True) self.assertEqual(UserModel().has_perm(user, perm_create), False)
def update_user_permission(self, repository, user, permission): permission = Permission.get_by_key(permission) current = self.get_user_permission(repository, user) if current: if not current.permission is permission: current.permission = permission else: p = UserRepoToPerm() p.user = user p.repository = repository p.permission = permission self.sa.add(p)
def update_users_group_permission(self, repository, users_group, permission): permission = Permission.get_by_key(permission) current = self.get_users_group_permission(repository, users_group) if current: if not current.permission is permission: current.permission = permission else: p = UsersGroupRepoToPerm() p.users_group = users_group p.repository = repository p.permission = permission self.sa.add(p) Session.commit()
def _create_default_perms(self, user_group): # create default permission default_perm = "usergroup.read" def_user = User.get_default_user() for p in def_user.user_perms: if p.permission.permission_name.startswith("usergroup."): default_perm = p.permission.permission_name break user_group_to_perm = UserUserGroupToPerm() user_group_to_perm.permission = Permission.get_by_key(default_perm) user_group_to_perm.user_group = user_group user_group_to_perm.user_id = def_user.user_id return user_group_to_perm
def _create_default_perms(self, new_group): # create default permission default_perm = 'group.read' def_user = User.get_default_user() for p in def_user.user_perms: if p.permission.permission_name.startswith('group.'): default_perm = p.permission.permission_name break repo_group_to_perm = UserRepoGroupToPerm() repo_group_to_perm.permission = Permission.get_by_key(default_perm) repo_group_to_perm.group = new_group repo_group_to_perm.user_id = def_user.user_id return repo_group_to_perm
def _create_default_perms(self, user_group): # create default permission default_perm = 'usergroup.read' def_user = User.get_default_user() for p in def_user.user_perms: if p.permission.permission_name.startswith('usergroup.'): default_perm = p.permission.permission_name break user_group_to_perm = UserUserGroupToPerm() user_group_to_perm.permission = Permission.get_by_key(default_perm) user_group_to_perm.user_group = user_group user_group_to_perm.user_id = def_user.user_id return user_group_to_perm
def update(self, id): """PUT /users_groups/id: 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('users_group', id=ID), # method='put') # url('users_group', id=ID) c.users_group = UsersGroup.get(id) 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 self.sa.query(User).all()] available_members = [safe_unicode(x[0]) for x in c.available_members] users_group_form = UsersGroupForm( edit=True, old_data=c.users_group.get_dict(), available_members=available_members)() try: form_result = users_group_form.to_python(request.POST) UsersGroupModel().update(c.users_group, form_result) h.flash(_('updated users group %s') \ % form_result['users_group_name'], category='success') #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa) Session.commit() except formencode.Invalid, errors: e = errors.error_dict or {} perm = Permission.get_by_key('hg.create.repository') e.update( {'create_repo_perm': UsersGroupModel().has_perm(id, perm)}) return htmlfill.render( render('admin/users_groups/users_group_edit.html'), defaults=errors.value, errors=e, prefix_error=False, encoding="UTF-8")
def _create_default_perms(self, repository, private): # create default permission default = 'repository.read' def_user = User.get_default_user() for p in def_user.user_perms: if p.permission.permission_name.startswith('repository.'): default = p.permission.permission_name break default_perm = 'repository.none' if private else default repo_to_perm = UserRepoToPerm() repo_to_perm.permission = Permission.get_by_key(default_perm) repo_to_perm.repository = repository repo_to_perm.user_id = def_user.user_id return repo_to_perm
def update(self, id): """PUT /users_groups/id: 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('users_group', id=ID), # method='put') # url('users_group', id=ID) c.users_group = UsersGroup.get(id) 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 self.sa.query(User).all()] available_members = [safe_unicode(x[0]) for x in c.available_members] users_group_form = UsersGroupForm(edit=True, old_data=c.users_group.get_dict(), available_members=available_members)() try: form_result = users_group_form.to_python(request.POST) UsersGroupModel().update(c.users_group, form_result) h.flash(_('updated users group %s') \ % form_result['users_group_name'], category='success') #action_logger(self.rhodecode_user, 'new_user', '', '', self.sa) Session.commit() except formencode.Invalid, errors: e = errors.error_dict or {} perm = Permission.get_by_key('hg.create.repository') e.update({'create_repo_perm': UsersGroupModel().has_perm(id, perm)}) return htmlfill.render( render('admin/users_groups/users_group_edit.html'), defaults=errors.value, errors=e, prefix_error=False, encoding="UTF-8")
def test_set_private_flag_sets_default_to_none(self): self.log_user() #initially repository perm should be read perm = _get_permission_for_user(user='******', repo=HG_REPO) self.assertTrue(len(perm), 1) self.assertEqual(perm[0].permission.permission_name, 'repository.read') self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, False) response = self.app.put( url('repo', repo_name=HG_REPO), fixture._get_repo_create_params(repo_private=1, repo_name=HG_REPO, user=TEST_USER_ADMIN_LOGIN)) self.checkSessionFlash(response, msg='Repository %s updated successfully' % (HG_REPO)) self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, True) #now the repo default permission should be None perm = _get_permission_for_user(user='******', repo=HG_REPO) self.assertTrue(len(perm), 1) self.assertEqual(perm[0].permission.permission_name, 'repository.none') response = self.app.put( url('repo', repo_name=HG_REPO), fixture._get_repo_create_params(repo_private=False, repo_name=HG_REPO, user=TEST_USER_ADMIN_LOGIN)) self.checkSessionFlash(response, msg='Repository %s updated successfully' % (HG_REPO)) self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, False) #we turn off private now the repo default permission should stay None perm = _get_permission_for_user(user='******', repo=HG_REPO) self.assertTrue(len(perm), 1) self.assertEqual(perm[0].permission.permission_name, 'repository.none') #update this permission back perm[0].permission = Permission.get_by_key('repository.read') Session().add(perm[0]) Session().commit()
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(id) if not c.user: return redirect(url('users')) if c.user.username == 'default': h.flash(_("You can't edit this user"), category='warning') return redirect(url('users')) c.user.permissions = {} c.granted_permissions = UserModel().fill_perms(c.user)\ .permissions['global'] defaults = c.user.get_dict() perm = Permission.get_by_key('hg.create.repository') defaults.update({'create_repo_perm': UserModel().has_perm(id, perm)}) return htmlfill.render(render('admin/users/user_edit.html'), defaults=defaults, encoding="UTF-8", force_defaults=False)
def test_set_private_flag_sets_default_to_none(self): self.log_user() #initially repository perm should be read perm = _get_permission_for_user(user='******', repo=HG_REPO) self.assertTrue(len(perm), 1) self.assertEqual(perm[0].permission.permission_name, 'repository.read') self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, False) response = self.app.put(url('repo', repo_name=HG_REPO), fixture._get_repo_create_params(repo_private=1, repo_name=HG_REPO, user=TEST_USER_ADMIN_LOGIN)) self.checkSessionFlash(response, msg='Repository %s updated successfully' % (HG_REPO)) self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, True) #now the repo default permission should be None perm = _get_permission_for_user(user='******', repo=HG_REPO) self.assertTrue(len(perm), 1) self.assertEqual(perm[0].permission.permission_name, 'repository.none') response = self.app.put(url('repo', repo_name=HG_REPO), fixture._get_repo_create_params(repo_private=False, repo_name=HG_REPO, user=TEST_USER_ADMIN_LOGIN)) self.checkSessionFlash(response, msg='Repository %s updated successfully' % (HG_REPO)) self.assertEqual(Repository.get_by_repo_name(HG_REPO).private, False) #we turn off private now the repo default permission should stay None perm = _get_permission_for_user(user='******', repo=HG_REPO) self.assertTrue(len(perm), 1) self.assertEqual(perm[0].permission.permission_name, 'repository.none') #update this permission back perm[0].permission = Permission.get_by_key('repository.read') Session().add(perm[0]) Session().commit()
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(id) if not c.user: return redirect(url('users')) if c.user.username == 'default': h.flash(_("You can't edit this user"), category='warning') return redirect(url('users')) c.user.permissions = {} c.granted_permissions = UserModel().fill_perms(c.user)\ .permissions['global'] defaults = c.user.get_dict() perm = Permission.get_by_key('hg.create.repository') defaults.update({'create_repo_perm': UserModel().has_perm(id, perm)}) return htmlfill.render( render('admin/users/user_edit.html'), defaults=defaults, encoding="UTF-8", force_defaults=False )
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 = self.sa.query(UsersGroup).get(id) if not c.users_group: return redirect(url('users_groups')) 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 self.sa.query(User).all()] defaults = c.users_group.get_dict() perm = Permission.get_by_key('hg.create.repository') defaults.update({'create_repo_perm': UsersGroupModel().has_perm(c.users_group, perm)}) return htmlfill.render( render('admin/users_groups/users_group_edit.html'), defaults=defaults, encoding="UTF-8", force_defaults=False )
def _make_new_user_group_perm(self, user_group, perm_name): log.debug('Creating new user group permission:%s', perm_name) new = UserGroupToPerm() new.users_group = user_group new.permission = Permission.get_by_key(perm_name) return new
def test_has_perm(self): perm = Permission.query().all() for p in perm: has_p = UserModel().has_perm(self.u1, p) self.assertEqual(False, has_p)
def step_6(self): notify('re-checking permissions') self.klass.create_permissions() notify('installing new UI options') sett4 = RhodeCodeSetting('show_public_icon', True) Session().add(sett4) sett5 = RhodeCodeSetting('show_private_icon', True) Session().add(sett5) sett6 = RhodeCodeSetting('stylify_metatags', False) Session().add(sett6) notify('fixing old PULL hook') _pull = RhodeCodeUi.get_by_key('preoutgoing.pull_logger') if _pull: _pull.ui_key = RhodeCodeUi.HOOK_PULL Session().add(_pull) notify('fixing old PUSH hook') _push = RhodeCodeUi.get_by_key('pretxnchangegroup.push_logger') if _push: _push.ui_key = RhodeCodeUi.HOOK_PUSH Session().add(_push) notify('installing new pre-push hook') hooks4 = RhodeCodeUi() hooks4.ui_section = 'hooks' hooks4.ui_key = RhodeCodeUi.HOOK_PRE_PUSH hooks4.ui_value = 'python:rhodecode.lib.hooks.pre_push' Session().add(hooks4) notify('installing new pre-pull hook') hooks6 = RhodeCodeUi() hooks6.ui_section = 'hooks' hooks6.ui_key = RhodeCodeUi.HOOK_PRE_PULL hooks6.ui_value = 'python:rhodecode.lib.hooks.pre_pull' Session().add(hooks6) notify('installing hgsubversion option') # enable hgsubversion disabled by default hgsubversion = RhodeCodeUi() hgsubversion.ui_section = 'extensions' hgsubversion.ui_key = 'hgsubversion' hgsubversion.ui_value = '' hgsubversion.ui_active = False Session().add(hgsubversion) notify('installing hg git option') # enable hggit disabled by default hggit = RhodeCodeUi() hggit.ui_section = 'extensions' hggit.ui_key = 'hggit' hggit.ui_value = '' hggit.ui_active = False Session().add(hggit) notify('re-check default permissions') default_user = User.get_by_username(User.DEFAULT_USER) perm = Permission.get_by_key('hg.fork.repository') reg_perm = UserToPerm() reg_perm.user = default_user reg_perm.permission = perm Session().add(reg_perm)
def fill_perms(self, user): """ Fills user permission attribute with permissions taken from database works for permissions given for repositories, and for permissions that are granted to groups :param user: user instance to fill his perms """ RK = 'repositories' GK = 'repositories_groups' GLOBAL = 'global' user.permissions[RK] = {} user.permissions[GK] = {} user.permissions[GLOBAL] = set() #====================================================================== # fetch default permissions #====================================================================== default_user = User.get_by_username('default', cache=True) default_user_id = default_user.user_id default_repo_perms = Permission.get_default_perms(default_user_id) default_repo_groups_perms = Permission.get_default_group_perms(default_user_id) if user.is_admin: #================================================================== # admin user have all default rights for repositories # and groups set to admin #================================================================== user.permissions[GLOBAL].add('hg.admin') # repositories for perm in default_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name p = 'repository.admin' user.permissions[RK][r_k] = p # repositories groups for perm in default_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = 'group.admin' user.permissions[GK][rg_k] = p return user #================================================================== # SET DEFAULTS GLOBAL, REPOS, REPOS GROUPS #================================================================== uid = user.user_id # default global permissions taken fron the default user default_global_perms = self.sa.query(UserToPerm)\ .filter(UserToPerm.user_id == default_user_id) for perm in default_global_perms: user.permissions[GLOBAL].add(perm.permission.permission_name) # defaults for repositories, taken from default user for perm in default_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name if perm.Repository.private and not (perm.Repository.user_id == uid): # disable defaults for private repos, p = 'repository.none' elif perm.Repository.user_id == uid: # set admin if owner p = 'repository.admin' else: p = perm.Permission.permission_name user.permissions[RK][r_k] = p # defaults for repositories groups taken from default user permission # on given group for perm in default_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = perm.Permission.permission_name user.permissions[GK][rg_k] = p #====================================================================== # !! OVERRIDE GLOBALS !! with user permissions if any found #====================================================================== # those can be configured from groups or users explicitly _configurable = set(['hg.fork.none', 'hg.fork.repository', 'hg.create.none', 'hg.create.repository']) # USER GROUPS comes first # users group global permissions user_perms_from_users_groups = self.sa.query(UsersGroupToPerm)\ .options(joinedload(UsersGroupToPerm.permission))\ .join((UsersGroupMember, UsersGroupToPerm.users_group_id == UsersGroupMember.users_group_id))\ .filter(UsersGroupMember.user_id == uid)\ .order_by(UsersGroupToPerm.users_group_id)\ .all() #need to group here by groups since user can be in more than one group _grouped = [[x, list(y)] for x, y in itertools.groupby(user_perms_from_users_groups, lambda x:x.users_group)] for gr, perms in _grouped: # since user can be in multiple groups iterate over them and # select the lowest permissions first (more explicit) ##TODO: do this^^ if not gr.inherit_default_permissions: # NEED TO IGNORE all configurable permissions and # replace them with explicitly set user.permissions[GLOBAL] = user.permissions[GLOBAL]\ .difference(_configurable) for perm in perms: user.permissions[GLOBAL].add(perm.permission.permission_name) # user specific global permissions user_perms = self.sa.query(UserToPerm)\ .options(joinedload(UserToPerm.permission))\ .filter(UserToPerm.user_id == uid).all() if not user.inherit_default_permissions: # NEED TO IGNORE all configurable permissions and # replace them with explicitly set user.permissions[GLOBAL] = user.permissions[GLOBAL]\ .difference(_configurable) for perm in user_perms: user.permissions[GLOBAL].add(perm.permission.permission_name) #====================================================================== # !! REPO PERMISSIONS !! #====================================================================== #====================================================================== # check if user is part of user groups for this repository and # fill in (or NOT replace with higher `or 1` permissions #====================================================================== # users group for repositories permissions user_repo_perms_from_users_groups = \ self.sa.query(UsersGroupRepoToPerm, Permission, Repository,)\ .join((Repository, UsersGroupRepoToPerm.repository_id == Repository.repo_id))\ .join((Permission, UsersGroupRepoToPerm.permission_id == Permission.permission_id))\ .join((UsersGroupMember, UsersGroupRepoToPerm.users_group_id == UsersGroupMember.users_group_id))\ .filter(UsersGroupMember.user_id == uid)\ .all() for perm in user_repo_perms_from_users_groups: r_k = perm.UsersGroupRepoToPerm.repository.repo_name p = perm.Permission.permission_name cur_perm = user.permissions[RK][r_k] # overwrite permission only if it's greater than permission # given from other sources - disabled with `or 1` now if PERM_WEIGHTS[p] > PERM_WEIGHTS[cur_perm] or 1: # disable check if perm.Repository.user_id == uid: # set admin if owner p = 'repository.admin' user.permissions[RK][r_k] = p # user explicit permissions for repositories user_repo_perms = \ self.sa.query(UserRepoToPerm, Permission, Repository)\ .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\ .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\ .filter(UserRepoToPerm.user_id == uid)\ .all() for perm in user_repo_perms: # set admin if owner r_k = perm.UserRepoToPerm.repository.repo_name if perm.Repository.user_id == uid: p = 'repository.admin' else: p = perm.Permission.permission_name user.permissions[RK][r_k] = p # REPO GROUP #================================================================== # get access for this user for repos group and override defaults #================================================================== # user explicit permissions for repository user_repo_groups_perms = \ self.sa.query(UserRepoGroupToPerm, Permission, RepoGroup)\ .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\ .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\ .filter(UserRepoGroupToPerm.user_id == uid)\ .all() for perm in user_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = perm.Permission.permission_name cur_perm = user.permissions[GK][rg_k] if PERM_WEIGHTS[p] > PERM_WEIGHTS[cur_perm] or 1: # disable check user.permissions[GK][rg_k] = p # REPO GROUP + USER GROUP #================================================================== # check if user is part of user groups for this repo group and # fill in (or replace with higher) permissions #================================================================== # users group for repositories permissions user_repo_group_perms_from_users_groups = \ self.sa.query(UsersGroupRepoGroupToPerm, Permission, RepoGroup)\ .join((RepoGroup, UsersGroupRepoGroupToPerm.group_id == RepoGroup.group_id))\ .join((Permission, UsersGroupRepoGroupToPerm.permission_id == Permission.permission_id))\ .join((UsersGroupMember, UsersGroupRepoGroupToPerm.users_group_id == UsersGroupMember.users_group_id))\ .filter(UsersGroupMember.user_id == uid)\ .all() for perm in user_repo_group_perms_from_users_groups: g_k = perm.UsersGroupRepoGroupToPerm.group.group_name p = perm.Permission.permission_name cur_perm = user.permissions[GK][g_k] # overwrite permission only if it's greater than permission # given from other sources if PERM_WEIGHTS[p] > PERM_WEIGHTS[cur_perm] or 1: # disable check user.permissions[GK][g_k] = p return user
def _make_perm(perm): new_perm = UserToPerm() new_perm.user = user new_perm.permission = Permission.get_by_key(perm) return new_perm
def test_add_perm(self): perm = Permission.query().all()[0] UserModel().grant_perm(self.u1, perm) Session().commit() self.assertEqual(UserModel().has_perm(self.u1, perm), True)
def fill_perms(self, user, explicit=True, algo="higherwin"): """ Fills user permission attribute with permissions taken from database works for permissions given for repositories, and for permissions that are granted to groups :param user: user instance to fill his perms :param explicit: In case there are permissions both for user and a group that user is part of, explicit flag will defiine if user will explicitly override permissions from group, if it's False it will make decision based on the algo :param algo: algorithm to decide what permission should be choose if it's multiple defined, eg user in two different groups. It also decides if explicit flag is turned off how to specify the permission for case when user is in a group + have defined separate permission """ RK = "repositories" GK = "repositories_groups" UK = "user_groups" GLOBAL = "global" user.permissions[RK] = {} user.permissions[GK] = {} user.permissions[UK] = {} user.permissions[GLOBAL] = set() def _choose_perm(new_perm, cur_perm): new_perm_val = PERM_WEIGHTS[new_perm] cur_perm_val = PERM_WEIGHTS[cur_perm] if algo == "higherwin": if new_perm_val > cur_perm_val: return new_perm return cur_perm elif algo == "lowerwin": if new_perm_val < cur_perm_val: return new_perm return cur_perm # ====================================================================== # fetch default permissions # ====================================================================== default_user = User.get_by_username("default", cache=True) default_user_id = default_user.user_id default_repo_perms = Permission.get_default_perms(default_user_id) default_repo_groups_perms = Permission.get_default_group_perms(default_user_id) default_user_group_perms = Permission.get_default_user_group_perms(default_user_id) if user.is_admin: # ================================================================== # admin user have all default rights for repositories # and groups set to admin # ================================================================== user.permissions[GLOBAL].add("hg.admin") # repositories for perm in default_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name p = "repository.admin" user.permissions[RK][r_k] = p # repository groups for perm in default_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = "group.admin" user.permissions[GK][rg_k] = p # user groups for perm in default_user_group_perms: u_k = perm.UserUserGroupToPerm.user_group.users_group_name p = "usergroup.admin" user.permissions[UK][u_k] = p return user # ================================================================== # SET DEFAULTS GLOBAL, REPOS, REPOSITORY GROUPS # ================================================================== uid = user.user_id # default global permissions taken fron the default user default_global_perms = self.sa.query(UserToPerm).filter(UserToPerm.user_id == default_user_id) for perm in default_global_perms: user.permissions[GLOBAL].add(perm.permission.permission_name) # defaults for repositories, taken from default user for perm in default_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name if perm.Repository.private and not (perm.Repository.user_id == uid): # disable defaults for private repos, p = "repository.none" elif perm.Repository.user_id == uid: # set admin if owner p = "repository.admin" else: p = perm.Permission.permission_name user.permissions[RK][r_k] = p # defaults for repository groups taken from default user permission # on given group for perm in default_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = perm.Permission.permission_name user.permissions[GK][rg_k] = p # defaults for user groups taken from default user permission # on given user group for perm in default_user_group_perms: u_k = perm.UserUserGroupToPerm.user_group.users_group_name p = perm.Permission.permission_name user.permissions[UK][u_k] = p # ====================================================================== # !! OVERRIDE GLOBALS !! with user permissions if any found # ====================================================================== # those can be configured from groups or users explicitly _configurable = set( [ "hg.fork.none", "hg.fork.repository", "hg.create.none", "hg.create.repository", "hg.usergroup.create.false", "hg.usergroup.create.true", ] ) # USER GROUPS comes first # user group global permissions user_perms_from_users_groups = ( self.sa.query(UserGroupToPerm) .options(joinedload(UserGroupToPerm.permission)) .join((UserGroupMember, UserGroupToPerm.users_group_id == UserGroupMember.users_group_id)) .filter(UserGroupMember.user_id == uid) .order_by(UserGroupToPerm.users_group_id) .all() ) # need to group here by groups since user can be in more than one group _grouped = [[x, list(y)] for x, y in itertools.groupby(user_perms_from_users_groups, lambda x: x.users_group)] for gr, perms in _grouped: # since user can be in multiple groups iterate over them and # select the lowest permissions first (more explicit) ##TODO: do this^^ if not gr.inherit_default_permissions: # NEED TO IGNORE all configurable permissions and # replace them with explicitly set user.permissions[GLOBAL] = user.permissions[GLOBAL].difference(_configurable) for perm in perms: user.permissions[GLOBAL].add(perm.permission.permission_name) # user specific global permissions user_perms = ( self.sa.query(UserToPerm).options(joinedload(UserToPerm.permission)).filter(UserToPerm.user_id == uid).all() ) if not user.inherit_default_permissions: # NEED TO IGNORE all configurable permissions and # replace them with explicitly set user.permissions[GLOBAL] = user.permissions[GLOBAL].difference(_configurable) for perm in user_perms: user.permissions[GLOBAL].add(perm.permission.permission_name) ## END GLOBAL PERMISSIONS # ====================================================================== # !! PERMISSIONS FOR REPOSITORIES !! # ====================================================================== # ====================================================================== # check if user is part of user groups for this repository and # fill in his permission from it. _choose_perm decides of which # permission should be selected based on selected method # ====================================================================== # user group for repositories permissions user_repo_perms_from_users_groups = ( self.sa.query(UserGroupRepoToPerm, Permission, Repository) .join((Repository, UserGroupRepoToPerm.repository_id == Repository.repo_id)) .join((Permission, UserGroupRepoToPerm.permission_id == Permission.permission_id)) .join((UserGroupMember, UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id)) .filter(UserGroupMember.user_id == uid) .all() ) multiple_counter = collections.defaultdict(int) for perm in user_repo_perms_from_users_groups: r_k = perm.UserGroupRepoToPerm.repository.repo_name multiple_counter[r_k] += 1 p = perm.Permission.permission_name cur_perm = user.permissions[RK][r_k] if perm.Repository.user_id == uid: # set admin if owner p = "repository.admin" else: if multiple_counter[r_k] > 1: p = _choose_perm(p, cur_perm) user.permissions[RK][r_k] = p # user explicit permissions for repositories, overrides any specified # by the group permission user_repo_perms = Permission.get_default_perms(uid) for perm in user_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name cur_perm = user.permissions[RK][r_k] # set admin if owner if perm.Repository.user_id == uid: p = "repository.admin" else: p = perm.Permission.permission_name if not explicit: p = _choose_perm(p, cur_perm) user.permissions[RK][r_k] = p # ====================================================================== # !! PERMISSIONS FOR REPOSITORY GROUPS !! # ====================================================================== # ====================================================================== # check if user is part of user groups for this repository groups and # fill in his permission from it. _choose_perm decides of which # permission should be selected based on selected method # ====================================================================== # user group for repo groups permissions user_repo_group_perms_from_users_groups = ( self.sa.query(UserGroupRepoGroupToPerm, Permission, RepoGroup) .join((RepoGroup, UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)) .join((Permission, UserGroupRepoGroupToPerm.permission_id == Permission.permission_id)) .join((UserGroupMember, UserGroupRepoGroupToPerm.users_group_id == UserGroupMember.users_group_id)) .filter(UserGroupMember.user_id == uid) .all() ) multiple_counter = collections.defaultdict(int) for perm in user_repo_group_perms_from_users_groups: g_k = perm.UserGroupRepoGroupToPerm.group.group_name multiple_counter[g_k] += 1 p = perm.Permission.permission_name cur_perm = user.permissions[GK][g_k] if multiple_counter[g_k] > 1: p = _choose_perm(p, cur_perm) user.permissions[GK][g_k] = p # user explicit permissions for repository groups user_repo_groups_perms = Permission.get_default_group_perms(uid) for perm in user_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = perm.Permission.permission_name cur_perm = user.permissions[GK][rg_k] if not explicit: p = _choose_perm(p, cur_perm) user.permissions[GK][rg_k] = p # ====================================================================== # !! PERMISSIONS FOR USER GROUPS !! # ====================================================================== # user group for user group permissions user_group_user_groups_perms = ( self.sa.query(UserGroupUserGroupToPerm, Permission, UserGroup) .join((UserGroup, UserGroupUserGroupToPerm.target_user_group_id == UserGroup.users_group_id)) .join((Permission, UserGroupUserGroupToPerm.permission_id == Permission.permission_id)) .join((UserGroupMember, UserGroupUserGroupToPerm.user_group_id == UserGroupMember.users_group_id)) .filter(UserGroupMember.user_id == uid) .all() ) multiple_counter = collections.defaultdict(int) for perm in user_group_user_groups_perms: g_k = perm.UserGroupUserGroupToPerm.target_user_group.users_group_name multiple_counter[g_k] += 1 p = perm.Permission.permission_name cur_perm = user.permissions[UK][g_k] if multiple_counter[g_k] > 1: p = _choose_perm(p, cur_perm) user.permissions[UK][g_k] = p # user explicit permission for user groups user_user_groups_perms = Permission.get_default_user_group_perms(uid) for perm in user_user_groups_perms: u_k = perm.UserUserGroupToPerm.user_group.users_group_name p = perm.Permission.permission_name cur_perm = user.permissions[UK][u_k] if not explicit: p = _choose_perm(p, cur_perm) user.permissions[UK][u_k] = p return user
def _make_new(usr, perm_name): log.debug('Creating new permission:%s' % (perm_name)) new = UserToPerm() new.user = usr new.permission = Permission.get_by_key(perm_name) return new
def fill_perms(self, user, explicit=True, algo='higherwin'): """ Fills user permission attribute with permissions taken from database works for permissions given for repositories, and for permissions that are granted to groups :param user: user instance to fill his perms :param explicit: In case there are permissions both for user and a group that user is part of, explicit flag will defiine if user will explicitly override permissions from group, if it's False it will make decision based on the algo :param algo: algorithm to decide what permission should be choose if it's multiple defined, eg user in two different groups. It also decides if explicit flag is turned off how to specify the permission for case when user is in a group + have defined separate permission """ RK = 'repositories' GK = 'repositories_groups' GLOBAL = 'global' user.permissions[RK] = {} user.permissions[GK] = {} user.permissions[GLOBAL] = set() def _choose_perm(new_perm, cur_perm): new_perm_val = PERM_WEIGHTS[new_perm] cur_perm_val = PERM_WEIGHTS[cur_perm] if algo == 'higherwin': if new_perm_val > cur_perm_val: return new_perm return cur_perm elif algo == 'lowerwin': if new_perm_val < cur_perm_val: return new_perm return cur_perm #====================================================================== # fetch default permissions #====================================================================== default_user = User.get_by_username('default', cache=True) default_user_id = default_user.user_id default_repo_perms = Permission.get_default_perms(default_user_id) default_repo_groups_perms = Permission.get_default_group_perms( default_user_id) if user.is_admin: #================================================================== # admin user have all default rights for repositories # and groups set to admin #================================================================== user.permissions[GLOBAL].add('hg.admin') # repositories for perm in default_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name p = 'repository.admin' user.permissions[RK][r_k] = p # repository groups for perm in default_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = 'group.admin' user.permissions[GK][rg_k] = p return user #================================================================== # SET DEFAULTS GLOBAL, REPOS, REPOSITORY GROUPS #================================================================== uid = user.user_id # default global permissions taken fron the default user default_global_perms = self.sa.query(UserToPerm)\ .filter(UserToPerm.user_id == default_user_id) for perm in default_global_perms: user.permissions[GLOBAL].add(perm.permission.permission_name) # defaults for repositories, taken from default user for perm in default_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name if perm.Repository.private and not (perm.Repository.user_id == uid): # disable defaults for private repos, p = 'repository.none' elif perm.Repository.user_id == uid: # set admin if owner p = 'repository.admin' else: p = perm.Permission.permission_name user.permissions[RK][r_k] = p # defaults for repository groups taken from default user permission # on given group for perm in default_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = perm.Permission.permission_name user.permissions[GK][rg_k] = p #====================================================================== # !! OVERRIDE GLOBALS !! with user permissions if any found #====================================================================== # those can be configured from groups or users explicitly _configurable = set([ 'hg.fork.none', 'hg.fork.repository', 'hg.create.none', 'hg.create.repository' ]) # USER GROUPS comes first # user group global permissions user_perms_from_users_groups = self.sa.query(UserGroupToPerm)\ .options(joinedload(UserGroupToPerm.permission))\ .join((UserGroupMember, UserGroupToPerm.users_group_id == UserGroupMember.users_group_id))\ .filter(UserGroupMember.user_id == uid)\ .order_by(UserGroupToPerm.users_group_id)\ .all() #need to group here by groups since user can be in more than one group _grouped = [[x, list(y)] for x, y in itertools.groupby( user_perms_from_users_groups, lambda x: x.users_group)] for gr, perms in _grouped: # since user can be in multiple groups iterate over them and # select the lowest permissions first (more explicit) ##TODO: do this^^ if not gr.inherit_default_permissions: # NEED TO IGNORE all configurable permissions and # replace them with explicitly set user.permissions[GLOBAL] = user.permissions[GLOBAL]\ .difference(_configurable) for perm in perms: user.permissions[GLOBAL].add(perm.permission.permission_name) # user specific global permissions user_perms = self.sa.query(UserToPerm)\ .options(joinedload(UserToPerm.permission))\ .filter(UserToPerm.user_id == uid).all() if not user.inherit_default_permissions: # NEED TO IGNORE all configurable permissions and # replace them with explicitly set user.permissions[GLOBAL] = user.permissions[GLOBAL]\ .difference(_configurable) for perm in user_perms: user.permissions[GLOBAL].add(perm.permission.permission_name) #====================================================================== # !! PERMISSIONS FOR REPOSITORIES !! #====================================================================== #====================================================================== # check if user is part of user groups for this repository and # fill in his permission from it. _choose_perm decides of which # permission should be selected based on selected method #====================================================================== # user group for repositories permissions user_repo_perms_from_users_groups = \ self.sa.query(UserGroupRepoToPerm, Permission, Repository,)\ .join((Repository, UserGroupRepoToPerm.repository_id == Repository.repo_id))\ .join((Permission, UserGroupRepoToPerm.permission_id == Permission.permission_id))\ .join((UserGroupMember, UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id))\ .filter(UserGroupMember.user_id == uid)\ .all() multiple_counter = collections.defaultdict(int) for perm in user_repo_perms_from_users_groups: r_k = perm.UserGroupRepoToPerm.repository.repo_name multiple_counter[r_k] += 1 p = perm.Permission.permission_name cur_perm = user.permissions[RK][r_k] if perm.Repository.user_id == uid: # set admin if owner p = 'repository.admin' else: if multiple_counter[r_k] > 1: p = _choose_perm(p, cur_perm) user.permissions[RK][r_k] = p # user explicit permissions for repositories, overrides any specified # by the group permission user_repo_perms = \ self.sa.query(UserRepoToPerm, Permission, Repository)\ .join((Repository, UserRepoToPerm.repository_id == Repository.repo_id))\ .join((Permission, UserRepoToPerm.permission_id == Permission.permission_id))\ .filter(UserRepoToPerm.user_id == uid)\ .all() for perm in user_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name cur_perm = user.permissions[RK][r_k] # set admin if owner if perm.Repository.user_id == uid: p = 'repository.admin' else: p = perm.Permission.permission_name if not explicit: p = _choose_perm(p, cur_perm) user.permissions[RK][r_k] = p #====================================================================== # !! PERMISSIONS FOR REPOSITORY GROUPS !! #====================================================================== #====================================================================== # check if user is part of user groups for this repository groups and # fill in his permission from it. _choose_perm decides of which # permission should be selected based on selected method #====================================================================== # user group for repo groups permissions user_repo_group_perms_from_users_groups = \ self.sa.query(UserGroupRepoGroupToPerm, Permission, RepoGroup)\ .join((RepoGroup, UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id))\ .join((Permission, UserGroupRepoGroupToPerm.permission_id == Permission.permission_id))\ .join((UserGroupMember, UserGroupRepoGroupToPerm.users_group_id == UserGroupMember.users_group_id))\ .filter(UserGroupMember.user_id == uid)\ .all() multiple_counter = collections.defaultdict(int) for perm in user_repo_group_perms_from_users_groups: g_k = perm.UserGroupRepoGroupToPerm.group.group_name multiple_counter[g_k] += 1 p = perm.Permission.permission_name cur_perm = user.permissions[GK][g_k] if multiple_counter[g_k] > 1: p = _choose_perm(p, cur_perm) user.permissions[GK][g_k] = p # user explicit permissions for repository groups user_repo_groups_perms = \ self.sa.query(UserRepoGroupToPerm, Permission, RepoGroup)\ .join((RepoGroup, UserRepoGroupToPerm.group_id == RepoGroup.group_id))\ .join((Permission, UserRepoGroupToPerm.permission_id == Permission.permission_id))\ .filter(UserRepoGroupToPerm.user_id == uid)\ .all() for perm in user_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = perm.Permission.permission_name cur_perm = user.permissions[GK][rg_k] if not explicit: p = _choose_perm(p, cur_perm) user.permissions[GK][rg_k] = p return user
def _create_repo(self, repo_name, repo_type, description, owner, private=False, clone_uri=None, repo_group=None, landing_rev='rev:tip', fork_of=None, copy_fork_permissions=False, enable_statistics=False, enable_locking=False, enable_downloads=False, copy_group_permissions=False, state=Repository.STATE_PENDING): """ Create repository inside database with PENDING state, this should be only executed by create() repo. With exception of importing existing repos """ from rhodecode.model.scm import ScmModel owner = self._get_user(owner) fork_of = self._get_repo(fork_of) repo_group = self._get_repo_group(safe_int(repo_group)) try: repo_name = safe_unicode(repo_name) description = safe_unicode(description) # repo name is just a name of repository # while repo_name_full is a full qualified name that is combined # with name and path of group repo_name_full = repo_name repo_name = repo_name.split(Repository.NAME_SEP)[-1] new_repo = Repository() new_repo.repo_state = state new_repo.enable_statistics = False new_repo.repo_name = repo_name_full new_repo.repo_type = repo_type new_repo.user = owner new_repo.group = repo_group new_repo.description = description or repo_name new_repo.private = private new_repo.clone_uri = clone_uri new_repo.landing_rev = landing_rev new_repo.enable_statistics = enable_statistics new_repo.enable_locking = enable_locking new_repo.enable_downloads = enable_downloads if repo_group: new_repo.enable_locking = repo_group.enable_locking if fork_of: parent_repo = fork_of new_repo.fork = parent_repo self.sa.add(new_repo) EMPTY_PERM = 'repository.none' if fork_of and copy_fork_permissions: repo = fork_of user_perms = UserRepoToPerm.query() \ .filter(UserRepoToPerm.repository == repo).all() group_perms = UserGroupRepoToPerm.query() \ .filter(UserGroupRepoToPerm.repository == repo).all() for perm in user_perms: UserRepoToPerm.create(perm.user, new_repo, perm.permission) for perm in group_perms: UserGroupRepoToPerm.create(perm.users_group, new_repo, perm.permission) # in case we copy permissions and also set this repo to private # override the default user permission to make it a private # repo if private: RepoModel(self.sa).grant_user_permission( repo=new_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM) elif repo_group and copy_group_permissions: user_perms = UserRepoGroupToPerm.query() \ .filter(UserRepoGroupToPerm.group == repo_group).all() group_perms = UserGroupRepoGroupToPerm.query() \ .filter(UserGroupRepoGroupToPerm.group == repo_group).all() for perm in user_perms: perm_name = perm.permission.permission_name.replace( 'group.', 'repository.') perm_obj = Permission.get_by_key(perm_name) UserRepoToPerm.create(perm.user, new_repo, perm_obj) for perm in group_perms: perm_name = perm.permission.permission_name.replace( 'group.', 'repository.') perm_obj = Permission.get_by_key(perm_name) UserGroupRepoToPerm.create(perm.users_group, new_repo, perm_obj) if private: RepoModel(self.sa).grant_user_permission( repo=new_repo, user=User.DEFAULT_USER, perm=EMPTY_PERM) else: perm_obj = self._create_default_perms(new_repo, private) self.sa.add(perm_obj) # now automatically start following this repository as owner ScmModel(self.sa).toggle_following_repo(new_repo.repo_id, owner.user_id) # we need to flush here, in order to check if database won't # throw any exceptions, create filesystem dirs at the very end self.sa.flush() return new_repo except Exception: log.error(traceback.format_exc()) raise
def test_enable_repository_read_on_group(self): self.log_user() users_group_name = TEST_USER_GROUP + 'another2' response = self.app.post(url('users_groups'), { 'users_group_name': users_group_name, 'active': True }) response.follow() ug = UserGroup.get_by_group_name(users_group_name) self.checkSessionFlash(response, 'Created user group %s' % users_group_name) ## ENABLE REPO CREATE ON A GROUP response = self.app.put(url('users_group_perm', id=ug.users_group_id), {'create_repo_perm': True}) response.follow() ug = UserGroup.get_by_group_name(users_group_name) p = Permission.get_by_key('hg.create.repository') p2 = Permission.get_by_key('hg.usergroup.create.false') p3 = Permission.get_by_key('hg.fork.none') # check if user has this perms, they should be here since # defaults are on perms = UserGroupToPerm.query()\ .filter(UserGroupToPerm.users_group == ug).all() self.assertEqual( sorted([[ x.users_group_id, x.permission_id, ] for x in perms]), sorted([[ug.users_group_id, p.permission_id], [ug.users_group_id, p2.permission_id], [ug.users_group_id, p3.permission_id]])) ## DISABLE REPO CREATE ON A GROUP response = self.app.put(url('users_group_perm', id=ug.users_group_id), {}) response.follow() ug = UserGroup.get_by_group_name(users_group_name) p = Permission.get_by_key('hg.create.none') p2 = Permission.get_by_key('hg.usergroup.create.false') p3 = Permission.get_by_key('hg.fork.none') # check if user has this perms, they should be here since # defaults are on perms = UserGroupToPerm.query()\ .filter(UserGroupToPerm.users_group == ug).all() self.assertEqual( sorted([[ x.users_group_id, x.permission_id, ] for x in perms]), sorted([[ug.users_group_id, p.permission_id], [ug.users_group_id, p2.permission_id], [ug.users_group_id, p3.permission_id]])) # DELETE ! ug = UserGroup.get_by_group_name(users_group_name) ugid = ug.users_group_id response = self.app.delete(url('users_group', id=ug.users_group_id)) response = response.follow() gr = Session().query(UserGroup)\ .filter(UserGroup.users_group_name == users_group_name).scalar() self.assertEqual(gr, None) p = Permission.get_by_key('hg.create.repository') perms = UserGroupToPerm.query()\ .filter(UserGroupToPerm.users_group_id == ugid).all() perms = [[ x.users_group_id, x.permission_id, ] for x in perms] self.assertEqual(perms, [])