def revoke_perm(self, user, perm): """ Revoke users global permissions :param user: :param perm: """ user = self._get_user(user) perm = self._get_perm(perm) UserToPerm.query().filter( UserToPerm.user == user, UserToPerm.permission == perm, ).delete()
def revoke_perm(self, user, perm): """ Revoke users global permissions :param user: :param perm: """ user = User.guess_instance(user) perm = Permission.guess_instance(perm) UserToPerm.query().filter( UserToPerm.user == user, UserToPerm.permission == perm, ).delete()
def _test_def_perm_equal(self, user, change_factor=0): perms = UserToPerm.query() \ .filter(UserToPerm.user == user) \ .all() self.assertEqual(len(perms), len(Permission.DEFAULT_USER_PERMISSIONS,)+change_factor, msg=perms)
def update_perms(self, id): user = self._get_user_or_raise_if_default(id) try: form = CustomDefaultPermissionsForm()() form_result = form.to_python(request.POST) user_model = UserModel() defs = UserToPerm.query() \ .filter(UserToPerm.user == user) \ .all() for ug in defs: Session().delete(ug) if form_result['create_repo_perm']: user_model.grant_perm(id, 'hg.create.repository') else: user_model.grant_perm(id, 'hg.create.none') if form_result['create_user_group_perm']: user_model.grant_perm(id, 'hg.usergroup.create.true') else: user_model.grant_perm(id, 'hg.usergroup.create.false') if form_result['fork_repo_perm']: user_model.grant_perm(id, 'hg.fork.repository') else: user_model.grant_perm(id, 'hg.fork.none') h.flash(_("Updated permissions"), category='success') Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during permissions saving'), category='error') raise HTTPFound(location=url('edit_user_perms', id=id))
def _test_def_perm_equal(self, user, change_factor=0): perms = UserToPerm.query()\ .filter(UserToPerm.user == user)\ .all() self.assertEqual(len(perms), len(Permission.DEFAULT_USER_PERMISSIONS, ) + change_factor, msg=perms)
def test_set_default_permissions_after_one_is_missing(self): PermissionModel().create_default_permissions(user=self.u1) self._test_def_perm_equal(user=self.u1) #now we delete one, it should be re-created after another call perms = UserToPerm.query() \ .filter(UserToPerm.user == self.u1) \ .all() Session().delete(perms[0]) Session().commit() self._test_def_perm_equal(user=self.u1, change_factor=-1) #create missing one ! PermissionModel().create_default_permissions(user=self.u1) self._test_def_perm_equal(user=self.u1)
def test_set_default_permissions_after_one_is_missing(self): PermissionModel().create_default_permissions(user=self.u1) self._test_def_perm_equal(user=self.u1) #now we delete one, it should be re-created after another call perms = UserToPerm.query()\ .filter(UserToPerm.user == self.u1)\ .all() Session().delete(perms[0]) Session().commit() self._test_def_perm_equal(user=self.u1, change_factor=-1) #create missing one ! PermissionModel().create_default_permissions(user=self.u1) self._test_def_perm_equal(user=self.u1)
def revoke_perm(self, user, perm): """ Revoke users global permissions :param user: :param perm: """ user = self._get_user(user) perm = self._get_perm(perm) obj = UserToPerm.query()\ .filter(UserToPerm.user == user)\ .filter(UserToPerm.permission == perm)\ .scalar() if obj: self.sa.delete(obj)
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) assert old != None assert new != None #now modify permissions p = UserToPerm.query() \ .filter(UserToPerm.user == self.u1) \ .filter(UserToPerm.permission == old) \ .one() p.permission = new Session().commit() PermissionModel().create_default_permissions(user=self.u1) self._test_def_perm_equal(user=self.u1)
def reset_permissions(self, username): """ Resets permissions to default state, useful when old systems had bad permissions, we must clean them up :param username: """ default_user = User.get_by_username(username) if not default_user: return u2p = UserToPerm.query()\ .filter(UserToPerm.user == default_user).all() fixed = False if len(u2p) != len(Permission.DEFAULT_USER_PERMISSIONS): for p in u2p: Session().delete(p) fixed = True self.populate_default_permissions() return fixed
def reset_permissions(self, username): """ Resets permissions to default state, useful when old systems had bad permissions, we must clean them up :param username: """ default_user = User.get_by_username(username) if not default_user: return u2p = UserToPerm.query() \ .filter(UserToPerm.user == default_user).all() fixed = False if len(u2p) != len(Permission.DEFAULT_USER_PERMISSIONS): for p in u2p: Session().delete(p) fixed = True self.populate_default_permissions() return fixed
def grant_perm(self, user, perm): """ Grant user global permissions :param user: :param perm: """ user = User.guess_instance(user) perm = Permission.guess_instance(perm) # if this permission is already granted skip it _perm = UserToPerm.query() \ .filter(UserToPerm.user == user) \ .filter(UserToPerm.permission == perm) \ .scalar() if _perm: return new = UserToPerm() new.user = user new.permission = perm Session().add(new) return new
def grant_perm(self, user, perm): """ Grant user global permissions :param user: :param perm: """ user = self._get_user(user) perm = self._get_perm(perm) # if this permission is already granted skip it _perm = UserToPerm.query()\ .filter(UserToPerm.user == user)\ .filter(UserToPerm.permission == perm)\ .scalar() if _perm: return new = UserToPerm() new.user = user new.permission = perm self.sa.add(new) return new
def update_perms(self, id): """PUT /users_perm/id: Update an existing item""" # url('user_perm', id=ID, method='put') user = self._get_user_or_raise_if_default(id) try: form = CustomDefaultPermissionsForm()() form_result = form.to_python(request.POST) inherit_perms = form_result['inherit_default_permissions'] user.inherit_default_permissions = inherit_perms Session().add(user) user_model = UserModel() defs = UserToPerm.query() \ .filter(UserToPerm.user == user) \ .all() for ug in defs: Session().delete(ug) if form_result['create_repo_perm']: user_model.grant_perm(id, 'hg.create.repository') else: user_model.grant_perm(id, 'hg.create.none') if form_result['create_user_group_perm']: user_model.grant_perm(id, 'hg.usergroup.create.true') else: user_model.grant_perm(id, 'hg.usergroup.create.false') if form_result['fork_repo_perm']: user_model.grant_perm(id, 'hg.fork.repository') else: user_model.grant_perm(id, 'hg.fork.none') h.flash(_("Updated permissions"), category='success') Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during permissions saving'), category='error') raise HTTPFound(location=url('edit_user_perms', id=id))
def create_default_permissions(self, user, force=False): """ Create missing default permissions for user. If force is set, the default permissions for the user are reset, otherwise only missing permissions are created. :param user: """ user = self._get_user(user) def _make_perm(perm): new_perm = UserToPerm() new_perm.user = user new_perm.permission = Permission.get_by_key(perm) return new_perm def _get_group(perm_name): return '.'.join(perm_name.split('.')[:1]) perms = UserToPerm.query().filter(UserToPerm.user == user).all() defined_perms_groups = map(_get_group, (x.permission.permission_name for x in perms)) log.debug('GOT ALREADY DEFINED:%s' % perms) DEFAULT_PERMS = Permission.DEFAULT_USER_PERMISSIONS if force: for perm in perms: self.sa.delete(perm) self.sa.commit() defined_perms_groups = [] # For every default permission that needs to be created, we check if # its group is already defined. If it's not, we create default permission. for perm_name in DEFAULT_PERMS: gr = _get_group(perm_name) if gr not in defined_perms_groups: log.debug('GR:%s not found, creating permission %s' % (gr, perm_name)) new_perm = _make_perm(perm_name) self.sa.add(new_perm)
def update_perms(self, id): """PUT /users_perm/id: Update an existing item""" # url('user_perm', id=ID, method='put') user = User.get_or_404(id) try: form = CustomDefaultPermissionsForm()() form_result = form.to_python(request.POST) inherit_perms = form_result['inherit_default_permissions'] user.inherit_default_permissions = inherit_perms Session().add(user) user_model = UserModel() defs = UserToPerm.query()\ .filter(UserToPerm.user == user)\ .all() for ug in defs: Session().delete(ug) if form_result['create_repo_perm']: user_model.grant_perm(id, 'hg.create.repository') else: user_model.grant_perm(id, 'hg.create.none') if form_result['create_user_group_perm']: user_model.grant_perm(id, 'hg.usergroup.create.true') else: user_model.grant_perm(id, 'hg.usergroup.create.false') if form_result['fork_repo_perm']: user_model.grant_perm(id, 'hg.fork.repository') else: user_model.grant_perm(id, 'hg.fork.none') h.flash(_("Updated permissions"), category='success') Session().commit() except Exception: log.error(traceback.format_exc()) h.flash(_('An error occurred during permissions saving'), category='error') return redirect(url('edit_user_perms', id=id))
def has_perm(self, user, perm): perm = Permission.guess_instance(perm) user = User.guess_instance(user) return UserToPerm.query().filter(UserToPerm.user == user) \ .filter(UserToPerm.permission == perm).scalar() is not None
def update(self, form_result): perm_user = User.get_by_username(username=form_result['perm_user_name']) try: # stage 1 set anonymous access if perm_user.is_default_user: perm_user.active = str2bool(form_result['anonymous']) # stage 2 reset defaults and set them from form data 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 # clear current entries, to make this function idempotent # it will fix even if we define more permissions or permissions # are somehow missing u2p = UserToPerm.query() \ .filter(UserToPerm.user == perm_user) \ .all() for p in u2p: Session().delete(p) #create fresh set of permissions for def_perm_key in ['default_repo_perm', 'default_group_perm', 'default_user_group_perm', 'default_repo_create', 'create_on_write', # special case for create repos on write access to group #'default_repo_group_create', #not implemented yet 'default_user_group_create', 'default_fork', 'default_register', 'default_extern_activate']: p = _make_new(perm_user, form_result[def_perm_key]) Session().add(p) #stage 3 update all default permissions for repos if checked if form_result['overwrite_default_repo']: _def_name = form_result['default_repo_perm'].split('repository.')[-1] _def = Permission.get_by_key('repository.' + _def_name) # repos for r2p in UserRepoToPerm.query() \ .filter(UserRepoToPerm.user == perm_user) \ .all(): #don't reset PRIVATE repositories if not r2p.repository.private: r2p.permission = _def if form_result['overwrite_default_group']: _def_name = form_result['default_group_perm'].split('group.')[-1] # groups _def = Permission.get_by_key('group.' + _def_name) for g2p in UserRepoGroupToPerm.query() \ .filter(UserRepoGroupToPerm.user == perm_user) \ .all(): g2p.permission = _def if form_result['overwrite_default_user_group']: _def_name = form_result['default_user_group_perm'].split('usergroup.')[-1] # groups _def = Permission.get_by_key('usergroup.' + _def_name) for g2p in UserUserGroupToPerm.query() \ .filter(UserUserGroupToPerm.user == perm_user) \ .all(): g2p.permission = _def Session().commit() except (DatabaseError,): log.error(traceback.format_exc()) Session().rollback() raise
def _cached_perms_data(user_id, user_is_admin): RK = 'repositories' GK = 'repositories_groups' UK = 'user_groups' GLOBAL = 'global' PERM_WEIGHTS = Permission.PERM_WEIGHTS permissions = {RK: {}, GK: {}, UK: {}, GLOBAL: set()} def bump_permission(kind, key, new_perm): """Add a new permission for kind and key. Assuming the permissions are comparable, set the new permission if it has higher weight, else drop it and keep the old permission. """ cur_perm = permissions[kind][key] new_perm_val = PERM_WEIGHTS[new_perm] cur_perm_val = PERM_WEIGHTS[cur_perm] if new_perm_val > cur_perm_val: permissions[kind][key] = new_perm #====================================================================== # fetch default permissions #====================================================================== default_repo_perms = Permission.get_default_perms( kallithea.DEFAULT_USER_ID) default_repo_groups_perms = Permission.get_default_group_perms( kallithea.DEFAULT_USER_ID) default_user_group_perms = Permission.get_default_user_group_perms( kallithea.DEFAULT_USER_ID) if user_is_admin: #================================================================== # admin users have all rights; # based on default permissions, just set everything to admin #================================================================== permissions[GLOBAL].add('hg.admin') permissions[GLOBAL].add('hg.create.write_on_repogroup.true') # repositories for perm in default_repo_perms: r_k = perm.repository.repo_name p = 'repository.admin' permissions[RK][r_k] = p # repository groups for perm in default_repo_groups_perms: rg_k = perm.group.group_name p = 'group.admin' permissions[GK][rg_k] = p # user groups for perm in default_user_group_perms: u_k = perm.user_group.users_group_name p = 'usergroup.admin' permissions[UK][u_k] = p return permissions #================================================================== # SET DEFAULTS GLOBAL, REPOS, REPOSITORY GROUPS #================================================================== # default global permissions taken from the default user default_global_perms = UserToPerm.query() \ .filter(UserToPerm.user_id == kallithea.DEFAULT_USER_ID) \ .options(joinedload(UserToPerm.permission)) for perm in default_global_perms: permissions[GLOBAL].add(perm.permission.permission_name) # defaults for repositories, taken from default user for perm in default_repo_perms: r_k = perm.repository.repo_name if perm.repository.owner_id == user_id: p = 'repository.admin' elif perm.repository.private: p = 'repository.none' else: p = perm.permission.permission_name 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.group.group_name p = perm.permission.permission_name 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.user_group.users_group_name p = perm.permission.permission_name permissions[UK][u_k] = p #====================================================================== # !! Augment GLOBALS with user permissions if any found !! #====================================================================== # USER GROUPS comes first # user group global permissions user_perms_from_users_groups = Session().query(UserGroupToPerm) \ .options(joinedload(UserGroupToPerm.permission)) \ .join((UserGroupMember, UserGroupToPerm.users_group_id == UserGroupMember.users_group_id)) \ .filter(UserGroupMember.user_id == user_id) \ .join((UserGroup, UserGroupMember.users_group_id == UserGroup.users_group_id)) \ .filter(UserGroup.users_group_active == True) \ .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: for perm in perms: permissions[GLOBAL].add(perm.permission.permission_name) # user specific global permissions user_perms = Session().query(UserToPerm) \ .options(joinedload(UserToPerm.permission)) \ .filter(UserToPerm.user_id == user_id).all() for perm in user_perms: permissions[GLOBAL].add(perm.permission.permission_name) # for each kind of global permissions, only keep the one with heighest weight kind_max_perm = {} for perm in sorted(permissions[GLOBAL], key=lambda n: PERM_WEIGHTS[n]): kind = perm.rsplit('.', 1)[0] kind_max_perm[kind] = perm permissions[GLOBAL] = set(kind_max_perm.values()) ## END GLOBAL PERMISSIONS #====================================================================== # !! PERMISSIONS FOR REPOSITORIES !! #====================================================================== #====================================================================== # check if user is part of user groups for this repository and # fill in his permission from it. #====================================================================== # user group for repositories permissions user_repo_perms_from_users_groups = \ Session().query(UserGroupRepoToPerm) \ .join((UserGroup, UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id)) \ .filter(UserGroup.users_group_active == True) \ .join((UserGroupMember, UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id)) \ .filter(UserGroupMember.user_id == user_id) \ .options(joinedload(UserGroupRepoToPerm.repository)) \ .options(joinedload(UserGroupRepoToPerm.permission)) \ .all() for perm in user_repo_perms_from_users_groups: bump_permission(RK, perm.repository.repo_name, perm.permission.permission_name) # user permissions for repositories user_repo_perms = Permission.get_default_perms(user_id) for perm in user_repo_perms: bump_permission(RK, perm.repository.repo_name, perm.permission.permission_name) #====================================================================== # !! PERMISSIONS FOR REPOSITORY GROUPS !! #====================================================================== #====================================================================== # check if user is part of user groups for this repository groups and # fill in his permission from it. #====================================================================== # user group for repo groups permissions user_repo_group_perms_from_users_groups = \ Session().query(UserGroupRepoGroupToPerm) \ .join((UserGroup, UserGroupRepoGroupToPerm.users_group_id == UserGroup.users_group_id)) \ .filter(UserGroup.users_group_active == True) \ .join((UserGroupMember, UserGroupRepoGroupToPerm.users_group_id == UserGroupMember.users_group_id)) \ .filter(UserGroupMember.user_id == user_id) \ .options(joinedload(UserGroupRepoGroupToPerm.permission)) \ .all() for perm in user_repo_group_perms_from_users_groups: bump_permission(GK, perm.group.group_name, perm.permission.permission_name) # user explicit permissions for repository groups user_repo_groups_perms = Permission.get_default_group_perms(user_id) for perm in user_repo_groups_perms: bump_permission(GK, perm.group.group_name, perm.permission.permission_name) #====================================================================== # !! PERMISSIONS FOR USER GROUPS !! #====================================================================== # user group for user group permissions user_group_user_groups_perms = \ Session().query(UserGroupUserGroupToPerm) \ .join((UserGroup, UserGroupUserGroupToPerm.target_user_group_id == UserGroup.users_group_id)) \ .join((UserGroupMember, UserGroupUserGroupToPerm.user_group_id == UserGroupMember.users_group_id)) \ .filter(UserGroupMember.user_id == user_id) \ .join((UserGroup, UserGroupMember.users_group_id == UserGroup.users_group_id), aliased=True, from_joinpoint=True) \ .filter(UserGroup.users_group_active == True) \ .options(joinedload(UserGroupUserGroupToPerm.permission)) \ .all() for perm in user_group_user_groups_perms: bump_permission(UK, perm.target_user_group.users_group_name, perm.permission.permission_name) # user explicit permission for user groups user_user_groups_perms = Permission.get_default_user_group_perms(user_id) for perm in user_user_groups_perms: bump_permission(UK, perm.user_group.users_group_name, perm.permission.permission_name) return permissions
def _cached_perms_data(user_id, user_is_admin, user_inherit_default_permissions, explicit, algo): RK = 'repositories' GK = 'repositories_groups' UK = 'user_groups' GLOBAL = 'global' PERM_WEIGHTS = Permission.PERM_WEIGHTS permissions = {RK: {}, GK: {}, UK: {}, 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 users have all rights; # based on default permissions, just set everything to admin #================================================================== permissions[GLOBAL].add('hg.admin') permissions[GLOBAL].add('hg.create.write_on_repogroup.true') # repositories for perm in default_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name p = 'repository.admin' permissions[RK][r_k] = p # repository groups for perm in default_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = 'group.admin' 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' permissions[UK][u_k] = p return permissions #================================================================== # SET DEFAULTS GLOBAL, REPOS, REPOSITORY GROUPS #================================================================== # default global permissions taken from the default user default_global_perms = UserToPerm.query() \ .filter(UserToPerm.user_id == default_user_id) \ .options(joinedload(UserToPerm.permission)) for perm in default_global_perms: 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.owner_id == user_id): # disable defaults for private repos, p = 'repository.none' elif perm.Repository.owner_id == user_id: # set admin if owner p = 'repository.admin' else: p = perm.Permission.permission_name 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 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 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 = Session().query(UserGroupToPerm) \ .options(joinedload(UserGroupToPerm.permission)) \ .join((UserGroupMember, UserGroupToPerm.users_group_id == UserGroupMember.users_group_id)) \ .filter(UserGroupMember.user_id == user_id) \ .join((UserGroup, UserGroupMember.users_group_id == UserGroup.users_group_id)) \ .filter(UserGroup.users_group_active == True) \ .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 permissions[GLOBAL] = permissions[GLOBAL] \ .difference(_configurable) for perm in perms: permissions[GLOBAL].add(perm.permission.permission_name) # user specific global permissions user_perms = Session().query(UserToPerm) \ .options(joinedload(UserToPerm.permission)) \ .filter(UserToPerm.user_id == user_id).all() if not user_inherit_default_permissions: # NEED TO IGNORE all configurable permissions and # replace them with explicitly set permissions[GLOBAL] = permissions[GLOBAL] \ .difference(_configurable) for perm in user_perms: 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 = \ Session().query(UserGroupRepoToPerm, Permission, Repository,) \ .join((Repository, UserGroupRepoToPerm.repository_id == Repository.repo_id)) \ .join((Permission, UserGroupRepoToPerm.permission_id == Permission.permission_id)) \ .join((UserGroup, UserGroupRepoToPerm.users_group_id == UserGroup.users_group_id)) \ .filter(UserGroup.users_group_active == True) \ .join((UserGroupMember, UserGroupRepoToPerm.users_group_id == UserGroupMember.users_group_id)) \ .filter(UserGroupMember.user_id == user_id) \ .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 = permissions[RK][r_k] if perm.Repository.owner_id == user_id: # set admin if owner p = 'repository.admin' else: if multiple_counter[r_k] > 1: p = _choose_perm(p, cur_perm) permissions[RK][r_k] = p # user explicit permissions for repositories, overrides any specified # by the group permission user_repo_perms = Permission.get_default_perms(user_id) for perm in user_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name cur_perm = permissions[RK][r_k] # set admin if owner if perm.Repository.owner_id == user_id: p = 'repository.admin' else: p = perm.Permission.permission_name if not explicit: p = _choose_perm(p, cur_perm) 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 = \ Session().query(UserGroupRepoGroupToPerm, Permission, RepoGroup) \ .join((RepoGroup, UserGroupRepoGroupToPerm.group_id == RepoGroup.group_id)) \ .join((Permission, UserGroupRepoGroupToPerm.permission_id == Permission.permission_id)) \ .join((UserGroup, UserGroupRepoGroupToPerm.users_group_id == UserGroup.users_group_id)) \ .filter(UserGroup.users_group_active == True) \ .join((UserGroupMember, UserGroupRepoGroupToPerm.users_group_id == UserGroupMember.users_group_id)) \ .filter(UserGroupMember.user_id == user_id) \ .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 = permissions[GK][g_k] if multiple_counter[g_k] > 1: p = _choose_perm(p, cur_perm) permissions[GK][g_k] = p # user explicit permissions for repository groups user_repo_groups_perms = Permission.get_default_group_perms(user_id) for perm in user_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = perm.Permission.permission_name cur_perm = permissions[GK][rg_k] if not explicit: p = _choose_perm(p, cur_perm) permissions[GK][rg_k] = p #====================================================================== # !! PERMISSIONS FOR USER GROUPS !! #====================================================================== # user group for user group permissions user_group_user_groups_perms = \ Session().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 == user_id) \ .join((UserGroup, UserGroupMember.users_group_id == UserGroup.users_group_id), aliased=True, from_joinpoint=True) \ .filter(UserGroup.users_group_active == True) \ .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 = permissions[UK][g_k] if multiple_counter[g_k] > 1: p = _choose_perm(p, cur_perm) permissions[UK][g_k] = p #user explicit permission for user groups user_user_groups_perms = Permission.get_default_user_group_perms(user_id) for perm in user_user_groups_perms: u_k = perm.UserUserGroupToPerm.user_group.users_group_name p = perm.Permission.permission_name cur_perm = permissions[UK][u_k] if not explicit: p = _choose_perm(p, cur_perm) permissions[UK][u_k] = p return permissions
def update(self, form_result): perm_user = User.get_by_username( username=form_result['perm_user_name']) try: # stage 1 set anonymous access if perm_user.is_default_user: perm_user.active = str2bool(form_result['anonymous']) # stage 2 reset defaults and set them from form data 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 # clear current entries, to make this function idempotent # it will fix even if we define more permissions or permissions # are somehow missing u2p = UserToPerm.query() \ .filter(UserToPerm.user == perm_user) \ .all() for p in u2p: Session().delete(p) # create fresh set of permissions for def_perm_key in [ 'default_repo_perm', 'default_group_perm', 'default_user_group_perm', 'default_repo_create', 'create_on_write', # special case for create repos on write access to group #'default_repo_group_create', # not implemented yet 'default_user_group_create', 'default_fork', 'default_register', 'default_extern_activate' ]: p = _make_new(perm_user, form_result[def_perm_key]) Session().add(p) # stage 3 update all default permissions for repos if checked if form_result['overwrite_default_repo']: _def_name = form_result['default_repo_perm'].split( 'repository.')[-1] _def = Permission.get_by_key('repository.' + _def_name) # repos for r2p in UserRepoToPerm.query() \ .filter(UserRepoToPerm.user == perm_user) \ .all(): # don't reset PRIVATE repositories if not r2p.repository.private: r2p.permission = _def if form_result['overwrite_default_group']: _def_name = form_result['default_group_perm'].split( 'group.')[-1] # groups _def = Permission.get_by_key('group.' + _def_name) for g2p in UserRepoGroupToPerm.query() \ .filter(UserRepoGroupToPerm.user == perm_user) \ .all(): g2p.permission = _def if form_result['overwrite_default_user_group']: _def_name = form_result['default_user_group_perm'].split( 'usergroup.')[-1] # groups _def = Permission.get_by_key('usergroup.' + _def_name) for g2p in UserUserGroupToPerm.query() \ .filter(UserUserGroupToPerm.user == perm_user) \ .all(): g2p.permission = _def Session().commit() except (DatabaseError, ): log.error(traceback.format_exc()) Session().rollback() raise
def _cached_perms_data(user_id, user_is_admin, user_inherit_default_permissions, explicit, algo): RK = 'repositories' GK = 'repositories_groups' UK = 'user_groups' GLOBAL = 'global' PERM_WEIGHTS = Permission.PERM_WEIGHTS permissions = {RK: {}, GK: {}, UK: {}, 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 #================================================================== permissions[GLOBAL].add('hg.admin') permissions[GLOBAL].add('hg.create.write_on_repogroup.true') # repositories for perm in default_repo_perms: r_k = perm.UserRepoToPerm.repository.repo_name p = 'repository.admin' permissions[RK][r_k] = p # repository groups for perm in default_repo_groups_perms: rg_k = perm.UserRepoGroupToPerm.group.group_name p = 'group.admin' 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' permissions[UK][u_k] = p return permissions #================================================================== # SET DEFAULTS GLOBAL, REPOS, REPOSITORY GROUPS #================================================================== uid = user_id # default global permissions taken from the default user default_global_perms = UserToPerm.query()\ .filter(UserToPerm.user_id == default_user_id)\ .options(joinedload(UserToPerm.permission)) for perm in default_global_perms: 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 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 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 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 = Session().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 permissions[GLOBAL] = permissions[GLOBAL]\ .difference(_configurable) for perm in perms: permissions[GLOBAL].add(perm.permission.permission_name) # user specific global permissions user_perms = Session().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 permissions[GLOBAL] = permissions[GLOBAL]\ .difference(_configurable) for perm in user_perms: 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 = \ Session().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 = 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) 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 = 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) 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 = \ Session().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 = permissions[GK][g_k] if multiple_counter[g_k] > 1: p = _choose_perm(p, cur_perm) 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 = permissions[GK][rg_k] if not explicit: p = _choose_perm(p, cur_perm) permissions[GK][rg_k] = p #====================================================================== # !! PERMISSIONS FOR USER GROUPS !! #====================================================================== # user group for user group permissions user_group_user_groups_perms = \ Session().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 = permissions[UK][g_k] if multiple_counter[g_k] > 1: p = _choose_perm(p, cur_perm) 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 = permissions[UK][u_k] if not explicit: p = _choose_perm(p, cur_perm) permissions[UK][u_k] = p return permissions
def has_perm(self, user, perm): perm = self._get_perm(perm) user = self._get_user(user) return UserToPerm.query().filter(UserToPerm.user == user)\ .filter(UserToPerm.permission == perm).scalar() is not None