diff --git a/django/test/client.py b/django/test/client.py index c1b05c0c51..1952af27eb 100644 --- a/django/test/client.py +++ b/django/test/client.py @@ -597,16 +597,13 @@ class Client(RequestFactory): Causes the authenticated user to be logged out. """ - from django.contrib.auth import get_user_model, logout + from django.contrib.auth import get_user, logout request = HttpRequest() engine = import_module(settings.SESSION_ENGINE) - UserModel = get_user_model() if self.session: request.session = self.session - uid = self.session.get("_auth_user_id") - if uid: - request.user = UserModel._default_manager.get(pk=uid) + request.user = get_user(request) else: request.session = engine.SessionStore() logout(request) diff --git a/tests/test_client_regress/auth_backends.py b/tests/test_client_regress/auth_backends.py new file mode 100644 index 0000000000..02a6d39611 --- /dev/null +++ b/tests/test_client_regress/auth_backends.py @@ -0,0 +1,20 @@ +from django.contrib.auth.backends import ModelBackend + +from .models import CustomUser + + +class CustomUserBackend(ModelBackend): + + def authenticate(self, username=None, password=None): + try: + user = CustomUser.custom_objects.get_by_natural_key(username) + if user.check_password(password): + return user + except CustomUser.DoesNotExist: + return None + + def get_user(self, user_id): + try: + return CustomUser.custom_objects.get(pk=user_id) + except CustomUser.DoesNotExist: + return None diff --git a/tests/test_client_regress/tests.py b/tests/test_client_regress/tests.py index f26adfc99a..71f6d18f24 100644 --- a/tests/test_client_regress/tests.py +++ b/tests/test_client_regress/tests.py @@ -1094,6 +1094,25 @@ class SessionTests(TestCase): user_logged_out.disconnect(listener) self.assertTrue(listener.executed) + @override_settings(AUTHENTICATION_BACKENDS=( + 'django.contrib.auth.backends.ModelBackend', + 'test_client_regress.auth_backends.CustomUserBackend')) + def test_logout_with_custom_auth_backend(self): + "Request a logout after logging in with custom authentication backend" + def listener(*args, **kwargs): + self.assertEqual(kwargs['sender'], CustomUser) + listener.executed = True + listener.executed = False + u = CustomUser.custom_objects.create(email='test@test.com') + u.set_password('password') + u.save() + + user_logged_out.connect(listener) + self.client.login(username='test@test.com', password='password') + self.client.logout() + user_logged_out.disconnect(listener) + self.assertTrue(listener.executed) + def test_logout_without_user(self): """Logout should send signal even if user not authenticated.""" def listener(user, *args, **kwargs):