Skip to content

Commit

Permalink
Merge pull request #2519 from Ofir-Purple/optimize-token-auth-queries
Browse files Browse the repository at this point in the history
Prefetching the user object when getting the token in TokenAuthentication
  • Loading branch information
tomchristie committed Feb 4, 2015
2 parents 4618134 + 58e7bbc commit d21617f
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion rest_framework/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ def authenticate(self, request):

def authenticate_credentials(self, key):
try:
token = self.model.objects.get(key=key)
token = self.model.objects.select_related('user').get(key=key)
except self.model.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token')

Expand Down
6 changes: 6 additions & 0 deletions tests/test_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,12 @@ def test_post_json_passing_token_auth(self):
response = self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
self.assertEqual(response.status_code, status.HTTP_200_OK)

def test_post_json_makes_one_db_query(self):
"""Ensure that authenticating a user using a token performs only one DB query"""
auth = "Token " + self.key
func_to_test = lambda: self.csrf_client.post('/token/', {'example': 'example'}, format='json', HTTP_AUTHORIZATION=auth)
self.assertNumQueries(1, func_to_test)

def test_post_form_failing_token_auth(self):
"""Ensure POSTing form over token auth without correct credentials fails"""
response = self.csrf_client.post('/token/', {'example': 'example'})
Expand Down

0 comments on commit d21617f

Please sign in to comment.