class AccountEditPermissionTestCase(TestCase): def setUp(self): self.user = PersonaFactory() self.anonymous = AnonymousUser() self.account = AccountFactory() def test_owner_cannot_change_account(self): '''Tests owners don't have change permission of Account''' self.assertFalse(self.account.user.has_perm('profiles.change_account', obj=self.account)) def test_others_cannot_change_account(self): '''Tests others don't have change permission of Account''' self.assertFalse(self.user.has_perm('profiles.change_account', obj=self.account)) def test_anonymous_cannot_change_account(self): '''Tests anonymous don't have change permission of Account''' self.assertFalse(self.anonymous.has_perm('profiles.change_account', obj=self.account)) def test_owner_can_delete_account(self): '''Tests owners have delete permission of Account''' self.assertTrue(self.account.user.has_perm('profiles.delete_account', obj=self.account)) def test_others_cannot_delete_account(self): '''Tests others don't have delete permission of Account''' self.assertFalse(self.user.has_perm('profiles.delete_account', obj=self.account)) def test_anonymous_cannot_delete_account(self): '''Tests anonymous don't have delete permission of Account''' self.assertFalse(self.anonymous.has_perm('profiles.delete_account', obj=self.account))
def read_detail( self, object_detail, bundle ): logged_in_user = bundle.request.user user = bundle.request.GET.get( 'user', None ) if object_detail.is_public: return True # Case 1: There is no logged in user and no user query provided. We don't # know what to query if logged_in_user.is_anonymous() and user is None: return False # Case 2: There *is* a logged in user and no user query. Query repos # that only belong to the currently logged in user if user is None and logged_in_user.is_authenticated(): public = AnonymousUser() return public.has_perm( 'view_repository', object_detail ) or logged_in_user.has_perm( 'view_repository', object_detail ) # Case 3: User query is provided. Check whether the public or the user has access # to this data. if user is not None: public = AnonymousUser() user = User.objects.get( username=user ) return public.has_perm( 'view_repository', object_detail ) or user.has_perm( 'view_repository', object_detail ) return False
class ProfileEditPermissionTestCase(TestCase): def setUp(self): self.user = PersonaFactory() self.anonymous = AnonymousUser() self.profile = ProfileFactory() def test_owner_can_change_profile(self): '''Tests owner has change permission of Profile''' self.assertTrue(self.profile.user.has_perm('profiles.change_profile', obj=self.profile)) def test_others_cannot_change_profile(self): '''Tests others don't have change permission of Profile''' self.assertFalse(self.user.has_perm('profiles.change_profile', obj=self.profile)) def test_anonymous_cannot_change_profile(self): '''Tests anonymous don't have change permission of Profile''' self.assertFalse(self.anonymous.has_perm('profiles.change_profile', obj=self.profile)) def test_owner_cannot_delete_profile(self): '''Tests owner don't have delete permission of Profile''' self.assertFalse(self.profile.user.has_perm('profiles.delete_profile', obj=self.profile)) def test_others_cannot_delete_profile(self): '''Tests others don't have delete permission of Profile''' self.assertFalse(self.user.has_perm('profiles.delete_profile', obj=self.profile)) def test_anonymous_cannot_delete_profile(self): '''Tests anonymous don't have delete permission of Profile''' self.assertFalse(self.anonymous.has_perm('profiles.delete_profile', obj=self.profile))
class GroupObjectPermBackendTest(TestCase): def setUp(self): self.james = User.objects.create_user('james', '*****@*****.**', 'james') self.emily = User.objects.create_user('emily', '*****@*****.**', 'emily') self.peter = User.objects.create_user('peter', '*****@*****.**', 'peter') self.fread = AnonymousUser() self.manager = Group.objects.create(name='manager') self.editor = Group.objects.create(name='editor') self.james.groups.add(self.manager) self.james.groups.add(self.editor) self.emily.groups.add(self.editor) self.page = FlatPage.objects.create(url='/test/', title='test', content='James can see this content but emily.') # for checking permission for all authenticated user ObjectPermissionMediator.viewer(self.page, None) # for checking permission for particular group ObjectPermissionMediator.manager(self.page, self.manager) ObjectPermissionMediator.editor(self.page, self.editor) def test_permission(self): # James has view, change, delete self.assertTrue(self.james.has_perm('flatpages.view_flatpage', self.page)) self.assertTrue(self.james.has_perm('flatpages.change_flatpage', self.page)) self.assertTrue(self.james.has_perm('flatpages.delete_flatpage', self.page)) # Emliy has view, change but delete self.assertTrue(self.emily.has_perm('flatpages.view_flatpage', self.page)) self.assertTrue(self.emily.has_perm('flatpages.change_flatpage', self.page)) self.assertTrue(not self.emily.has_perm('flatpages.delete_flatpage', self.page)) # Peter has view self.assertTrue(self.peter.has_perm('flatpages.view_flatpage', self.page)) self.assertTrue(not self.peter.has_perm('flatpages.change_flatpage', self.page)) self.assertTrue(not self.peter.has_perm('flatpages.delete_flatpage', self.page)) # Fread never has any permission because he is not authenticated self.assertTrue(not self.fread.has_perm('flatpages.view_flatpage', self.page)) self.assertTrue(not self.fread.has_perm('flatpages.change_flatpage', self.page)) self.assertTrue(not self.fread.has_perm('flatpages.delete_flatpage', self.page))
def read_detail( self, object_detail, bundle ): logged_in_user = bundle.request.user user = bundle.request.GET.get( 'user', None ) if object_detail.is_public: return True # Case 1: There is no logged in user and no user query provided. We don't # know what to query if logged_in_user.is_anonymous() and user is None: return False # Case 2: There *is* a logged in user and no user query. Query repos # that only belong to the currently logged in user if user is None and logged_in_user.is_authenticated(): public = AnonymousUser() return public.has_perm( 'view_repository', object_detail ) or logged_in_user.has_perm( 'view_repository', object_detail ) # Case 3: User query is provided. Check whether the public or the user has access # to this data. if user is not None: public = AnonymousUser() user = User.objects.get( username=user ) return public.has_perm( 'view_repository', object_detail ) or user.has_perm( 'view_repository', object_detail ) return False
class AnonymousAuthenticationBackendTest(BluebottleTestCase): def setUp(self): super(AnonymousAuthenticationBackendTest, self).setUp() self.codename = 'add_site' self.permission_string = 'sites.{}'.format(self.codename) self.permission = Permission.objects.get(codename=self.codename) self.group, _ = Group.objects.get_or_create(name='Anonymous') self.anonymous_user = AnonymousUser() self.user = BlueBottleUserFactory.create() def test_has_permission(self): """ Test that anonymous user get permissions from anonymous group""" self.group.permissions.add(self.permission) self.assertTrue(self.anonymous_user.has_perm(self.permission_string)) def test_has_no_permission(self): """ Test that anonymous user get no permissions if permission not in group""" self.assertFalse(self.anonymous_user.has_perm(self.permission_string)) def test_authenticated_user_has_no_permission(self): """ Test that normal user get no permissions""" self.group.permissions.add(self.permission) self.assertFalse(self.user.has_perm(self.permission_string)) def test_no_permission_non_existant_group(self): """ Test that if the group does not exist, the user does not get the permission""" self.group.delete() self.assertFalse(self.anonymous_user.has_perm(self.permission_string))
def test_anonymous_user_does_not_have_permissions(self): # Given user = AnonymousUser() # When/Then self.assertFalse(user.has_perm('rsr.change_project', None)) self.assertFalse(user.has_perm('rsr.change_project', self.project))
class ProductQuitPermissionTestCase(TestCase): def setUp(self): self.product = ProductFactory() self.user = PersonaFactory() self.wille = PersonaFactory(role='wille') self.anonymous = AnonymousUser() def test_anonymous_dont_have_quit_permission(self): ''' Test anonymous users do not have quit from product permission ''' self.assertFalse(self.anonymous.has_perm('products.quit_product')) def test_wille_dont_have_quit_permission(self): ''' Test wille users do not have quit from product permission ''' self.assertFalse(self.wille.has_perm('products.quit_product')) def test_general_user_have_quit_permission(self): ''' Test general user have quit from product permission ''' self.assertTrue(self.user.has_perm('products.quit_product')) def test_anonymous_dont_have_quit_permission_with_object(self): ''' Test anonymous users do not have quit from product permission ''' self.assertFalse(self.anonymous.has_perm('products.quit_product', self.product)) def test_wille_dont_have_quit_permission_with_object(self): ''' Test wille users do not have quit from product permission ''' self.assertFalse(self.wille.has_perm('products.quit_product', self.product)) def test_other_user_dont_have_quit_permission_with_object(self): ''' Test other user don't have quit from product permission ''' self.assertFalse(self.user.has_perm('products.quit_product', self.product)) def test_last_administrators_dont_have_quit_permission_with_object(self): ''' Test last_administrators don't have quit from product permission ''' self.product.administrators.add(self.user) self.assertEqual(self.product.administrators.count(), 1) self.assertFalse(self.user.has_perm('products.quit_product', self.product)) def test_administrators_have_quit_permission_with_object(self): ''' Test last_administrators have quit from product permission ''' other = PersonaFactory() self.product.administrators.add(self.user) self.product.administrators.add(other) self.assertTrue(self.user.has_perm('products.quit_product', self.product))
def test_anonymous_user_perms(self): anonymous_user = AnonymousUser() self.assertFalse(anonymous_user.has_perm(self.get_perm_str('add'))) self.assertFalse(anonymous_user.has_perm(self.get_perm_str('change'), obj=self.codebase_release)) self.assertFalse(anonymous_user.has_perm(self.get_perm_str('delete'), obj=self.codebase_release)) self.assertFalse(anonymous_user.has_perm(self.get_perm_str('view'), obj=self.codebase_release)) self.codebase_release.live = True self.codebase_release.save() self.assertTrue(anonymous_user.has_perm(self.get_perm_str('view'), obj=self.codebase_release))
def test_anonymous(self): person = AnonymousUser() event = EventFactory() with self.assertNumQueries(0): self.assertEqual( person.get_all_permissions(event.organization), set(), ) with self.assertNumQueries(0): self.assertFalse(person.has_perm('view', event.organization)) self.assertFalse(person.has_perm('edit', event.organization)) self.assertFalse(person.has_perm('change_permissions', event.organization))
class ProductJoinPermissionTestCase(TestCase): def setUp(self): self.product = ProductFactory() self.user = PersonaFactory() self.wille = PersonaFactory(role='wille') self.anonymous = AnonymousUser() def test_anonymous_dont_have_join_permission(self): ''' Test anonymous users do not have join to product permission ''' self.assertFalse(self.anonymous.has_perm('products.join_product')) def test_wille_dont_have_join_permission(self): ''' Test wille users do not have join to product permission ''' self.assertFalse(self.wille.has_perm('products.join_product')) def test_general_user_have_join_permission(self): ''' Test general user have join to product permission ''' self.assertTrue(self.user.has_perm('products.join_product')) def test_anonymous_dont_have_join_permission_with_object(self): ''' Test anonymous users do not have join to product permission ''' self.assertFalse(self.anonymous.has_perm('products.join_product', self.product)) def test_wille_dont_have_join_permission_with_object(self): ''' Test wille users do not have join to product permission ''' self.assertFalse(self.wille.has_perm('products.join_product', self.product)) def test_other_user_have_join_permission_with_object(self): ''' Test other user have join to product permission ''' self.assertTrue(self.user.has_perm('products.join_product', self.product)) def test_administrators_dont_have_join_permission_with_object(self): ''' Test administrators don't have join to product permission ''' self.product.administrators.add(self.user) self.assertFalse(self.user.has_perm('products.join_product', self.product))
def authorization(request): """Check if user has authorization to access requested file. This function is used by nginx's ngx_http_auth_request_module module and follows it's specifications: http://nginx.org/en/docs/http/ngx_http_auth_request_module.html If the subrequest returns a 2xx response code, the access is allowed. If it returns 401 or 403, the access is denied with the corresponding error code. Any other response code returned by the subrequest is considered an error. """ if 'HTTP_REQUEST_URI' not in request.META: return HttpResponse(status=403) uri = request.META['HTTP_REQUEST_URI'] if re.match('/upload/$', uri): if not request.user.is_authenticated: return HttpResponse(status=403) return HttpResponse(status=200) uri_regex = re.match(r'/(data|datagzip)/(?P<data_id>\d+)/', uri) if uri_regex: data_id = uri_regex.group('data_id') try: data = Data.objects.get(pk=data_id) except Data.DoesNotExist: return HttpResponse(status=403) # Session authentication. pub_user = AnonymousUser() if pub_user.has_perm('view_data', data) and pub_user.has_perm( 'download_data', data ): return HttpResponse(status=200) if ( request.user.is_authenticated and request.user.has_perm('view_data', data) and request.user.has_perm('download_data', data) ): return HttpResponse(status=200) return HttpResponse(status=403)
def render(self, context): user_obj = template.resolve_variable('user', context) obj = template.resolve_variable(self.objname, context) if not user_obj.is_authenticated: user_obj = AnonymousUser() context[self.varname] = user_obj.has_perm(self.codename, obj) return ''
def test_anonymous_user(self): csv_data = f""" Model, App, Action, Is Global, , {USER1_TYPE}, TestModelA, test_csv_permissions, foo, yes, , yes, """.strip() user = AnonymousUser() with override_csv_permissions([csv_data]): with override_settings(CSV_PERMISSIONS_STRICT=True): self.assertFalse( user.has_perm("test_csv_permissions.foo_testmodela")) with override_settings(CSV_PERMISSIONS_STRICT=False): self.assertFalse( user.has_perm("test_csv_permissions.foo_testmodela"))
class AnnouncementAddPermissionTestCase(TestCase): def setUp(self): self.nerv = PersonaFactory(role='nerv') self.user = PersonaFactory() self.wille = PersonaFactory(role='wille') self.anonymous = AnonymousUser() def test_staffs_have_add_announcement_permission(self): ''' Tests staffs have permission to add announcements ''' self.assertTrue(self.nerv.has_perm('announcements.add_announcement')) def test_users_dont_have_add_announcement_permission(self): ''' Tests users do not have permission to add announcements ''' self.assertFalse(self.user.has_perm('announcements.add_announcement')) def test_wille_dont_have_add_announcement_permission(self): ''' Tests wille users do not have permission to add announcements ''' self.assertFalse(self.wille.has_perm('announcements.add_announcement')) def test_anonymous_dont_have_add_announcement_permission(self): ''' Tests anonymous users do not have permission to add announcements ''' self.assertFalse(self.anonymous.has_perm('announcements.add_announcement'))
class AnnouncementAddPermissionTestCase(TestCase): def setUp(self): self.nerv = PersonaFactory(role='nerv') self.user = PersonaFactory() self.wille = PersonaFactory(role='wille') self.anonymous = AnonymousUser() def test_staffs_have_add_announcement_perm(self): """ スタッフはお知らせを作成する権限を持つ """ self.assertTrue(self.nerv.has_perm( 'announcements.add_announcement')) def test_users_dont_have_add_announcement_perm(self): """ ログインユーザーはお知らせを作成する権限を持たない """ self.assertFalse(self.user.has_perm( 'announcements.add_announcement')) def test_wille_dont_have_add_announcement_perm(self): """ Willeユーザーはお知らせを作成する権限を持たない """ self.assertFalse(self.wille.has_perm( 'announcements.add_announcement')) def test_anonymous_dont_have_add_announcement_perm(self): """ 非ログインユーザーはお知らせを作成する権限を持たない """ self.assertFalse(self.anonymous.has_perm( 'announcements.add_announcement'))
class AnonymousUserBackendTest(TestCase): """ Tests for AnonymousUser delegating to backend. """ backend = 'django.contrib.auth.tests.auth_backends.SimpleRowlevelBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = (self.backend, ) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user1.has_perm('anon', TestObj()), True) def test_has_perms(self): self.assertEqual(self.user1.has_perms(['anon'], TestObj()), True) self.assertEqual(self.user1.has_perms(['anon', 'perm'], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms("app1"), True) self.assertEqual(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['anon']))
class LikeRulesTestCase(SiteTestCase): def set_up(self): super().set_up() self.user = ActiveUserFactory() self.other_user = ActiveUserFactory() self.anon = AnonymousUser() def test_anonymous_cannot_like(self): self.assertFalse(expr=self.anon.has_perm(perm='likes.like', obj=self.other_user)) def test_user_cannot_like_self(self): self.assertFalse(expr=self.user.has_perm(perm='likes.like', obj=self.user)) def test_user_can_like(self): self.assertTrue(expr=self.user.has_perm(perm='likes.like', obj=self.other_user)) def test_user_cannot_like_other_user_if_blocked(self): Block.objects.block(blocker=self.user, blocked=self.other_user) self.assertFalse(expr=self.user.has_perm(perm='likes.like', obj=self.other_user)) def test_user_cannot_like_other_user_if_blocking(self): Block.objects.block(blocker=self.other_user, blocked=self.user) self.assertFalse(expr=self.user.has_perm(perm='likes.like', obj=self.other_user)) def test_user_cannot_like_twice(self): UserLike.objects.add_like(from_user=self.user, to_user=self.other_user) self.assertFalse(expr=self.user.has_perm(perm='likes.like', obj=self.other_user))
class NoAnonymousUserBackendTest(TestCase): """ Tests that AnonymousUser does not delegate to backend if it has 'supports_anonymous_user' = False """ backend = 'django.contrib.auth.tests.auth_backends.NoAnonymousUserBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = tuple( self.curr_auth) + (self.backend, ) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user1.has_perm('anon', TestObj()), False) def test_has_perms(self): self.assertEqual(self.user1.has_perms(['anon'], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms("app1"), False) self.assertEqual(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set())
class RowlevelBackendTest(TestCase): backend = 'django.contrib.auth.tests.auth_backends.SimpleRowlevelBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = self.curr_auth + (self.backend,) self.user1 = User.objects.create_user('test', '*****@*****.**', 'test') self.user2 = User.objects.create_user('test2', '*****@*****.**', 'test') self.user3 = AnonymousUser() self.user4 = User.objects.create_user('test4', '*****@*****.**', 'test') def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user2.has_perm('perm', TestObj()), True) self.assertEqual(self.user2.has_perm('perm'), False) self.assertEqual(self.user2.has_perms(['simple', 'advanced'], TestObj()), True) self.assertEqual(self.user3.has_perm('perm', TestObj()), False) self.assertEqual(self.user3.has_perm('anon', TestObj()), False) self.assertEqual(self.user3.has_perms(['simple', 'advanced'], TestObj()), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['simple'])) self.assertEqual(self.user2.get_all_permissions(TestObj()), set(['simple', 'advanced'])) self.assertEqual(self.user2.get_all_permissions(), set([])) def test_get_group_permissions(self): content_type=ContentType.objects.get_for_model(Group) group = Group.objects.create(name='test_group') self.user4.groups.add(group) self.assertEqual(self.user4.get_group_permissions(TestObj()), set(['group_perm']))
def render(self, context): user_obj = template.resolve_variable('user', context) obj = template.resolve_variable(self.objname, context) if not user_obj.is_authenticated: user_obj = AnonymousUser() context[self.varname] = user_obj.has_perm(self.codename, obj) return ''
def test_custom_perms(self): user = self.UserModel.objects.get(pk=self.user.pk) user.user_permissions = ['auth.test'] user.save() # reloading user to purge the _perm_cache user = self.UserModel.objects.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions() == set(['auth.test']), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms('Group'), False) self.assertEqual(user.has_module_perms('auth'), True) user.user_permissions.extend(['auth.test2', 'auth.test3']) user.save() user = self.UserModel.objects.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), set(['auth.test2', 'auth.test', 'auth.test3'])) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) group = Group.objects.create(name='test_group') group.permissions = ['auth.test_group'] group.save() user.groups = [group] user.save() user = self.UserModel.objects.get(pk=self.user.pk) exp = set(['auth.test2', 'auth.test', 'auth.test3', 'auth.test_group']) self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), set(['auth.test_group'])) self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)
class AnnouncementAddPermissionTestCase(TestCase): def setUp(self): self.nerv = PersonaFactory(role='nerv') self.user = PersonaFactory() self.wille = PersonaFactory(role='wille') self.anonymous = AnonymousUser() def test_staffs_have_add_announcement_perm(self): """ スタッフはお知らせを作成する権限を持つ """ self.assertTrue(self.nerv.has_perm('announcements.add_announcement')) def test_users_dont_have_add_announcement_perm(self): """ ログインユーザーはお知らせを作成する権限を持たない """ self.assertFalse(self.user.has_perm('announcements.add_announcement')) def test_wille_dont_have_add_announcement_perm(self): """ Willeユーザーはお知らせを作成する権限を持たない """ self.assertFalse(self.wille.has_perm('announcements.add_announcement')) def test_anonymous_dont_have_add_announcement_perm(self): """ 非ログインユーザーはお知らせを作成する権限を持たない """ self.assertFalse( self.anonymous.has_perm('announcements.add_announcement'))
def test_custom_perms(self): user = self.UserModel.objects.get(pk=self.user.pk) user.user_permissions = ['auth.test'] user.save() # reloading user to purge the _perm_cache user = self.UserModel.objects.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions() == set(['auth.test']), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms('Group'), False) self.assertEqual(user.has_module_perms('auth'), True) user.user_permissions.extend(['auth.test2', 'auth.test3']) user.save() user = self.UserModel.objects.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), set(['auth.test2', 'auth.test', 'auth.test3'])) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) group = Group.objects.create(name='test_group') group.permissions = ['auth.test_group'] group.save() user.groups = [group] user.save() user = self.UserModel.objects.get(pk=self.user.pk) exp = set(['auth.test2', 'auth.test', 'auth.test3', 'auth.test_group']) self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), set(['auth.test_group'])) self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)
class RowlevelBackendTest(TestCase): backend = "django.contrib.auth.tests.auth_backends.SimpleRowlevelBackend" def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = self.curr_auth + (self.backend,) self.user1 = User.objects.create_user("test", "*****@*****.**", "test") self.user2 = User.objects.create_user("test2", "*****@*****.**", "test") self.user3 = AnonymousUser() self.user4 = User.objects.create_user("test4", "*****@*****.**", "test") def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm("perm", TestObj()), False) self.assertEqual(self.user2.has_perm("perm", TestObj()), True) self.assertEqual(self.user2.has_perm("perm"), False) self.assertEqual(self.user2.has_perms(["simple", "advanced"], TestObj()), True) self.assertEqual(self.user3.has_perm("perm", TestObj()), False) self.assertEqual(self.user3.has_perm("anon", TestObj()), False) self.assertEqual(self.user3.has_perms(["simple", "advanced"], TestObj()), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(["simple"])) self.assertEqual(self.user2.get_all_permissions(TestObj()), set(["simple", "advanced"])) self.assertEqual(self.user2.get_all_permissions(), set([])) def test_get_group_permissions(self): content_type = ContentType.objects.get_for_model(Group) group = Group.objects.create(name="test_group") self.user4.groups.add(group) self.assertEqual(self.user4.get_group_permissions(TestObj()), set(["group_perm"]))
class AnonymousUserBackendTest(TestCase): """ Tests for AnonymousUser delegating to backend if it has 'supports_anonymous_user' = True """ backend = "django.contrib.auth.tests.auth_backends.AnonymousUserBackend" def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = (self.backend,) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm("perm", TestObj()), False) self.assertEqual(self.user1.has_perm("anon", TestObj()), True) def test_has_perms(self): self.assertEqual(self.user1.has_perms(["anon"], TestObj()), True) self.assertEqual(self.user1.has_perms(["anon", "perm"], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms("app1"), True) self.assertEqual(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(["anon"]))
class AnonymousUserBackendTest(TestCase): """ Tests for AnonymousUser delegating to backend. """ backend = 'django.contrib.auth.tests.auth_backends.SimpleRowlevelBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = (self.backend,) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user1.has_perm('anon', TestObj()), True) def test_has_perms(self): self.assertEqual(self.user1.has_perms(['anon'], TestObj()), True) self.assertEqual(self.user1.has_perms(['anon', 'perm'], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms("app1"), True) self.assertEqual(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set(['anon']))
class AnonymousUserBackendTest(SimpleTestCase): """ Tests for AnonymousUser delegating to backend. """ def setUp(self): self.user1 = AnonymousUser() def test_has_perm(self): self.assertIs(self.user1.has_perm('perm', TestObj()), False) self.assertIs(self.user1.has_perm('anon', TestObj()), True) def test_has_perms(self): self.assertIs(self.user1.has_perms(['anon'], TestObj()), True) self.assertIs(self.user1.has_perms(['anon', 'perm'], TestObj()), False) def test_has_perms_perm_list_invalid(self): msg = 'perm_list must be an iterable of permissions.' with self.assertRaisesMessage(ValueError, msg): self.user1.has_perms('perm') with self.assertRaisesMessage(ValueError, msg): self.user1.has_perms(object()) def test_has_module_perms(self): self.assertIs(self.user1.has_module_perms("app1"), True) self.assertIs(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), {'anon'})
class NoAnonymousUserBackendTest(TestCase): """ Tests that AnonymousUser does not delegate to backend if it has 'supports_anonymous_user' = False """ backend = 'django.contrib.auth.tests.auth_backends.NoAnonymousUserBackend' def setUp(self): self.curr_auth = settings.AUTHENTICATION_BACKENDS settings.AUTHENTICATION_BACKENDS = tuple(self.curr_auth) + (self.backend,) self.user1 = AnonymousUser() def tearDown(self): settings.AUTHENTICATION_BACKENDS = self.curr_auth def test_has_perm(self): self.assertEqual(self.user1.has_perm('perm', TestObj()), False) self.assertEqual(self.user1.has_perm('anon', TestObj()), False) def test_has_perms(self): self.assertEqual(self.user1.has_perms(['anon'], TestObj()), False) def test_has_module_perms(self): self.assertEqual(self.user1.has_module_perms("app1"), False) self.assertEqual(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), set())
def render(self, context): user = context.get('user', None) request = context.get('request',None) if not user: if request: user = getattr(request, 'user', None) if not user: user = AnonymousUser() current_site=None object_filter = {'name': self.content_name} # Get current Site object (if used) if site: if request: current_site = get_current_site(request) if current_site: object_filter['site'] = current_site else: object_filter['site_id'] = 1 # Get current content object if AUTOCREATE or (not CHECK_PERMS and user.is_staff) or (CHECK_PERMS and user.has_perm('content_edit_add_cmscontent')): content = CmsContent.objects.get_or_create(**object_filter)[0] else: try: content = CmsContent.objects.get(**object_filter) except CmsContent.DoesNotExist: content= CmsContent(content='') # Check user Perms change_perm = False if user.is_authenticated(): if (CHECK_PERMS and user.has_perm('content_edit_change_cmscontent')) or (not CHECK_PERMS and user.is_staff): change_perm = True # Generate content if change_perm: html_content = u'<div id="content_{0}" onblur="save_cms_content(this, \'{0}\')" contenteditable="true">{1}</div>'.format( content.name, content.content) else: html_content = content.content return html_content
class AnonymousObjectPermBackendTest(TestCase): def setUp(self): self.james = User.objects.create_user('james', '*****@*****.**', 'james') self.fread = AnonymousUser() self.page = FlatPage.objects.create(url='/test/', title='test', content='James can see this content but emily.') # for checking permission for all authenticated user ObjectPermissionMediator.viewer(self.page, None) # for checking permission for anonymous user ObjectPermissionMediator.manager(self.page, 'anonymous') def test_permission(self): # James has view self.assertTrue(self.james.has_perm('flatpages.view_flatpage', self.page)) self.assertTrue(not self.james.has_perm('flatpages.change_flatpage', self.page)) self.assertTrue(not self.james.has_perm('flatpages.delete_flatpage', self.page)) # Fread has view, change, delete because he is anonymous user self.assertTrue(self.fread.has_perm('flatpages.view_flatpage', self.page)) self.assertTrue(self.fread.has_perm('flatpages.change_flatpage', self.page)) self.assertTrue(self.fread.has_perm('flatpages.delete_flatpage', self.page))
def read_detail( self, object_detail, bundle ): logged_in_user = bundle.request.user if logged_in_user.is_anonymous(): return object_detail.is_public or logged_in_user.has_perm( 'view_data', object_detail ) if logged_in_user.is_authenticated(): public = AnonymousUser() return public.has_perm( 'view_data', object_detail ) or logged_in_user.has_perm( 'view_data', object_detail )
def render(self, context): user = context.get('user', None) request = context.get('request',None) if not user: if request: user = getattr(request, 'user', None) if not user: user = AnonymousUser() current_site=None object_filter = {'name': self.content_name} # Get current Site object (if used) if site: if request: current_site = get_current_site(request) if current_site: object_filter['site'] = current_site else: object_filter['site_id'] = 1 # Get current content object if AUTOCREATE or (not CHECK_PERMS and user.is_staff) or (CHECK_PERMS and user.has_perm('content_edit_add_cmscontent')): content = CmsContent.objects.get_or_create(**object_filter)[0] else: try: content = CmsContent.objects.get(**object_filter) except CmsContent.DoesNotExist: content= CmsContent(content='') # Check user Perms change_perm = False if user.is_authenticated(): if (CHECK_PERMS and user.has_perm('content_edit_change_cmscontent')) or (not CHECK_PERMS and user.is_staff): change_perm = True # Generate content if change_perm: html_content = u'<span id="content_{0}">{1}</span><a href="#" data-tagname="{0}" class="glyphicon glyphicon-pencil btn btn-info btn-sm" data-toggle="modal" data-target="#content-edit-modal"></a>'.format(content.name, content.content) else: html_content = content.content return html_content
def render(self, context): user = context.get('user', None) request = context.get('request',None) if not user: if request: user = getattr(request, 'user', None) if not user: user = AnonymousUser() current_site=None object_filter = {'name': self.content_name} # Get current Site object (if used) if site: if request: current_site = get_current_site(request) if current_site: object_filter['site'] = current_site else: object_filter['site_id'] = 1 # Get current content object if AUTOCREATE or (not CHECK_PERMS and user.is_staff) or (CHECK_PERMS and user.has_perm('content_edit_add_cmscontent')): content = CmsContent.objects.get_or_create(**object_filter)[0] else: try: content = CmsContent.objects.get(**object_filter) except CmsContent.DoesNotExist: content= CmsContent(content='') # Check user Perms change_perm = False if user.is_authenticated(): if (CHECK_PERMS and user.has_perm('content_edit_change_cmscontent')) or (not CHECK_PERMS and user.is_staff): change_perm = True # Generate content if change_perm: html_content = u'<div id="content_{0}" onblur="save_cms_content(this, \'{0}\')" contenteditable="true">{1}</div>'.format( content.name, content.content) else: html_content = content.content return html_content
def test_user_without_perms_get_anonymous_perms(self): asset = self.admin_asset grantee = self.someuser anonymous_user = AnonymousUser() self.assertFalse(grantee.has_perm(PERM_VIEW_SUBMISSIONS, asset)) self.assertFalse(anonymous_user.has_perm(PERM_VIEW_SUBMISSIONS, asset)) asset.assign_perm(anonymous_user, PERM_VIEW_SUBMISSIONS) self.assertTrue(grantee.has_perm(PERM_VIEW_SUBMISSIONS, asset)) self.assertTrue(list(asset.get_perms(grantee)), list(asset.get_perms(AnonymousUser())))
def test_django_integration(self): """ Tests logical permission integration with Django's auth framework. """ user = AnonymousUser() # Should work with class-based permissions. class ClassPermission(LogicalPermission): def has_permission(self, user, obj=None): return True default_storage.register(ClassPermission()) self.assertTrue(user.has_perm('tests.ClassPermission')) self.assertFalse(user.has_perm('tests.blep')) # Should work with decorated permissions. @permission(register=True) def inline_decorated(user, obj=None): return True self.assertTrue(user.has_perm('tests.inline_decorated')) self.assertFalse(user.has_perm('tests.blep')) # Should work with custom labeled permissions. default_storage.register(ClassPermission(), label='tests.blep') self.assertTrue(user.has_perm('tests.blep')) # Should work with the permission registration from # the app's permissions.py. self.assertTrue(user.has_perm('tests.registered_permission')) # The authenticate method should just return None, # we don't authenticate users. self.assertIsNone(LogicalPermissionsBackend().authenticate())
class BackendTestAnonymousUser(RubberStampTestCase): fixtures = ['users.json', 'objects.json', 'permissions.json', 'assigned.json', 'assigned_object.json'] def setUp(self): self.anon = AnonymousUser() self.user = User.objects.get(pk=2) self.object = TestModel.objects.get(pk=1) def test_no_type_or_object(self): self.assertFalse(self.anon.has_perm('testapp.use')) def test_with_type(self): self.assertFalse(self.anon.has_perm('testapp.use.testapp.testmodel')) def test_with_object(self): self.assertFalse(self.anon.has_perm('testapp.use', obj=self.object)) def test_with_both(self): self.assertFalse(self.anon.has_perm('testapp.use.testapp.testmodel', obj=self.object)) def test_with_both_mismatched(self): self.assertFalse(self.anon.has_perm('testapp.use.auth.user', obj=self.object)) self.assertFalse(self.anon.has_perm('testapp.use.testapp.testmodel', obj=self.user)) def test_has_module_perms(self): self.assertFalse(self.anon.has_module_perms('testapp')) def test_get_all(self): self.assertEqual(len(self.anon.get_all_permissions()), 0) self.assertEqual(len(self.anon.get_all_permissions(obj=self.object)), 0) self.assertEqual(len(self.anon.get_all_permissions(obj=self.user)), 0)
def test_custom_perms(self): user = User.objects.get(username='******') content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() # reloading user to purge the _perm_cache user = User.objects.get(username='******') self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms('Group'), False) self.assertEqual(user.has_module_perms('auth'), True) perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2') user.user_permissions.add(perm) user.save() perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3') user.user_permissions.add(perm) user.save() user = User.objects.get(username='******') self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3'])) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group') group = Group.objects.create(name='test_group') group.permissions.add(perm) group.save() user.groups.add(group) user = User.objects.get(username='******') exp = set( [u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group']) self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), set([u'auth.test_group'])) self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)
def test_custom_perms(self): user = User.objects.get(username='******') content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create( name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) user.save() # reloading user to purge the _perm_cache user = User.objects.get(username='******') self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms('Group'), False) self.assertEqual(user.has_module_perms('auth'), True) perm = Permission.objects.create( name='test2', content_type=content_type, codename='test2') user.user_permissions.add(perm) user.save() perm = Permission.objects.create( name='test3', content_type=content_type, codename='test3') user.user_permissions.add(perm) user.save() user = User.objects.get(username='******') self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3'])) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) perm = Permission.objects.create( name='test_group', content_type=content_type, codename='test_group') group = Group.objects.create(name='test_group') group.permissions.add(perm) group.save() user.groups.add(group) user = User.objects.get(username='******') exp = set( [u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group']) self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), set([u'auth.test_group'])) self.assertEqual( user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)
class ProfileEditPermissionTestCase(TestCase): def setUp(self): self.user = PersonaFactory() self.anonymous = AnonymousUser() self.profile = ProfileFactory() def test_owner_can_change_profile(self): '''Tests owner has change permission of Profile''' self.assertTrue(self.profile.user.has_perm( 'personas.change_profile', obj=self.profile)) def test_others_cannot_change_profile(self): '''Tests others don't have change permission of Profile''' self.assertFalse(self.user.has_perm( 'personas.change_profile', obj=self.profile)) def test_anonymous_cannot_change_profile(self): '''Tests anonymous don't have change permission of Profile''' self.assertFalse(self.anonymous.has_perm( 'personas.change_profile', obj=self.profile)) def test_owner_cannot_delete_profile(self): '''Tests owner don't have delete permission of Profile''' self.assertFalse(self.profile.user.has_perm( 'personas.delete_profile', obj=self.profile)) def test_others_cannot_delete_profile(self): '''Tests others don't have delete permission of Profile''' self.assertFalse(self.user.has_perm( 'personas.delete_profile', obj=self.profile)) def test_anonymous_cannot_delete_profile(self): '''Tests anonymous don't have delete permission of Profile''' self.assertFalse(self.anonymous.has_perm( 'personas.delete_profile', obj=self.profile))
class AccountEditPermissionTestCase(TestCase): def setUp(self): self.user = PersonaFactory() self.anonymous = AnonymousUser() self.account = AccountFactory() def test_owner_cannot_change_account(self): '''Tests owners don't have change permission of Account''' self.assertFalse(self.account.profile.user.has_perm( 'personas.change_account', obj=self.account)) def test_others_cannot_change_account(self): '''Tests others don't have change permission of Account''' self.assertFalse(self.user.has_perm( 'personas.change_account', obj=self.account)) def test_anonymous_cannot_change_account(self): '''Tests anonymous don't have change permission of Account''' self.assertFalse(self.anonymous.has_perm( 'personas.change_account', obj=self.account)) def test_owner_can_delete_account(self): '''Tests owners have delete permission of Account''' self.assertTrue(self.account.profile.user.has_perm( 'personas.delete_account', obj=self.account)) def test_others_cannot_delete_account(self): '''Tests others don't have delete permission of Account''' self.assertFalse(self.user.has_perm( 'personas.delete_account', obj=self.account)) def test_anonymous_cannot_delete_account(self): '''Tests anonymous don't have delete permission of Account''' self.assertFalse(self.anonymous.has_perm( 'personas.delete_account', obj=self.account))
class ViewLikesRulesTestCase(SiteTestCase): def set_up(self): super().set_up() self.user = ActiveUserFactory() self.other_user = ActiveUserFactory() self.anon = AnonymousUser() def test_anonymous_cannot_view_likes(self): self.assertFalse(expr=self.anon.has_perm(perm='likes.view_likes', obj=self.user)) def test_other_user_cannot_view_likes(self): self.assertFalse(expr=self.other_user.has_perm(perm='likes.view_likes', obj=self.user)) def test_user_can_view_likes(self): self.assertTrue(expr=self.user.has_perm(perm='likes.view_likes', obj=self.user))
class ViewLikesTestCase(SiteTestCase): def set_up(self): super().set_up() self.user = ActiveUserFactory() self.other_user = ActiveUserFactory() self.anon = AnonymousUser() def test_anonymous_cannot_view_likes(self): self.assertFalse(expr=self.anon.has_perm(perm='likes.view_likes', obj=self.user)) def test_other_user_cannot_view_likes(self): self.assertFalse(expr=self.other_user.has_perm(perm='likes.view_likes', obj=self.user)) def test_user_can_view_likes(self): self.assertTrue(expr=self.user.has_perm(perm='likes.view_likes', obj=self.user))
def test_custom_perms(self): """Check interactions with custom permissions and groups""" user = self.UserModel._default_manager.get(pk=self.user.pk) content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name="test", content_type=content_type, codename="test") user.user_permissions.add(perm) # reloading user to purge the _perm_cache user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), {"auth.test"}) self.assertEqual(user.get_group_permissions(), set()) self.assertIs(user.has_module_perms("Group"), False) self.assertIs(user.has_module_perms("auth"), True) perm = Permission.objects.create(name="test2", content_type=content_type, codename="test2") user.user_permissions.add(perm) perm = Permission.objects.create(name="test3", content_type=content_type, codename="test3") user.user_permissions.add(perm) user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual( user.get_all_permissions(), {"auth.test2", "auth.test", "auth.test3"}, ) self.assertIs(user.has_perm("test"), False) self.assertIs(user.has_perm("auth.test"), True) self.assertIs(user.has_perms(["auth.test2", "auth.test3"]), True) perm = Permission.objects.create(name="test_group", content_type=content_type, codename="test_group") group = Group.objects.create(name="test_group") group.permissions.add(perm) user.groups.add(group) user = self.UserModel._default_manager.get(pk=self.user.pk) exp = {"auth.test2", "auth.test", "auth.test3", "auth.test_group"} self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), {"auth.test_group"}) self.assertIs(user.has_perms(["auth.test3", "auth.test_group"]), True) user = AnonymousUser() self.assertIs(user.has_perm("test"), False) self.assertIs(user.has_perms(["auth.test2", "auth.test3"]), False)
def test_custom_perms(self): user = self.UserModel._default_manager.get(pk=self.user.pk) content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) # reloading user to purge the _perm_cache user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), {'auth.test'}) self.assertEqual(user.get_user_permissions(), {'auth.test'}) self.assertEqual(user.get_group_permissions(), set()) self.assertIs(user.has_module_perms('Group'), False) self.assertIs(user.has_module_perms('auth'), True) perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2') user.user_permissions.add(perm) perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3') user.user_permissions.add(perm) user = self.UserModel._default_manager.get(pk=self.user.pk) expected_user_perms = {'auth.test2', 'auth.test', 'auth.test3'} self.assertEqual(user.get_all_permissions(), expected_user_perms) self.assertIs(user.has_perm('test'), False) self.assertIs(user.has_perm('auth.test'), True) self.assertIs(user.has_perms(['auth.test2', 'auth.test3']), True) perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group') group = Group.objects.create(name='test_group') group.permissions.add(perm) user.groups.add(group) user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), {*expected_user_perms, 'auth.test_group'}) self.assertEqual(user.get_user_permissions(), expected_user_perms) self.assertEqual(user.get_group_permissions(), {'auth.test_group'}) self.assertIs(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertIs(user.has_perm('test'), False) self.assertIs(user.has_perms(['auth.test2', 'auth.test3']), False)
class UnlikeTestCase(SiteTestCase): def set_up(self): super().set_up() self.user = ActiveUserFactory() self.other_user = ActiveUserFactory() self.anon = AnonymousUser() def test_anonymous_cannot_unlike(self): self.assertFalse(expr=self.anon.has_perm(perm='likes.unlike', obj=self.other_user)) def test_user_cannot_unlike_self(self): self.assertFalse(expr=self.user.has_perm(perm='likes.unlike', obj=self.user)) def test_user_cannot_unlike_if_doesnt_like(self): self.assertFalse(expr=self.user.has_perm(perm='likes.unlike', obj=self.other_user)) def test_user_can_unlike_if_likes(self): UserLike.objects.create(from_user=self.user, to_user=self.other_user) self.assertTrue(expr=self.user.has_perm(perm='likes.unlike', obj=self.other_user))
class UnlikeRulesTestCase(SiteTestCase): def set_up(self): super().set_up() self.user = ActiveUserFactory() self.other_user = ActiveUserFactory() self.anon = AnonymousUser() def test_anonymous_cannot_unlike(self): self.assertFalse(expr=self.anon.has_perm(perm='likes.unlike', obj=self.other_user)) def test_user_cannot_unlike_self(self): self.assertFalse(expr=self.user.has_perm(perm='likes.unlike', obj=self.user)) def test_user_cannot_unlike_if_doesnt_like(self): self.assertFalse(expr=self.user.has_perm(perm='likes.unlike', obj=self.other_user)) def test_user_can_unlike_if_likes(self): UserLike.objects.create(from_user=self.user, to_user=self.other_user) self.assertTrue(expr=self.user.has_perm(perm='likes.unlike', obj=self.other_user))
class AnonymousUserBackendTest(SimpleTestCase): """ Tests for AnonymousUser delegating to backend. """ def setUp(self): self.user1 = AnonymousUser() def test_has_perm(self): self.assertIs(self.user1.has_perm('perm', TestObj()), False) self.assertIs(self.user1.has_perm('anon', TestObj()), True) def test_has_perms(self): self.assertIs(self.user1.has_perms(['anon'], TestObj()), True) self.assertIs(self.user1.has_perms(['anon', 'perm'], TestObj()), False) def test_has_module_perms(self): self.assertIs(self.user1.has_module_perms("app1"), True) self.assertIs(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), {'anon'})
def apply_retrieve_permission(self, document_type, queryset, user): """ Apply potential additional restrictions based on the permissions. """ retrieve_permissions = document_type.retrieve_permissions.all() if user is None: user = AnonymousUser() if retrieve_permissions: for perm in retrieve_permissions: perm = perm.get_plugin() app_label = DocumentType._meta.app_label perm_name = "%s.%s" % (app_label, perm.permission_codename) if user.has_perm(perm_name): queryset = perm.filter_queryset_user_has_permission( queryset, model_type="index", user=user) else: queryset = \ perm.filter_queryset_user_does_not_have_permission( queryset=queryset, model_type="index", user=user) return queryset
class AnonymousUserBackendTest(SimpleTestCase): """ Tests for AnonymousUser delegating to backend. """ def setUp(self): self.user1 = AnonymousUser() def test_has_perm(self): self.assertIs(self.user1.has_perm('perm', TestObj()), False) self.assertIs(self.user1.has_perm('anon', TestObj()), True) def test_has_perms(self): self.assertIs(self.user1.has_perms(['anon'], TestObj()), True) self.assertIs(self.user1.has_perms(['anon', 'perm'], TestObj()), False) def test_has_module_perms(self): self.assertIs(self.user1.has_module_perms("app1"), True) self.assertIs(self.user1.has_module_perms("app2"), False) def test_get_all_permissions(self): self.assertEqual(self.user1.get_all_permissions(TestObj()), {'anon'})
def create_session(self, username, timestamp, auth): """ Get a new session """ # Create a new session key session = sha1(str(random.random())[2:]).hexdigest() # Check the time skew time_now = datetime.now() try: time_client = datetime.strptime(str(timestamp), TIME_FORMAT) except ValueError: return {'status': 'BADCALL Invalid time format.'} if time_client < time_now - TIME_SKEW or time_client > time_now + TIME_SKEW: return {'status': 'BADSESSION Clock skew too great. Maximum of %s minutes allowed.' % settings.XMLRPC_MAX_TIME_SKEW} # Find the user try: user = User.objects.get(username = username) except User.DoesNotExist: # No such user user = AnonymousUser() if settings.XMLRPC_DEBUG: return {'status': 'BADSESSION User not found: %s' % username} else: # Check the permissions if user.has_perm('xmlrpc.access_xmlrpc'): # Get the user's shared secret user_profile = user.get_profile() # Check the authentication vrf_auth = sha1(username + str(timestamp) + user_profile.xmlrpc_key).hexdigest() if auth == vrf_auth: # Create the new authentication new_auth = sha1(user.username + session + user_profile.xmlrpc_key).hexdigest() xmlrpc_session = self.create(user = user, session = session, auth = new_auth) elif settings.XMLRPC_DEBUG: # Authentication failed return {'status': 'BADSESSION Initial authentication failed.'} elif settings.XMLRPC_DEBUG: # Not allowed return {'status': 'FORBIDDEN You are not allowed to access the XML-RPC interface.'} # Return the status and the session key return {'status': 'OK', 'session': session}
def test_custom_perms(self): user = self.UserModel._default_manager.get(pk=self.user.pk) content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name="test", content_type=content_type, codename="test") user.user_permissions.add(perm) user.save() # reloading user to purge the _perm_cache user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions() == set(["auth.test"]), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms("Group"), False) self.assertEqual(user.has_module_perms("auth"), True) perm = Permission.objects.create(name="test2", content_type=content_type, codename="test2") user.user_permissions.add(perm) user.save() perm = Permission.objects.create(name="test3", content_type=content_type, codename="test3") user.user_permissions.add(perm) user.save() user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), set(["auth.test2", "auth.test", "auth.test3"])) self.assertEqual(user.has_perm("test"), False) self.assertEqual(user.has_perm("auth.test"), True) self.assertEqual(user.has_perms(["auth.test2", "auth.test3"]), True) perm = Permission.objects.create(name="test_group", content_type=content_type, codename="test_group") group = Group.objects.create(name="test_group") group.permissions.add(perm) group.save() user.groups.add(group) user = self.UserModel._default_manager.get(pk=self.user.pk) exp = set(["auth.test2", "auth.test", "auth.test3", "auth.test_group"]) self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), set(["auth.test_group"])) self.assertEqual(user.has_perms(["auth.test3", "auth.test_group"]), True) user = AnonymousUser() self.assertEqual(user.has_perm("test"), False) self.assertEqual(user.has_perms(["auth.test2", "auth.test3"]), False)
class LikeTestCase(SiteTestCase): def set_up(self): super().set_up() self.user = ActiveUserFactory() self.other_user = ActiveUserFactory() self.anon = AnonymousUser() def test_anonymous_cannot_like(self): self.assertFalse(expr=self.anon.has_perm(perm='likes.like', obj=self.other_user)) def test_user_cannot_like_self(self): self.assertFalse(expr=self.user.has_perm(perm='likes.like', obj=self.user)) def test_user_can_like(self): self.assertTrue(expr=self.user.has_perm(perm='likes.like', obj=self.other_user)) def test_user_cannot_like_if_blocked(self): Block.objects.block(blocker=self.other_user, blocked=self.user) self.assertFalse(expr=self.user.has_perm(perm='likes.like', obj=self.other_user)) def test_user_cannot_like_twice(self): UserLike.objects.create(from_user=self.user, to_user=self.other_user) self.assertFalse(expr=self.user.has_perm(perm='likes.like', obj=self.other_user))
def test_custom_perms(self): user = self.UserModel._default_manager.get(pk=self.user.pk) content_type = ContentType.objects.get_for_model(Group) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') user.user_permissions.add(perm) # reloading user to purge the _perm_cache user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), {'auth.test'}) self.assertEqual(user.get_group_permissions(), set()) self.assertIs(user.has_module_perms('Group'), False) self.assertIs(user.has_module_perms('auth'), True) perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2') user.user_permissions.add(perm) perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3') user.user_permissions.add(perm) user = self.UserModel._default_manager.get(pk=self.user.pk) self.assertEqual(user.get_all_permissions(), {'auth.test2', 'auth.test', 'auth.test3'}) self.assertIs(user.has_perm('test'), False) self.assertIs(user.has_perm('auth.test'), True) self.assertIs(user.has_perms(['auth.test2', 'auth.test3']), True) perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group') group = Group.objects.create(name='test_group') group.permissions.add(perm) user.groups.add(group) user = self.UserModel._default_manager.get(pk=self.user.pk) exp = {'auth.test2', 'auth.test', 'auth.test3', 'auth.test_group'} self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), {'auth.test_group'}) self.assertIs(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertIs(user.has_perm('test'), False) self.assertIs(user.has_perms(['auth.test2', 'auth.test3']), False)
class SupportGroupPermissionsTestCase(TestCase): def setUp(self) -> None: self.group = SupportGroup.objects.create(name="Group", published=True) self.referent = Person.objects.create_insoumise( "*****@*****.**", create_role=True ) self.manager = Person.objects.create_insoumise( "*****@*****.**", create_role=True ) self.member = Person.objects.create_insoumise( "*****@*****.**", create_role=True ) self.follower = Person.objects.create_insoumise( "*****@*****.**", create_role=True ) self.outsider = Person.objects.create_insoumise( "*****@*****.**", create_role=True ) self.anonymous = AnonymousUser() self.referent_membership = Membership.objects.create( supportgroup=self.group, person=self.referent, membership_type=Membership.MEMBERSHIP_TYPE_REFERENT, ) self.manager_membership = Membership.objects.create( supportgroup=self.group, person=self.manager, membership_type=Membership.MEMBERSHIP_TYPE_MANAGER, ) self.member_membership = Membership.objects.create( supportgroup=self.group, person=self.member, membership_type=Membership.MEMBERSHIP_TYPE_MEMBER, ) self.follower_membership = Membership.objects.create( supportgroup=self.group, person=self.follower, membership_type=Membership.MEMBERSHIP_TYPE_FOLLOWER, ) def test_can_view_published_group(self): self.assertTrue(self.referent.has_perm("groups.view_supportgroup", self.group)) self.assertTrue(self.manager.has_perm("groups.view_supportgroup", self.group)) self.assertTrue(self.member.has_perm("groups.view_supportgroup", self.group)) self.assertTrue(self.follower.has_perm("groups.view_supportgroup", self.group)) self.assertTrue(self.outsider.has_perm("groups.view_supportgroup", self.group)) self.assertTrue(self.anonymous.has_perm("groups.view_supportgroup", self.group)) def test_cannot_view_unpublished_group(self): self.group.published = False self.group.save() self.assertFalse(self.referent.has_perm("groups.view_supportgroup", self.group)) self.assertFalse(self.manager.has_perm("groups.view_supportgroup", self.group)) self.assertFalse(self.member.has_perm("groups.view_supportgroup", self.group)) self.assertFalse(self.follower.has_perm("groups.view_supportgroup", self.group)) self.assertFalse(self.outsider.has_perm("groups.view_supportgroup", self.group)) self.assertFalse( self.anonymous.has_perm("groups.view_supportgroup", self.group) ) def test_only_managers_can_change_group(self): self.assertTrue( self.referent.has_perm("groups.change_supportgroup", self.group) ) self.assertTrue(self.manager.has_perm("groups.change_supportgroup", self.group)) self.assertFalse(self.member.has_perm("groups.change_supportgroup", self.group)) self.assertFalse( self.follower.has_perm("groups.change_supportgroup", self.group) ) self.assertFalse( self.outsider.has_perm("groups.change_supportgroup", self.group) ) self.assertFalse( self.anonymous.has_perm("groups.change_supportgroup", self.group) ) def test_only_referent_cannot_leave_group(self): self.assertFalse( self.referent.has_perm("groups.delete_membership", self.referent_membership) ) self.assertTrue( self.manager.has_perm("groups.delete_membership", self.manager_membership) ) self.assertTrue( self.member.has_perm("groups.delete_membership", self.member_membership) ) self.assertTrue( self.follower.has_perm("groups.delete_membership", self.follower_membership) ) self.manager_membership.membership_type = Membership.MEMBERSHIP_TYPE_REFERENT self.manager_membership.save() self.assertTrue( self.referent.has_perm("groups.delete_membership", self.referent_membership) ) def test_only_referent_can_add_manager(self): self.assertTrue( self.referent.has_perm("groups.add_manager_to_supportgroup", self.group) ) self.assertFalse( self.manager.has_perm("groups.add_manager_to_supportgroup", self.group) ) self.assertFalse( self.member.has_perm("groups.add_manager_to_supportgroup", self.group) ) self.assertFalse( self.follower.has_perm("groups.add_manager_to_supportgroup", self.group) ) self.assertFalse( self.outsider.has_perm("groups.add_manager_to_supportgroup", self.group) ) self.assertFalse( self.anonymous.has_perm("groups.add_manager_to_supportgroup", self.group) ) def test_only_referent_can_add_referent_if_he_is_only_referent(self): self.assertTrue( self.referent.has_perm("groups.add_referent_to_supportgroup", self.group) ) self.assertFalse( self.manager.has_perm("groups.add_referent_to_supportgroup", self.group) ) self.assertFalse( self.member.has_perm("groups.add_referent_to_supportgroup", self.group) ) self.assertFalse( self.follower.has_perm("groups.add_referent_to_supportgroup", self.group) ) self.assertFalse( self.outsider.has_perm("groups.add_referent_to_supportgroup", self.group) ) self.assertFalse( self.anonymous.has_perm("groups.add_referent_to_supportgroup", self.group) ) self.manager_membership.membership_type = Membership.MEMBERSHIP_TYPE_REFERENT self.manager_membership.save() self.assertFalse( self.referent.has_perm("groups.add_referent_to_supportgroup", self.group) )
def test_custom_perms(self): user = User.objects.get(username='******') content_type = ContentType.objects.get_for_model(Permission) perm = Permission.objects.create(name='test', content_type=content_type, codename='test') # default django way (ManyToManyField) #user.user_permissions.add(perm) add_permission_to_user(perm, user) # reloading user to purge the _perm_cache user = User.objects.get(username='******') self.assertEqual(user.get_all_permissions() == set([u'auth.test']), True) self.assertEqual(user.get_group_permissions(), set([])) self.assertEqual(user.has_module_perms('Group'), False) self.assertEqual(user.has_module_perms('auth'), True) perm = Permission.objects.create(name='test2', content_type=content_type, codename='test2') # default django way (ManyToManyField) #user.user_permissions.add(perm) add_permission_to_user(perm, user) perm = Permission.objects.create(name='test3', content_type=content_type, codename='test3') # default django way (ManyToManyField) #user.user_permissions.add(perm) add_permission_to_user(perm, user) user = User.objects.get(username='******') self.assertEqual(user.get_all_permissions(), set([u'auth.test2', u'auth.test', u'auth.test3'])) self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perm('auth.test'), True) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), True) perm = Permission.objects.create(name='test_group', content_type=content_type, codename='test_group') group = Group.objects.create(name='test_group') # default django way (ManyToManyField) #group.permissions.add(perm) add_permission_to_group(perm, group) # default django way (ManyToManyField) #user.groups.add(group) add_user_to_group(user, group) user = User.objects.get(username='******') exp = set( [u'auth.test2', u'auth.test', u'auth.test3', u'auth.test_group']) self.assertEqual(user.get_all_permissions(), exp) self.assertEqual(user.get_group_permissions(), set([u'auth.test_group'])) self.assertEqual(user.has_perms(['auth.test3', 'auth.test_group']), True) user = AnonymousUser() self.assertEqual(user.has_perm('test'), False) self.assertEqual(user.has_perms(['auth.test2', 'auth.test3']), False)
def is_public(self): """ Returns True if anonymous (public) user can view map. """ user = AnonymousUser() return user.has_perm('maps.view_map', obj=self)