def test_assign_multiple_roles(self): user = self.user assign_role(user, ShoRole1) assign_role(user, ShoRole2) self.assertListEqual([ShoRole1, ShoRole2], get_user_roles(user))
def site_meta_processor(request): user_roles = False if request.user.is_authenticated: user_roles = [role.title for role in get_user_roles(request.user)] data = { 'meta': { "debug": settings.DEBUG, "application_version": settings.APPLICATION_VERSION }, 'user_roles': user_roles, 'constants': { 'permissions': p }, 'is_user_switched': request.session.get("%s_is_switched" % settings.LOGIN_AS_SESSION_FLAG, 0) } options = getOptions() for key in options: data['meta'][key] = options[key] return data
def assign_user_role(instance): role = get_user_roles(intance) if role: if role != instance.role: remove_role(intance, role) assign_role(instance, instance.role)
def get_sidebar(self, user): if self.sidebar_section is None: raise ImproperlyConfigured( "You must specify 'sidebar_section' or override 'get_sidebar'." ) if self.sidebar_item is None: raise ImproperlyConfigured( "You must specify 'sidebar_item' or override 'get_sidebar'.") filtered_sidebar = OrderedDict() if user.is_anonymous: return filtered_sidebar sidebar = Sidebar().set_sidebar_item_active(self.sidebar_section, self.sidebar_item) user_roles = set([role.get_name() for role in get_user_roles(user)]) for type in sidebar: filtered_sidebar[type] = OrderedDict() for item in sidebar[type]: roles = set(sidebar[type][item]['roles']) if (user_roles & roles): filtered_sidebar[type][item] = sidebar[type][item] return filtered_sidebar
def test_get_user_roles_multiple_roles(self): user = self.user ShoRole1.assign_role_to_user(user) ShoRole3.assign_role_to_user(user) self.assertListEqual([ShoRole3, ShoRole1], get_user_roles(user))
def jwt_response_payload_handler(token, user=None, request=None): roles = [] permissions = [] if (user): roles = get_user_roles(user) user_roles = [role.get_name() for role in roles] return {'token': token, 'roles': user_roles, 'user_id': user.id}
def get_initial(self): # Get requested role. This will break when dealing with a # registered user that has multiple roles assigned, before # activation, as a result of admin intervention. user_roles = get_user_roles(self.object.user) role = user_roles[0].role_name if user_roles else '' return dict(role=role)
def get_role(request): user = request.user result = {'user': UserSerializer(user).data} if user.is_superuser: result['role'] = 'admin' return HttpResponse(json.dumps(result), content_type='application/json') roles = get_user_roles(user) permissions = [] for role in roles: for p, granted in role.available_permissions.items(): if granted: permissions.append(p) result['permissions'] = permissions roles = [] if has_role(user, 'purchasing_agent'): roles.append('purchasing_agent') if has_role(user, 'finance'): roles.append('finance') if has_role(user, 'godown_manager'): roles.append('godown_manager') if has_role(user, 'operator'): roles.append('operator') result['role'] = roles[0] return HttpResponse(json.dumps(result), content_type='application/json')
def test_remove_role_from_user_with_multiple_roles(self): """Ensure that remove_role() only removes the role specified, not all of the user's roles.""" assign_role(self.user, self.Doctor) assign_role(self.user, self.Surgeon) assign_role(self.user, self.Anesthesiologist) remove_role(self.user, self.Doctor) self.assertListEqual([self.Anesthesiologist, self.Surgeon], get_user_roles(self.user))
def test_ensure_user_roles_are_in_order(self): user = self.user assign_role(user, ShoRole2) assign_role(user, ShoRole4) assign_role(user, ShoRole1) assign_role(user, ShoRole3) self.assertListEqual([ShoRole3, ShoRole1, ShoRole2, ShoRole4], get_user_roles(user))
def get_name_role(request): user = request.user name = user.name try: role = get_user_roles(user)[0].get_cls_name() except IndexError: role = '无角色' return name, role
def has_object_permission(checker_name, user, obj): """Check if a user has permission to perform an action on an object.""" if user and user.is_superuser: return True checker = PermissionsManager.retrieve_checker(checker_name) user_roles = get_user_roles(user) return any([checker(user_role, user, obj) for user_role in user_roles])
def test_clear_roles(self): user = self.user assign_role(user, ShoRole1) assign_role(user, ShoRole2) assign_role(user, ShoRole3) clear_roles(user) self.assertListEqual([], get_user_roles(user))
def UserEditView(request, userid=None): form = None user = None passForm = None rolesForm = None if userid == None: user = request.user elif has_permission(request.user, p.EDIT_USERS) or request.user.id == userid: try: user = User.objects.get(id=userid) except ObjectDoesNotExist as e: raise Http404("User Does Not Exist") else: raise PermissionDenied( "You do not have permission to edit/view this user") if has_permission(request.user, p.EDIT_USERS): roles = [] for x in get_user_roles(user): roles.append(x.display_name) rolesForm = RolesForm({'roles': roles}) form = UserForm(user=request.user, instance=user) passForm = PasswordChangeForm(user) if request.method == "POST": if 'user-submit' in request.POST: form = UserForm(user=request.user, data=request.POST or None, files=request.FILES or None, instance=user) if form.is_valid(): form.save() if 'password-change' in request.POST: passForm = PasswordChangeForm(user, request.POST or None) if passForm.is_valid(): passForm.save() update_session_auth_hash(request, user) if 'change-role' in request.POST: rolesForm = RolesForm(request.POST or None) if rolesForm.is_valid(): User().change_user_role(user, rolesForm.cleaned_data['roles']) return render( request, "dashboard/edit-user.html", { 'form': form, 'user_context': user, 'passform': passForm, 'rolesForm': rolesForm })
def test_admin_save_related_syncs_roles(self): user = mommy.make(get_user_model()) grp1 = mommy.make(Group) grp2 = mommy.make(Group, name=AdminRole1.get_name()) user.groups.add(grp1) user.groups.add(grp2) form = self.FormMock(instance=user) self.CustomUserAdminMock().save_related(None, form, None, None) user_roles = get_user_roles(user) self.assertNotIn(grp1.name, (role.get_name() for role in user_roles)) self.assertIn(AdminRole1, user_roles)
def available_perm_names(user): """ Return a list of permissions codenames available to a user, based on that user's roles. i.e., keys for all "True" permissions from available_perm_status(user): Assert: set(available_perm_names(user)) == set(perm for perm,has_perm in available_perm_status(user) if has_perm) Query efficient; especially when prefetch_related('group', 'user_permissions') on user object. No side-effects; permissions are not created in DB as side-effect. """ roles = get_user_roles(user) perm_names = set(p for role in roles for p in role.permission_names_list()) return [p.codename for p in user.user_permissions.all() if p.codename in perm_names] \ if roles else [] # e.g., user == None
def has_object_permission(checker_name, user, obj): """Check if a user has permission to perform an action on an object.""" if user and user.is_superuser: return True checker = PermissionsManager.retrieve_checker(checker_name) user_roles = get_user_roles(user) if not user_roles: user_roles = [None] return any([checker(user_role, user, obj) for user_role in user_roles])
def get_permission(user): try: role_name = get_user_roles(user)[0].get_name() except IndexError: pass else: try: return dict(AddUserForm.USER_TYPE_CHOICES)[role_name] except KeyError: pass return AddUserForm.USER_TYPE_CHOICES[-1][1]
def test_queries_with_prefetch(self): user = self.user assign_role(user, ShoRole1) assign_role(user, ShoRole2) assign_role(user, ShoRole3) fetched_user = get_user_model().objects.prefetch_related('groups').get(pk=self.user.pk) N = 3 with self.assertNumQueries(0): # all data required is cached with fetched_user for i in range(N): user_roles = get_user_roles(fetched_user)
def test_queries_no_prefetch(self): user = self.user assign_role(user, ShoRole1) assign_role(user, ShoRole2) assign_role(user, ShoRole3) fetched_user = get_user_model().objects.get(pk=self.user.pk) N = 3 with self.assertNumQueries(N): # One query (fetch roles) per call for i in range(N): user_roles = get_user_roles(fetched_user)
def test_dont_return_non_role_groups(self): user = self.user assign_role(user, ShoRole1) assign_role(user, ShoRole2) assign_role(user, ShoRole3) assign_role(user, ShoRole4) other_group = mommy.make(Group) user.groups.add(other_group) self.assertNotIn(other_group, get_user_roles(user))
def to_representation(self, instance): result = super().to_representation(instance) roles = get_user_roles(instance.user) roles_json = [] for role in roles: roles_json.append(role.role_name) if len(roles_json): result["roles"] = roles_json else: result["roles"] = [] return result
def has_object_permission(checker_name, user, obj): """Check if a user has permission to perform an action on an object.""" if _check_superpowers(user): return True checker = PermissionsManager.retrieve_checker(checker_name) user_roles = get_user_roles(user) if not user_roles: user_roles = [None] return any([checker(user_role, user, obj) for user_role in user_roles])
def test_queries_with_prefetch(self): user = self.user assign_role(user, ShoRole1) assign_role(user, ShoRole2) assign_role(user, ShoRole3) fetched_user = get_user_model().objects.prefetch_related('groups').get( pk=self.user.pk) N = 3 with self.assertNumQueries( 0): # all data required is cached with fetched_user for i in range(N): user_roles = get_user_roles(fetched_user)
def save(self, notify): user = self.instance.user # remove any existing roles for role in get_user_roles(user): role.remove_role_from_user(user) to_assign = RolesManager.retrieve_role(self.cleaned_data['role']) to_assign.assign_role_to_user(user) user.is_active = True user.save() notify(user, to_assign.get_name())
def available_perm_status(user): """ Get a boolean map of the permissions available to a user based on that user's roles. """ roles = get_user_roles(user) permission_hash = {} for role in roles: permission_names = role.permission_names_list() for permission_name in permission_names: permission_hash[permission_name] = True return permission_hash
def available_perm_status(user): """ Get a boolean map of the permissions available to a user based on that user's roles. """ permission_hash = {} roles = get_user_roles(user) permissions = set(user.user_permissions.all()) | set(Permission.objects.filter(group__user=user)) for role in roles: permission_names = role.permission_names_list() for permission_name in permission_names: permission_hash[permission_name] = get_permission( permission_name) in permissions return permission_hash
def available_perm_status(user): """ Get a boolean map of the permissions available to a user based on that user's roles. """ roles = get_user_roles(user) permission_hash = {} user_permission_names = set( user.user_permissions.values_list("codename", flat=True)) for role in roles: for permission_name in role.permission_names_list(): permission_hash[ permission_name] = permission_name in user_permission_names return permission_hash
def revoke_permission(user, permission_name): """ Revoke a specified permission from a user. Permissions are only revoked if they are in the scope any of the user's roles. If the permission is out of scope, a RolePermissionScopeException is raised. """ roles = get_user_roles(user) for role in roles: if permission_name in role.permission_names_list(): permission = get_permission(permission_name) user.user_permissions.remove(permission) return raise RolePermissionScopeException("This permission isn't in the scope of " "any of this user's roles.")
def grant_permission(user, permission_name): """ Grant a user a specified permission. Permissions are only granted if they are in the scope any of the user's roles. If the permission is out of scope, a RolePermissionScopeException is raised. """ roles = get_user_roles(user) for role in roles: if permission_name in role.permission_names_list(): permission = get_permission(permission_name) user.user_permissions.add(permission) return raise RolePermissionScopeException("This permission isn't in the scope of " "any of this user's roles.")
def has_role(user, roles): """Check if a user has any of the given roles.""" if user and user.is_superuser: return True if not isinstance(roles, list): roles = [roles] normalized_roles = [] for role in roles: if not inspect.isclass(role): role = RolesManager.retrieve_role(role) normalized_roles.append(role) user_roles = get_user_roles(user) return any([role in user_roles for role in normalized_roles])
def handle(self, *args, **options): # Sync auth.Group with current registered roles (leaving existing groups intact!) for role in roles.RolesManager.get_roles(): group, created = role.get_or_create_group() if created: self.stdout.write("Created Group: %s from Role: %s" % (group.name, role.get_name())) # Sync auth.Permission with permissions for this role role.get_default_true_permissions() if options.get('reset_user_permissions', False): # dj1.7 compat # Push any permission changes made to roles and remove any unregistered roles from all auth.Users self.stdout.write("Resetting permissions for ALL Users to defaults defined by roles.") for user in get_user_model().objects.all(): user_roles = roles.get_user_roles(user=user) roles.clear_roles(user=user) for role in user_roles: roles.assign_role(user=user, role=role)
def save_related(self, request, form, formsets, change): user = UserModel.objects.get(pk=form.instance.pk) old_user_roles = set(r.get_name() for r in roles.get_user_roles(user)) super(RolePermissionsUserAdminMixin, self).save_related(request, form, formsets, change) new_user_groups = set(g.name for g in user.groups.all()) for role_name in (old_user_roles - new_user_groups): # roles removed from User's groups try: # put the recently removed group back, let rolepermissions remove it... group = Group.objects.get(name=role_name) user.groups.add(group) except Group.DoesNotExist: pass roles.remove_role(user, role_name) for group_name in (new_user_groups - old_user_roles): # groups potentially added to User's roles try: roles.assign_role(user, group_name) except roles.RoleDoesNotExist: pass
def test_remove_role_user_isnt_assigned_to(self): remove_role(self.user, self.Doctor) self.assertListEqual([], get_user_roles(self.user))
def test_assign_role(self): user = self.user assign_role(user, 'sho_role1') self.assertListEqual([ShoRole1], get_user_roles(user))
def test_user_without_role(self): user = self.user self.assertListEqual([], get_user_roles(user))
def test_remove_role_from_user(self): assign_role(self.user, self.Doctor) remove_role(self.user, self.Doctor) self.assertListEqual([], get_user_roles(self.user))
def test_returns_list(self) : user = self.user user_roles = get_user_roles(user) self.assertEquals(type(user_roles), type([]))
def test_assign_role_by_class(self): user = self.user assign_role(user, ShoRole1) self.assertListEqual([ShoRole1], get_user_roles(user))