Debian Codegraph @

allauth/account/internal/flows/login.py

raw
1 from __future__ import annotations
2
3 import time
4 from typing import Any
5
6 from django.core import exceptions, validators
7 from django.http import HttpRequest, HttpResponse
8
9 from allauth import app_settings as allauth_settings
10 from allauth.account import app_settings
11 from allauth.account.adapter import get_adapter
12 from allauth.account.app_settings import LoginMethod
13 from allauth.account.models import Login
14 from allauth.account.signals import authentication_step_completed
15 from allauth.core.exceptions import ImmediateHttpResponse
16
17
18 AUTHENTICATION_METHODS_SESSION_KEY = "account_authentication_methods"
19
20
21 def record_authentication(
22 request: HttpRequest, user, method: str, **extra_data
23 ) -> None:
24 """Here we keep a log of all authentication methods used within the current
25 session. Important to note is that having entries here does not imply that
26 a user is fully signed in. For example, consider a case where a user
27 authenticates using a password, but fails to complete the 2FA challenge.
28 Or, a user successfully signs in into an inactive account or one that still
29 needs verification. In such cases, ``request.user`` is still anonymous, yet,
30 we do have an entry here.
31
32 Example data::
33
34 {'method': 'password',
35 'at': 1701423602.7184925,
36 'username': 'john.doe'}
37
38 {'method': 'socialaccount',
39 'at': 1701423567.6368647,
40 'provider': 'amazon',
41 'uid': 'amzn1.account.K2LI23KL2LK2'}
42
43 {'method': 'mfa',
44 'at': 1701423602.6392953,
45 'id': 1,
46 'type': 'totp'}
47
48 """
49 methods = request.session.get(AUTHENTICATION_METHODS_SESSION_KEY, [])
50 data = {
51 "method": method,
52 "at": time.time(),
53 }
54 for k, v in extra_data.items():
55 if v is not None:
56 data[k] = v
57 methods.append(data)
58 request.session[AUTHENTICATION_METHODS_SESSION_KEY] = methods
59 authentication_step_completed.send(
60 sender=user.__class__, request=request, method=method, user=user, **extra_data
61 )
62
63
64 def _get_login_hook_kwargs(login: Login) -> dict[str, Any]:
65 """
66 TODO: Just break backwards compatibility and pass only `login` to
67 `pre/post_login()`.
68 """
69 return dict(
70 email_verification=login.email_verification,
71 redirect_url=login.redirect_url,
72 signal_kwargs=login.signal_kwargs,
73 signup=login.signup,
74 email=login.email,
75 )
76
77
78 def perform_password_login(
79 request: HttpRequest, credentials: dict[str, Any], login: Login
80 ) -> HttpResponse:
81 extra_data = {
82 field: credentials.get(field)
83 for field in ["email", "username"]
84 if credentials.get(field)
85 }
86 record_authentication(request, login.user, method="password", **extra_data)
87 return perform_login(request, login)
88
89
90 def perform_login(request: HttpRequest, login: Login) -> HttpResponse:
91 adapter = get_adapter()
92 hook_kwargs = _get_login_hook_kwargs(login)
93 if login.user:
94 response = adapter.pre_login(request, login.user, **hook_kwargs)
95 if response:
96 return response
97 return resume_login(request, login)
98
99
100 def resume_login(request: HttpRequest, login: Login) -> HttpResponse:
101 from allauth.account.stages import LoginStageController
102
103 adapter = get_adapter()
104 ctrl = LoginStageController(request, login)
105 response: HttpResponse
106 try:
107 response = ctrl.handle()
108 if response:
109 return response
110 user = login.user
111 assert user # nosec
112 adapter.login(request, user)
113 hook_kwargs = _get_login_hook_kwargs(login)
114 response = adapter.post_login(request, user, **hook_kwargs)
115 if response:
116 return response
117 except ImmediateHttpResponse as e:
118 if allauth_settings.HEADLESS_ENABLED:
119 from allauth.headless.internal.restkit.response import APIResponse
120
121 if isinstance(e.response, APIResponse):
122 raise e
123 response = e.response
124 return response
125
126
127 def is_login_rate_limited(request: HttpRequest, login: Login) -> bool:
128 from allauth.account.internal.flows.email_verification import (
129 is_verification_rate_limited,
130 )
131
132 if is_verification_rate_limited(request, login):
133 return True
134 return False
135
136
137 def derive_login_method(login: str) -> LoginMethod:
138 if len(app_settings.LOGIN_METHODS) == 1:
139 return next(iter(app_settings.LOGIN_METHODS))
140 if LoginMethod.EMAIL in app_settings.LOGIN_METHODS:
141 try:
142 validators.validate_email(login)
143 return LoginMethod.EMAIL
144 except exceptions.ValidationError:
145 pass
146 if LoginMethod.PHONE in app_settings.LOGIN_METHODS:
147 try:
148 get_adapter().phone_form_field(required=True).clean(login)
149 return LoginMethod.PHONE
150 except exceptions.ValidationError:
151 pass
152 return LoginMethod.USERNAME