41 lines
1.5 KiB
Python
41 lines
1.5 KiB
Python
# custom auth backend to allow user to login with either username or email address
|
|
from django.db.models import Q
|
|
from django.contrib.auth import get_user_model
|
|
from rest_framework.authtoken.models import Token
|
|
|
|
user_obj = get_user_model()
|
|
print("\nUSER: " + (str(user_obj)) +'\n')
|
|
|
|
# called when making api attempts to authenticate users and create auth tokens
|
|
class Custom_Backend(object):
|
|
|
|
def authenticate(self, request, username=None, password=None, **kwargs):
|
|
try:
|
|
# Try to fetch the user by searching the username or email field
|
|
user = user_obj.objects.get(Q(username=username)|Q(email=username))
|
|
print("\nUSER: " + (str(user)) +'\n')
|
|
# if password was correct, authenticate using token auth
|
|
if user.check_password(password):
|
|
|
|
# create token for this user:
|
|
# first try to get this token (if the user's token was deleted somehow)
|
|
try:
|
|
print("\nttempting to get token for user\n")
|
|
token = Token.objects.get(user=user)
|
|
except:
|
|
print("\nToken doesn't exist for user, creating one\n")
|
|
token = Token.objects.create(user=user)
|
|
|
|
|
|
return user
|
|
except user_obj.DoesNotExist:
|
|
return None
|
|
|
|
# called when saving a new model obj
|
|
def get_user(self, user_id):
|
|
|
|
try:
|
|
return user_obj.objects.get(pk=user_id)
|
|
except user_obj.DoesNotExist:
|
|
return None
|
|
|