Coverage for src/accounts/authentication.py: 100%

13 statements  

« prev     ^ index     » next       coverage.py v7.9.2, created at 2025-08-04 12:59 +0300

1""" 

2CustomAuthBackendBackend: 

3- Allows authentication with email OR username 

4""" 

5 

6from django.contrib.auth.backends import ModelBackend 

7from django.contrib.auth import get_user_model 

8from django.db.models import Q 

9 

10UserModel = get_user_model() 

11 

12 

13class CustomAuthBackendBackend(ModelBackend): 

14 def authenticate( 

15 self, request=None, username=None, password=None, **kwargs 

16 ): 

17 try: 

18 # Try to find a user with the provided username/email 

19 user = UserModel.objects.get( 

20 Q(email__iexact=username) | Q(username__iexact=username) 

21 ) 

22 

23 except UserModel.DoesNotExist: 

24 # This indicates authentication failure 

25 return None 

26 

27 # check_password() compares the provided password with the stored hash 

28 # user_can_authenticate() checks if the user is active and not blocked 

29 if user.check_password(password) and self.user_can_authenticate(user): 

30 # Return the authenticated user object 

31 return user 

32 

33 # Return None if password is incorrect or user cannot authenticate 

34 return None