我们从Python开源项目中,提取了以下7个代码示例,用于说明如何使用django.contrib.auth.backends.ModelBackend()。
def has_object_perm(self, user_obj, perm=None, obj=None): """ Validate permissions for the object specified. If there is not object should be validated before with the `contrib.auth.backends.ModelBackend`. Is required class permission to has permission over an object of the class. permissions: `change` `delete` `view` """ if not user_obj.is_active or user_obj.is_anonymous or not all([perm, obj]): return False # validation object permission obj_permission_label = '_has_perm_cache_{}_{}'.format(slugify(perm), obj.id) if not hasattr(user_obj, obj_permission_label): setattr(user_obj, obj_permission_label, self._has_object_permissions(user_obj, perm, obj)) return getattr(user_obj, obj_permission_label)
def test_it_is_a_model_backend(self): self.assertTrue( issubclass(FilteredModelBackend, ModelBackend), FilteredModelBackend.__mro__)
def authenticate(self, username, password, backend_cls=None): if not backend_cls: class EveryoneCanActAs(ActAsBackend): def can_act_as(self, auth_user, user): return True backend_cls = EveryoneCanActAs backend = backend_cls() with patched_get_backends([backend, ModelBackend()]): return auth_through_backend( backend, username=username, password=password)
def validate(self, attrs): username = attrs.get('username') password = attrs.get('password') if password and password: is_correct = bool(ModelBackend().authenticate(self.request, username=username, password=password)) if not is_correct: raise serializers.ValidationError('Incorrect login and password combination.') return attrs
def test_changed_backend_settings(self): """ Tests that removing a backend configured in AUTHENTICATION_BACKENDS make already logged-in users disconnect. """ # Get a session for the test user self.assertTrue(self.client.login( username=self.TEST_USERNAME, password=self.TEST_PASSWORD) ) # Prepare a request object request = HttpRequest() request.session = self.client.session # Remove NewModelBackend with self.settings(AUTHENTICATION_BACKENDS=( 'django.contrib.auth.backends.ModelBackend',)): # Get the user from the request user = get_user(request) # Assert that the user retrieval is successful and the user is # anonymous as the backend is not longer available. self.assertIsNotNone(user) self.assertTrue(user.is_anonymous())
def _upgrate_user_auth(self, user, raw_password): user.set_password(raw_password) user.backend = 'django.contrib.auth.backends.ModelBackend' user.save(update_fields=['password', 'backend'])
def login_password(request, username, password): """login_password(username, password): session_id""" backend = ModelBackend() user = backend.authenticate(username, password) if user is None: raise PermissionDenied("Invalid username or password.") user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) django.contrib.auth.login(request, user) return request.session.session_key # TODO: proxy_user