Debian Codegraph @

allauth/account/internal/flows/email_verification.py

raw
1 from __future__ import annotations
2
3 from django.contrib import messages
4 from django.contrib.auth.base_user import AbstractBaseUser
5 from django.http import HttpRequest, HttpResponse
6 from django.urls import reverse
7
8 from allauth.account import app_settings, signals
9 from allauth.account.adapter import get_adapter
10 from allauth.account.internal.flows.manage_email import (
11 emit_email_changed,
12 sync_email_address,
13 sync_user_email_address,
14 )
15 from allauth.account.internal.flows.signup import send_unknown_account_mail
16 from allauth.account.models import EmailAddress, Login
17 from allauth.core.exceptions import ImmediateHttpResponse
18 from allauth.core.internal import ratelimit
19 from allauth.core.internal.httpkit import get_frontend_url
20 from allauth.core.ratelimit import respond_429
21 from allauth.utils import build_absolute_uri
22
23
24 def verify_email_indirectly(
25 request: HttpRequest, user: AbstractBaseUser, email: str
26 ) -> bool:
27 try:
28 email_address = EmailAddress.objects.get_for_user(user, email)
29 except EmailAddress.DoesNotExist:
30 return False
31 else:
32 if not email_address.verified:
33 return verify_email(request, email_address)
34 return True
35
36
37 def verify_email_and_resume(
38 request: HttpRequest, verification
39 ) -> tuple[EmailAddress | None, HttpResponse | None]:
40 email_address = verification.confirm(request)
41 if not email_address:
42 return None, None
43 response = login_on_verification(request, email_address)
44 return email_address, response
45
46
47 def verify_email(request: HttpRequest, email_address: EmailAddress) -> bool:
48 """
49 Marks the email address as confirmed on the db
50 """
51 added = not email_address.pk
52 from_email_address = (
53 EmailAddress.objects.filter(user_id=email_address.user_id)
54 .exclude(pk=email_address.pk)
55 .first()
56 )
57 if not email_address.set_verified(commit=False):
58 get_adapter(request).add_message(
59 request,
60 messages.ERROR,
61 "account/messages/email_confirmation_failed.txt",
62 {"email": email_address.email},
63 )
64 return False
65 email_address.set_as_primary(conditional=(not app_settings.CHANGE_EMAIL))
66 email_address.save()
67 if added:
68 signals.email_added.send(
69 sender=EmailAddress,
70 request=request,
71 user=request.user,
72 email_address=email_address,
73 )
74 signals.email_confirmed.send(
75 sender=EmailAddress,
76 request=request,
77 email_address=email_address,
78 )
79 if app_settings.CHANGE_EMAIL:
80 for instance in EmailAddress.objects.filter(
81 user_id=email_address.user_id
82 ).exclude(pk=email_address.pk):
83 instance.remove()
84 emit_email_changed(request, from_email_address, email_address)
85 get_adapter(request).add_message(
86 request,
87 messages.SUCCESS,
88 "account/messages/email_confirmed.txt",
89 {"email": email_address.email},
90 )
91 return True
92
93
94 def get_email_verification_url(request: HttpRequest, emailconfirmation) -> str:
95 """Constructs the email confirmation (activation) url.
96
97 Note that if you have architected your system such that email
98 confirmations are sent outside of the request context `request`
99 can be `None` here.
100 """
101 url = get_frontend_url(request, "account_confirm_email", key=emailconfirmation.key)
102 if not url:
103 url = reverse("account_confirm_email", args=[emailconfirmation.key])
104 url = build_absolute_uri(request, url)
105 return url
106
107
108 def login_on_verification(request: HttpRequest, email_address) -> HttpResponse | None:
109 """Simply logging in the user may become a security issue. If you
110 do not take proper care (e.g. don't purge used email
111 confirmations), a malicious person that got hold of the link
112 will be able to login over and over again and the user is
113 unable to do anything about it. Even restoring their own mailbox
114 security will not help, as the links will still work. For
115 password reset this is different, this mechanism works only as
116 long as the attacker has access to the mailbox. If they no
117 longer has access they cannot issue a password request and
118 intercept it. Furthermore, all places where the links are
119 listed (log files, but even Google Analytics) all of a sudden
120 need to be secured. Purging the email confirmation once
121 confirmed changes the behavior -- users will not be able to
122 repeatedly confirm (in case they forgot that they already
123 clicked the mail).
124
125 All in all, we only login on verification when the user that is in the
126 process of signing up is present in the session to avoid all of the above.
127 This may not 100% work in case the user closes the browser (and the session
128 gets lost), but at least we're secure.
129 """
130 from allauth.account.stages import EmailVerificationStage, LoginStageController
131
132 stage = LoginStageController.enter(request, EmailVerificationStage.key)
133 if (
134 (
135 # Logging in on email verification is disabled...
136 not app_settings.LOGIN_ON_EMAIL_CONFIRMATION
137 # (but, that is only relevant for verification-by-link)
138 and not app_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED
139 )
140 or (request.user.is_authenticated)
141 or (not stage or not stage.login.user)
142 or (stage.login.user.pk != email_address.user_id)
143 ):
144 if stage:
145 stage.abort()
146 return None
147 return stage.exit()
148
149
150 def consume_email_verification_rate_limit(
151 request: HttpRequest,
152 email: str,
153 dry_run: bool = False,
154 raise_exception: bool = False,
155 ) -> bool:
156 return bool(
157 ratelimit.consume(
158 request,
159 config=app_settings.RATE_LIMITS,
160 action="confirm_email",
161 key=email.lower(),
162 dry_run=dry_run,
163 raise_exception=raise_exception,
164 limit_get=True,
165 )
166 )
167
168
169 def handle_verification_email_rate_limit(
170 request: HttpRequest, email: str, raise_exception: bool = False
171 ) -> bool:
172 """
173 For email verification by link, it is not an issue if the user runs into rate
174 limits. The reason is that the link is session independent. Therefore, if the
175 user hits rate limits, we can just silently skip sending additional
176 verification emails, as the previous emails that were already sent still
177 contain valid links. This is different from email verification by code. Here,
178 the session contains a specific code, meaning, silently skipping new
179 verification emails is not an option, and we must hard fail (429) instead. The
180 latter was missing, fixed.
181 """
182 rl_ok = consume_email_verification_rate_limit(
183 request, email, raise_exception=raise_exception
184 )
185 if not rl_ok and app_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED:
186 raise ImmediateHttpResponse(respond_429(request))
187 return rl_ok
188
189
190 def get_address_for_user(user: AbstractBaseUser) -> EmailAddress | None:
191 address = (
192 EmailAddress.objects.filter(user_id=user.pk)
193 .order_by("-primary", "-verified")
194 .first()
195 )
196 if not address:
197 address = sync_user_email_address(user)
198 return address
199
200
201 def get_address_for_login(login: Login) -> EmailAddress | None:
202 assert login.user # nosec
203 if login.email:
204 try:
205 return EmailAddress.objects.get_for_user(login.user, login.email)
206 except EmailAddress.DoesNotExist:
207 # We do have an email, it's not stored as an EmailAddress. Might be the
208 # case that a user was setup in the admin. So, let's sync
209 # EmailAddress'es on the fly here.
210 return sync_email_address(login.user, login.email)
211 else:
212 return get_address_for_user(login.user)
213
214
215 def send_verification_email_for_user(
216 request: HttpRequest, user: AbstractBaseUser
217 ) -> bool:
218 """
219 Used in the email-required-decorator.
220 """
221 address = get_address_for_user(user)
222 if not address:
223 return False
224 return send_verification_email_to_address(request, address)
225
226
227 def send_verification_email_to_address(
228 request: HttpRequest,
229 address: EmailAddress,
230 signup: bool = False,
231 process=None,
232 skip_enumeration_mails: bool = False,
233 ) -> bool:
234 """
235 Resend email verification for an existing email address.
236 """
237 if app_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED:
238 if not process:
239 from allauth.account.internal.flows.email_verification_by_code import (
240 EmailVerificationProcess,
241 )
242
243 process = EmailVerificationProcess.initiate(
244 request=request,
245 user=address.user if address.user_id else None,
246 email=address.email,
247 )
248 return process.did_send
249
250 send = handle_verification_email_rate_limit(
251 request,
252 address.email,
253 )
254 if not send:
255 return False
256
257 if not address.user_id:
258 if skip_enumeration_mails:
259 pass
260 elif signup:
261 get_adapter().send_account_already_exists_mail(address.email)
262 else:
263 send_unknown_account_mail(request, address.email)
264 confirmation = None
265 elif app_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED:
266 get_adapter().send_confirmation_mail(request, process, signup=signup)
267 confirmation = process
268 else:
269 confirmation = address.send_confirmation(request, signup=signup)
270 add_email_verification_sent_message(request, address.email, signup=signup)
271 if confirmation:
272 signals.email_confirmation_sent.send(
273 sender=confirmation.__class__,
274 request=request,
275 confirmation=confirmation,
276 signup=signup,
277 )
278 return True
279
280
281 def send_verification_email_at_login(request: HttpRequest, login: Login) -> bool:
282 """
283 At this point, it has already been confirmed that email verification
284 is needed.
285
286 Email verification mails are sent:
287 a) Explicitly: when a user signs up
288 b) Implicitly: when a user attempts to log in using an unverified
289 email while EMAIL_VERIFICATION is mandatory.
290 """
291 if not login.user:
292 sent = send_verification_email_at_fake_login(request, login)
293 else:
294 sent = send_verification_email_at_real_login(request, login)
295 return sent
296
297
298 def send_verification_email_at_real_login(request: HttpRequest, login: Login) -> bool:
299 assert login.user # nosec
300 address = get_address_for_login(login)
301 if not address:
302 return False
303 if address.verified:
304 return False
305 send = get_adapter().should_send_confirmation_mail(request, address, login.signup)
306 if not send:
307 return False
308 return send_verification_email_to_address(request, address, signup=login.signup)
309
310
311 def send_verification_email_at_fake_login(request: HttpRequest, login: Login) -> bool:
312 """
313 Enumeration prevention.
314 """
315 assert not login.user # nosec
316 if not login.email:
317 # Odd, no user & no email implies email enumeration prevention is
318 # active, at signup, which implies we should have an email here?
319 return False
320 address = EmailAddress(user=None, email=login.email)
321 return send_verification_email_to_address(request, address, signup=True)
322
323
324 def add_email_verification_sent_message(
325 request: HttpRequest, email: str, signup: bool
326 ) -> None:
327 get_adapter().add_message(
328 request,
329 messages.INFO,
330 "account/messages/email_confirmation_sent.txt",
331 {"email": email, "login": not signup, "signup": signup},
332 )
333
334
335 def is_verification_rate_limited(request: HttpRequest, login: Login) -> bool:
336 """
337 Returns whether or not the email verification is *hard* rate limited.
338 Hard, meaning, it would be blocking login (verification by code, not link).
339 """
340 if (
341 (not login.email)
342 or (not login.user)
343 or (not app_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED)
344 or login.email_verification != app_settings.EmailVerificationMethod.MANDATORY
345 ):
346 return False
347 try:
348 email_address = EmailAddress.objects.get_for_user(login.user, login.email)
349 if not email_address.verified:
350 if not consume_email_verification_rate_limit(
351 request, login.email, dry_run=True
352 ):
353 return True
354 except EmailAddress.DoesNotExist:
355 pass
356 return False
357
358
359 def mark_email_address_as_verified(
360 request: HttpRequest, address: EmailAddress
361 ) -> EmailAddress | None:
362 if not address.verified:
363 confirmed = get_adapter().confirm_email(request, address)
364 if confirmed:
365 return address
366 return None