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
3from django.contrib.auth import get_user_model
4from django.contrib.auth.backends import ModelBackend
6# Exports
8__all__ = (
9 "CaseInsensitiveModelBackend",
10 "EmailBackend",
11)
13# Backends
16class CaseInsensitiveModelBackend(ModelBackend):
17 """Validate a user with a username that ignores the case of the submitted user name.
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.
24 """
26 def authenticate(self, request, username=None, password=None, **kwargs):
27 """Authenticate with iexact."""
28 # noinspection PyPep8Naming
29 UserModel = get_user_model()
31 if username is None:
32 username = kwargs.get(UserModel.USERNAME_FIELD)
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
47class EmailBackend(object):
48 """Allow the user to authenticate using an email address.
50 .. code-block:: python
52 # settings.py
53 AUTHENTICATION_BACKENDS = [
54 'superdjango.accounts.backends.EmailBackend',
55 'django.contrib.auth.backends.ModelBackend',
56 ]
58 """
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()
66 if "@" in username:
67 try:
68 user = UserModel.objects.get(email__exact=username)
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
79 # noinspection PyMethodMayBeStatic
80 def get_user(self, user_id=None):
81 """Comply with backend API."""
82 # noinspection PyPep8Naming
83 UserModel = get_user_model()
85 try:
86 return UserModel.objects.get(pk=user_id)
87 except UserModel.DoesNotExist:
88 return None