Fixed #22771 -- Fixed test.Client.logout when using custom auth backend.

This commit is contained in:
Xavier Fernandez 2014-06-06 11:19:16 +02:00 committed by Tim Graham
parent 4696cd9671
commit 50b9313e0a
3 changed files with 41 additions and 5 deletions

View File

@ -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)

View File

@ -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

View File

@ -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):