Debian Codegraph @

allauth/account/auth_backends.py

raw
1 from __future__ import annotations
2
3 from threading import local
4
5 from django.contrib.auth import get_user_model
6 from django.contrib.auth.backends import ModelBackend
7 from django.contrib.auth.base_user import AbstractBaseUser
8 from django.http import HttpRequest
9
10 from allauth.account.adapter import get_adapter
11 from allauth.account.app_settings import LoginMethod
12
13 from . import app_settings
14 from .utils import filter_users_by_email, filter_users_by_username
15
16
17 _stash = local()
18
19
20 class AuthenticationBackend(ModelBackend):
21 def authenticate( # type: ignore[override]
22 self, request: HttpRequest | None, **credentials
23 ) -> AbstractBaseUser | None:
24 password = credentials.get("password")
25 if not password:
26 return None
27 self._did_check_password = False
28 user = self._authenticate(request, **credentials)
29 if not self._did_check_password:
30 self._mitigate_timing_attack(password)
31 return user
32
33 def _authenticate(
34 self, request: HttpRequest | None, **credentials
35 ) -> AbstractBaseUser | None:
36 username: str | None = credentials.get("username")
37 password: str = credentials.get("password") or ""
38 if username:
39 if LoginMethod.EMAIL in app_settings.LOGIN_METHODS:
40 # Username/email ambiguity: even though allauth will pass along
41 # `email` explicitly, other apps may not respect this. For example,
42 # when using django-tastypie basic authentication, the login is
43 # always passed as `username`. So let's play nice with other apps
44 # and use username as fallback.
45 user = self._authenticate_by_email(username, password)
46 if user:
47 return user
48 user = self._authenticate_by_username(username, password)
49 if user:
50 return user
51
52 email = credentials.get("email")
53 if email:
54 user = self._authenticate_by_email(email, password)
55 if user:
56 return user
57
58 phone = credentials.get("phone")
59 if phone:
60 user = self._authenticate_by_phone(phone, password)
61 if user:
62 return user
63 return None
64
65 def _authenticate_by_phone(
66 self, phone: str, password: str
67 ) -> AbstractBaseUser | None:
68 if not phone or LoginMethod.PHONE not in app_settings.LOGIN_METHODS:
69 return None
70 adapter = get_adapter()
71 user = adapter.get_user_by_phone(phone)
72 return self._check_password(user, password)
73
74 def _authenticate_by_username(
75 self, username: str, password: str
76 ) -> AbstractBaseUser | None:
77 if (
78 (LoginMethod.USERNAME not in app_settings.LOGIN_METHODS)
79 or (not app_settings.USER_MODEL_USERNAME_FIELD)
80 or not username
81 ):
82 return None
83 user = filter_users_by_username(username).first()
84 return self._check_password(user, password)
85
86 def _authenticate_by_email(
87 self,
88 email: str,
89 password: str,
90 ) -> AbstractBaseUser | None:
91 if not email or LoginMethod.EMAIL not in app_settings.LOGIN_METHODS:
92 return None
93 users = filter_users_by_email(email, prefer_verified=True)
94 for user in users:
95 if self._check_password(user, password):
96 return user
97 return None
98
99 def _mitigate_timing_attack(self, password) -> None:
100 get_user_model()().set_password(password)
101
102 def _check_password(
103 self, user: AbstractBaseUser | None, password: str
104 ) -> AbstractBaseUser | None:
105 if not user:
106 return None
107 self._did_check_password = True
108 ok = user.check_password(password)
109 if ok:
110 ok = self.user_can_authenticate(user) # type:ignore[arg-type]
111 if not ok:
112 self._stash_user(user)
113 return user if ok else None
114
115 @classmethod
116 def _stash_user(cls, user: AbstractBaseUser | None) -> AbstractBaseUser | None:
117 """Now, be aware, the following is quite ugly, let me explain:
118
119 Even if the user credentials match, the authentication can fail because
120 Django's default ModelBackend calls user_can_authenticate(), which
121 checks `is_active`. Now, earlier versions of allauth did not do this
122 and simply returned the user as authenticated, even in case of
123 `is_active=False`. For allauth scope, this does not pose a problem, as
124 these users are properly redirected to an account inactive page.
125
126 This does pose a problem when the allauth backend is used in a
127 different context where allauth is not responsible for the login. Then,
128 by not checking on `user_can_authenticate()` users will allow to become
129 authenticated whereas according to Django logic this should not be
130 allowed.
131
132 In order to preserve the allauth behavior while respecting Django's
133 logic, we stash a user for which the password check succeeded but
134 `user_can_authenticate()` failed. In the allauth authentication logic,
135 we can then unstash this user and proceed pointing the user to the
136 account inactive page.
137 """
138 global _stash # noqa: F824
139 ret = getattr(_stash, "user", None)
140 _stash.user = user
141 return ret
142
143 @classmethod
144 def unstash_authenticated_user(cls) -> AbstractBaseUser | None:
145 return cls._stash_user(None)