from django.contrib.auth import get_user_model

from .models import SingleUseToken

class PinBackend(object):
    """Authentication backend based on pin value."""
    def authenticate(self, request, email=None, pin=None):
        """Authenticate user based on valid pin."""
        user_model = get_user_model()
        kwargs = {
            user_model.USERNAME_FIELD: email
        }
        try:
            user = user_model.objects.get(**kwargs)
        except user_model.DoesNotExist:
            return None

        # Now that we have the user, check that we have a token
        try:
            token = self._get_token(user, pin)
        except SingleUseToken.DoesNotExist:
            return None

        if token.is_valid():
            # Read token (delete it)
            token.read()
            return user

    def _get_token(self, user, pin):
        """Get the token for corresponding user and pin."""
        return SingleUseToken.objects.get(user=user, token=pin)

@@ -271,120 +271,8 @@
 %22%22%22%0A
-        user_model = get_user_model()%0A        kwargs = %7B%0A            user_model.USERNAME_FIELD: email%0A        %7D%0A
     
@@ -296,46 +296,42 @@
     
-user
+token
  = 
-u
 se
-r_model.objects.get(**kwargs
+lf._get_token(email, pin
 )%0A  
@@ -343,26 +343,30 @@
  except 
-user_model
+SingleUseToken
 .DoesNot
@@ -409,102 +409,130 @@
     
-# Now that we have the user, check that we have a token%0A        try:%0A            token = self.
+if token.is_valid():%0A            # Read token (delete it)%0A            token.read()%0A            return token.user%0A%0A    def 
 _get
@@ -538,26 +538,34 @@
 t_token(
-u
 se
-r
+lf, email
 , pin)
+:
 %0A       
@@ -569,134 +569,175 @@
     
-except SingleUseToken.DoesNotExist:%0A            return None%0A%0A        if token.is_valid():%0A            # Read token (delete it)
+%22%22%22Get the token for corresponding user and pin.%22%22%22%0A        user_model = get_user_model()%0A        kwargs = %7B%0A            'user__%25s' %25 user_model.USERNAME_FIELD: email,
 %0A   
@@ -749,44 +749,82 @@
     
+'
 token
-.read()%0A            return user
+': pin%0A        %7D%0A        return SingleUseToken.objects.get(**kwargs)
 %0A%0A  
@@ -825,34 +825,32 @@
 s)%0A%0A    def 
-_
 get_
-token
+user
 (self, user,
@@ -848,21 +848,19 @@
 lf, user
-, pin
+_id
 ):%0A     
@@ -873,53 +873,80 @@
 Get 
-the token for corresponding user and pin.%22%22%22%0A
+user from id.%22%22%22%0A        user_model = get_user_model()%0A        try:%0A    
     
@@ -952,38 +952,34 @@
      return 
-SingleUseToken
+user_model
 .objects.get
@@ -983,26 +983,80 @@
 get(
+pk=
 user
-=user, token=pin)
+_id)%0A        except user_model.DoesNotExist:%0A            return None
 %0A

Refactor to query straight for user