Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1# Imports 

2 

3from django.contrib.auth import get_user_model 

4from django.contrib.auth.backends import ModelBackend 

5 

6# Exports 

7 

8__all__ = ( 

9 "CaseInsensitiveModelBackend", 

10 "EmailBackend", 

11) 

12 

13# Backends 

14 

15 

16class CaseInsensitiveModelBackend(ModelBackend): 

17 """Validate a user with a username that ignores the case of the submitted user name. 

18 

19 .. warning:: 

20 Use this backend with caution. While it allows a user to authenticate with a case-insensitive variation of his 

21 or her user name, it can produce errors (``MultipleObjectsExist``, for example) if you don't also check for 

22 case-insensitive user names upon user account creation. 

23 

24 """ 

25 

26 def authenticate(self, request, username=None, password=None, **kwargs): 

27 """Authenticate with iexact.""" 

28 # noinspection PyPep8Naming 

29 UserModel = get_user_model() 

30 

31 if username is None: 

32 username = kwargs.get(UserModel.USERNAME_FIELD) 

33 

34 try: 

35 case_insensitive_username_field = '{}__iexact'.format(UserModel.USERNAME_FIELD) 

36 # noinspection PyProtectedMember 

37 user = UserModel._default_manager.get(**{case_insensitive_username_field: username}) 

38 except UserModel.DoesNotExist: 

39 # Run the default password hasher once to reduce the timing 

40 # difference between an existing and a non-existing user (#20760). 

41 UserModel().set_password(password) 

42 else: 

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

44 return user 

45 

46 

47class EmailBackend(object): 

48 """Allow the user to authenticate using an email address. 

49 

50 .. code-block:: python 

51 

52 # settings.py 

53 AUTHENTICATION_BACKENDS = [ 

54 'superdjango.accounts.backends.EmailBackend', 

55 'django.contrib.auth.backends.ModelBackend', 

56 ] 

57 

58 """ 

59 

60 # noinspection PyMethodMayBeStatic,PyUnusedLocal 

61 def authenticate(self, username=None, password=None, **kwargs): 

62 """Authenticate against an email address.""" 

63 # noinspection PyPep8Naming 

64 UserModel = get_user_model() 

65 

66 if "@" in username: 

67 try: 

68 user = UserModel.objects.get(email__exact=username) 

69 

70 if user.check_password(password): 

71 return user 

72 else: 

73 return None 

74 except UserModel.DoesNotExist: 

75 return None 

76 else: 

77 return None 

78 

79 # noinspection PyMethodMayBeStatic 

80 def get_user(self, user_id=None): 

81 """Comply with backend API.""" 

82 # noinspection PyPep8Naming 

83 UserModel = get_user_model() 

84 

85 try: 

86 return UserModel.objects.get(pk=user_id) 

87 except UserModel.DoesNotExist: 

88 return None