from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend from django.contrib.auth.hashers import check_password from goodtimes import constants from .models import IAmPrincipalOtp class EmailBackend(ModelBackend): """ Custom Authentication Backend for Email and Password Authentication. It extends Django's built-in 'ModelBackend' Methods: - authenticate(self, request, email=None, password=None, **kwargs): Authenticate a user. - get_user(self, user_id): Retrive a user by their user ID. Example: ``` # Authenticate a user using their email and password user = EmailBackend.authenticate(request, email='user@example.com', password='password123') if user: # Authentication successful, user is logged in. else: # Authentication failed, user is not logged in. ``` """ UserModel = get_user_model() def authenticate(self, email=None, password=None, **kwargs): # Use a case-insensitive query for the email field try: user = self.UserModel.objects.get(email__iexact=email) except self.UserModel.DoesNotExist: return None # Use the user's `check_password` method to verify the password if user.check_password(password): return user return None def get_user(self, user_id): try: return self.UserModel.objects.get(pk=user_id) except self.UserModel.DoesNotExist: return None