def get_user_role(user): if user: roles = user.groups.filter(name__in=RolesManager.get_roles_names()) if roles: return RolesManager.retrieve_role(roles[0].name) return None
def test_creates_when_does_not_exists(self): user = self.user class Role4(AbstractUserRole): available_permissions = { 'the_permission': True, } RolesManager.register_role(Role4) Role4.assign_role_to_user(user) Role4.available_permissions = { 'the_permission': True, 'new_permission': True, } permissions = get_user_permissions(user) self.assertIn('the_permission', permissions) self.assertIn('new_permission', permissions) self.assertTrue(permissions['the_permission']) self.assertTrue(permissions['new_permission']) self.assertEquals(len(permissions), 2) new_permission = UserPermission.objects.get(user=user, permission_name='new_permission') self.assertTrue(new_permission.is_granted)
def setUp(self): RolesManager.register_role(Role1) RolesManager.register_role(Role2) self.user = mommy.make(get_user_model()) self.factory = RequestFactory() self.request = self.factory.get('/') self.request.session = {} self.request.user = self.user
def remove_role(user): old_groups = user.groups.filter(name__in=registered_roles.keys()) for old_group in old_groups: # Normally there is only one, but remove all other role groups role = RolesManager.retrieve_role(old_group.name) permissions_to_remove = Permission.objects.filter(codename__in=role.permission_names_list()).all() user.user_permissions.remove(*permissions_to_remove) user.groups.remove(*old_groups)
class ApproveRegistration(ModelForm): role = forms.ChoiceField( label='Desired role', choices=map( lambda x: (x, x), RolesManager.get_roles_names() ) ) class Meta: model = models.UserProfile fields = [] 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 delete(self, notify): email = self.instance.user.email self.instance.user.delete() notify(email)
def remove_role(user): old_groups = user.groups.filter(name__in=registered_roles.keys()) for old_group in old_groups: # Normally there is only one, but remove all other role groups role = RolesManager.retrieve_role(old_group.name) permissions_to_remove = Permission.objects.filter( codename__in=role.permission_names_list()).all() user.user_permissions.remove(*permissions_to_remove) user.groups.remove(*old_groups)
def load_roles_and_permissions(): roles_module = import_module(settings.ROLEPERMISSIONS_MODULE) RolesManager._roles = {} PermissionsManager._checkers = {} for name, cls in roles_module.__dict__.items(): if inspect.isclass(cls) and issubclass(cls, AbstractUserRole) and cls is not AbstractUserRole: RolesManager.register_role(cls) # print 'Loading role ' + cls().get_name() for app_name in settings.INSTALLED_APPS: if app_name is not 'rolepermissions': try: import_module('.permissions', app_name) except ImportError as exc: pass
def test_creates_permission_when_not_existent(self): user = self.user class Role4(AbstractUserRole): available_permissions = { 'the_permission': True } RolesManager.register_role(Role4) Role4.assign_role_to_user(user) Role4.available_permissions = { 'different_one': True } self.assertTrue(has_permission(user, 'different_one')) permission = UserPermission.objects.get(user=user, permission_name='different_one') self.assertTrue(permission.is_granted)
def all_roles_permissions(self, obj): # get all roles permission in json structure roles_json = {} for role in RolesManager.get_roles(): roles_json[role.get_name()] = [ '- %s' % permission for permission in list(role.permission_names_list()) ] return json.dumps(roles_json)
def setUp(self): RolesManager.register_role(Role1) RolesManager.register_role(Role2) RolesManager.register_role(Role3) self.user = mommy.make(get_user_model()) self.user_role = Role2.assign_role_to_user(self.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 _construct_permission_to_roles(role_ids): """ Create a mapping of role id Args: role_ids (list of str): A list of all role ids Returns: dict: A map of permission to a list of role ids which have that permission """ permissions = defaultdict(list) for role_id in role_ids: for permission, is_set in RolesManager.retrieve_role(role_id).available_permissions.items(): if is_set: permissions[permission].append(role_id) return permissions
def setUp(self): RolesManager.register_role(Role1) RolesManager.register_role(Role2) RolesManager.register_role(Role3) self.user = mommy.make(get_user_model()) Role1.assign_role_to_user(self.user) @register_object_checker() def obj_checker(role, user, obj): return obj and True
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 _construct_permission_to_roles(role_ids): """ Create a mapping of role id Args: role_ids (list of str): A list of all role ids Returns: dict: A map of permission to a list of role ids which have that permission """ permissions = defaultdict(list) for role_id in role_ids: for permission, is_set in RolesManager.retrieve_role( role_id).available_permissions.items(): if is_set: permissions[permission].append(role_id) return permissions
def save(self, commit=False): profile = super().save(commit=False) first_name = self.cleaned_data["first_name"] last_name = self.cleaned_data["last_name"] email = self.cleaned_data["email"] role = RolesManager.retrieve_role(self.cleaned_data["role"]) # create user user = models.User.objects.create_user(email, email=email, first_name=first_name, last_name=last_name) role.assign_role_to_user(user) user.is_active = False user.save() # assign to profile profile.user = user profile.save() return profile
def has_role(user, 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) try: user_role = get_user_role(user) except ObjectDoesNotExist: return False if not user_role: return False return user_role in normalized_roles
def setUp(self): RolesManager.register_role(Role1) RolesManager.register_role(Role2) RolesManager.register_role(Role3) self.user = mommy.make(get_user_model())
def get_user_role(user): if hasattr(user, 'role'): return RolesManager.retrieve_role(user.role.role_name) return None
def retrieve_role(role_name): return RolesManager.retrieve_role(role_name)
def setUp(self): RolesManager.register_role(Role1) RolesManager.register_role(Role2) RolesManager.register_role(Role3)
def get_nonprivileged_roles(): return [ name for name in RolesManager.get_roles_names() if name != SiteAdministrator.get_name() and name != ContentManager.get_name() ]
def test_retrieve_role(self): self.assertEquals(RolesManager.retrieve_role('rol_role1'), RolRole1) self.assertEquals(RolesManager.retrieve_role('rol_role2'), RolRole2)
def test_registering_role(self): self.assertNotIn('role1', RolesManager._roles) RolesManager.register_role(Role1) self.assertIn('role1', RolesManager._roles)
def test_get_roles(self): RolesManager.register_role(Role1) RolesManager.register_role(Role2) self.assertTrue(isinstance(RolesManager.get_roles(), dict)) self.assertEquals(len(RolesManager.get_roles()), 2)
def test_retrieve_role(self): RolesManager.register_role(Role1) RolesManager.register_role(Role2) self.assertEquals(RolesManager.retrieve_role('role1'), Role1) self.assertEquals(RolesManager.retrieve_role('role2'), Role2)
def get(self, request): result = [{'name': entry} for entry in RolesManager.get_roles_names()] return JsonResponse(result, safe=False)
def sync_user_delay(mocker): return mocker.patch( 'pythonpro.domain.user_facade.sync_user_on_discourse.delay') @pytest.fixture def email_market_mocks(mocker): maybe_function_names = dir(user_facade._email_marketing_facade) task_function_mocks = [] for name in maybe_function_names: maybe_task_function = getattr(user_facade._email_marketing_facade, name) if hasattr(maybe_task_function, 'delay'): task_function_mocks.append( mocker.patch( f'pythonpro.domain.user_facade._email_marketing_facade.{name}.delay', side_effeict=maybe_task_function)) return task_function_mocks @pytest.mark.parametrize('role', RolesManager.get_roles_names()) def test_make_actions(logged_user, role, django_user_model, sync_user_delay, email_market_mocks, cohort): if role in {'lead', 'client'}: return # Client product is not active anymore admin = UserAdmin(django_user_model, AdminSite()) make_method = getattr(admin, f'make_{role}') assert not has_role(logged_user, role) make_method(None, [logged_user]) assert has_role(logged_user, role)
class RegisterForm(ModelForm): first_name = forms.CharField(max_length=30) last_name = forms.CharField(max_length=150) email = forms.EmailField(label='Email address') role = forms.ChoiceField( label='Desired role', choices=map(lambda x: (x, x), filter( lambda n: n != roles.SiteAdministrator.get_name(), RolesManager.get_roles_names() )) ) affiliation = forms.CharField(max_length=255, required=True) class Meta: model = models.UserProfile exclude = ['user', 'countries'] labels = { 'home_country': 'Country', } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) widgets = (field.widget for field in self.fields.values()) for widget in widgets: widget.attrs['class'] = 'form-control' def clean_email(self): email = self.cleaned_data['email'] users_with_email = models.User.objects.filter( Q(email=email) | Q(username=email) ) if users_with_email: raise ValidationError('That email address is already registered!') return email def save(self, commit=False): profile = super().save(commit=False) first_name = self.cleaned_data['first_name'] last_name = self.cleaned_data['last_name'] email = self.cleaned_data['email'] role = RolesManager.retrieve_role(self.cleaned_data['role']) # create user user = models.User.objects.create_user( email, email=email, first_name=first_name, last_name=last_name ) role.assign_role_to_user(user) user.is_active = False user.save() # assign to profile profile.user = user profile.save() return profile
def get_all_roles(): roles_list = enumerate(list(RolesManager.get_roles_names())) roles = [] for key, role in roles_list: roles.append((role, role.title())) return tuple(roles)