force_authenticate(None) also clears session info.

Closes #1055.
This commit is contained in:
Tom Christie 2013-08-23 11:21:45 +01:00
parent b8561f4123
commit 19a774f972
3 changed files with 33 additions and 0 deletions

View File

@ -44,6 +44,7 @@ You can determine your currently installed version using `pip freeze`:
* Support customizable view name and description functions, using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings. * Support customizable view name and description functions, using the `VIEW_NAME_FUNCTION` and `VIEW_DESCRIPTION_FUNCTION` settings.
* Bugfix: `required=True` argument fixed for boolean serializer fields. * Bugfix: `required=True` argument fixed for boolean serializer fields.
* Bugfix: `client.force_authenticate(None)` should also clear session info if it exists.
### 2.3.7 ### 2.3.7

View File

@ -134,6 +134,8 @@ class APIClient(APIRequestFactory, DjangoClient):
""" """
self.handler._force_user = user self.handler._force_user = user
self.handler._force_token = token self.handler._force_token = token
if user is None:
self.logout() # Also clear any possible session info if required
def request(self, **kwargs): def request(self, **kwargs):
# Ensure that any credentials set get added to every request. # Ensure that any credentials set get added to every request.

View File

@ -17,8 +17,18 @@ def view(request):
}) })
@api_view(['GET', 'POST'])
def session_view(request):
active_session = request.session.get('active_session', False)
request.session['active_session'] = True
return Response({
'active_session': active_session
})
urlpatterns = patterns('', urlpatterns = patterns('',
url(r'^view/$', view), url(r'^view/$', view),
url(r'^session-view/$', session_view),
) )
@ -46,6 +56,26 @@ class TestAPITestClient(TestCase):
response = self.client.get('/view/') response = self.client.get('/view/')
self.assertEqual(response.data['user'], 'example') self.assertEqual(response.data['user'], 'example')
def test_force_authenticate_with_sessions(self):
"""
Setting `.force_authenticate()` forcibly authenticates each request.
"""
user = User.objects.create_user('example', 'example@example.com')
self.client.force_authenticate(user)
# First request does not yet have an active session
response = self.client.get('/session-view/')
self.assertEqual(response.data['active_session'], False)
# Subsequant requests have an active session
response = self.client.get('/session-view/')
self.assertEqual(response.data['active_session'], True)
# Force authenticating as `None` should also logout the user session.
self.client.force_authenticate(None)
response = self.client.get('/session-view/')
self.assertEqual(response.data['active_session'], False)
def test_csrf_exempt_by_default(self): def test_csrf_exempt_by_default(self):
""" """
By default, the test client is CSRF exempt. By default, the test client is CSRF exempt.