Debian Codegraph @

allauth/headless/base/response.py

raw
1 from __future__ import annotations
2
3 from http import HTTPStatus
4
5 from django.http import HttpRequest
6
7 from allauth import app_settings as allauth_settings
8 from allauth.account import app_settings as account_settings
9 from allauth.account.adapter import get_adapter as get_account_adapter
10 from allauth.account.app_settings import LoginMethod
11 from allauth.account.authentication import get_authentication_records
12 from allauth.account.internal import flows
13 from allauth.account.internal.stagekit import LOGIN_SESSION_KEY
14 from allauth.headless.adapter import get_adapter
15 from allauth.headless.constants import Flow
16 from allauth.headless.internal import authkit
17 from allauth.headless.internal.restkit.response import APIResponse
18 from allauth.mfa import app_settings as mfa_settings
19
20
21 class BaseAuthenticationResponse(APIResponse):
22 def __init__(self, request: HttpRequest, user=None, status=None) -> None:
23 data: dict = {}
24 if user and user.is_authenticated:
25 adapter = get_adapter()
26 data["user"] = adapter.serialize_user(user)
27 data["methods"] = get_authentication_records(request)
28 status = status or HTTPStatus.OK
29 else:
30 status = status or HTTPStatus.UNAUTHORIZED
31 if status != HTTPStatus.OK:
32 data["flows"] = self._get_flows(request, user)
33 meta = {
34 "is_authenticated": user and user.is_authenticated,
35 }
36 super().__init__(
37 request,
38 data=data,
39 meta=meta,
40 status=status,
41 )
42
43 def _get_flows(self, request: HttpRequest, user) -> list:
44 auth_status = authkit.AuthenticationStatus(request)
45 ret = []
46 if user and user.is_authenticated:
47 ret.extend(flows.reauthentication.get_reauthentication_flows(user))
48 else:
49 if not allauth_settings.SOCIALACCOUNT_ONLY:
50 ret.append({"id": Flow.LOGIN})
51 if account_settings.LOGIN_BY_CODE_ENABLED:
52 ret.append({"id": Flow.LOGIN_BY_CODE})
53 if (
54 get_account_adapter().is_open_for_signup(request)
55 and not allauth_settings.SOCIALACCOUNT_ONLY
56 ):
57 ret.append({"id": Flow.SIGNUP})
58 if allauth_settings.SOCIALACCOUNT_ENABLED:
59 from allauth.headless.socialaccount.response import provider_flows
60
61 ret.extend(provider_flows(request))
62 if allauth_settings.MFA_ENABLED:
63 if mfa_settings.PASSKEY_LOGIN_ENABLED:
64 ret.append({"id": Flow.MFA_LOGIN_WEBAUTHN})
65 stage_key = None
66 stage = auth_status.get_pending_stage()
67 if stage:
68 stage_key = stage.key
69 else:
70 lsk = request.session.get(LOGIN_SESSION_KEY)
71 if isinstance(lsk, str):
72 stage_key = lsk
73 if stage_key:
74 pending_flow = {"id": stage_key, "is_pending": True}
75 if stage and stage_key == Flow.MFA_AUTHENTICATE:
76 self._enrich_mfa_flow(stage, pending_flow)
77 self._upsert_pending_flow(ret, pending_flow)
78
79 if (
80 not allauth_settings.SOCIALACCOUNT_ONLY
81 and account_settings.PASSWORD_RESET_BY_CODE_ENABLED
82 ):
83 from allauth.account.internal.flows import password_reset_by_code
84
85 ret.append(
86 {
87 "id": Flow.PASSWORD_RESET_BY_CODE,
88 "is_pending": bool(
89 password_reset_by_code.PasswordResetVerificationProcess.resume(
90 request
91 )
92 ),
93 }
94 )
95 return ret
96
97 def _upsert_pending_flow(self, flows, pending_flow) -> None:
98 flow = next((flow for flow in flows if flow["id"] == pending_flow["id"]), None)
99 if flow:
100 flow.update(pending_flow)
101 else:
102 flows.append(pending_flow)
103
104 def _enrich_mfa_flow(self, stage, flow: dict) -> None:
105 from allauth.mfa.adapter import get_adapter as get_mfa_adapter
106 from allauth.mfa.models import Authenticator
107
108 adapter = get_mfa_adapter()
109 types = []
110 for typ in Authenticator.Type:
111 if adapter.is_mfa_enabled(stage.login.user, types=[typ]):
112 types.append(typ)
113 flow["types"] = types
114
115
116 class AuthenticationResponse(BaseAuthenticationResponse):
117 def __init__(self, request: HttpRequest) -> None:
118 super().__init__(request, user=request.user)
119
120 @classmethod
121 def from_response(cls, request: HttpRequest, response) -> AuthenticationResponse:
122 """
123 The response might be a headed redirect to e.g. the confirmation
124 email page, because allauth.account is not (much) headless
125 aware. Also, what if an adapter method return headed responses in
126 post_login()? So, let's ensure we always return a headless
127 response.
128 """
129 if isinstance(response, AuthenticationResponse):
130 return response
131 return AuthenticationResponse(request)
132
133
134 class ReauthenticationResponse(BaseAuthenticationResponse):
135 def __init__(self, request: HttpRequest) -> None:
136 super().__init__(request, user=request.user, status=HTTPStatus.UNAUTHORIZED)
137
138
139 class UnauthorizedResponse(BaseAuthenticationResponse):
140 def __init__(self, request: HttpRequest, status=HTTPStatus.UNAUTHORIZED) -> None:
141 super().__init__(request, user=None, status=status)
142
143
144 class ForbiddenResponse(APIResponse):
145 def __init__(self, request: HttpRequest) -> None:
146 super().__init__(request, status=HTTPStatus.FORBIDDEN)
147
148
149 class ConflictResponse(APIResponse):
150 def __init__(self, request: HttpRequest) -> None:
151 super().__init__(request, status=HTTPStatus.CONFLICT)
152
153
154 def get_config_data(request: HttpRequest) -> dict:
155 login_methods = account_settings.LOGIN_METHODS
156 data = {
157 "login_methods": list(login_methods),
158 "is_open_for_signup": get_account_adapter().is_open_for_signup(request),
159 "email_verification_by_code_enabled": account_settings.EMAIL_VERIFICATION_BY_CODE_ENABLED,
160 "login_by_code_enabled": account_settings.LOGIN_BY_CODE_ENABLED,
161 "password_reset_by_code_enabled": account_settings.PASSWORD_RESET_BY_CODE_ENABLED,
162 }
163 # NOTE: For backwards compatibility only.
164 if LoginMethod.EMAIL in login_methods and LoginMethod.USERNAME in login_methods:
165 data["authentication_method"] = "username_email"
166 elif LoginMethod.EMAIL in login_methods:
167 data["authentication_method"] = "email"
168 elif LoginMethod.USERNAME in login_methods:
169 data["authentication_method"] = "username"
170 # (end NOTE)
171 return {"account": data}
172
173
174 class ConfigResponse(APIResponse):
175 def __init__(self, request: HttpRequest) -> None:
176 data = get_config_data(request)
177 if allauth_settings.SOCIALACCOUNT_ENABLED:
178 from allauth.headless.socialaccount.response import (
179 get_config_data as get_socialaccount_config_data,
180 )
181
182 data.update(get_socialaccount_config_data(request))
183 if allauth_settings.MFA_ENABLED:
184 from allauth.headless.mfa.response import (
185 get_config_data as get_mfa_config_data,
186 )
187
188 data.update(get_mfa_config_data(request))
189 if allauth_settings.USERSESSIONS_ENABLED:
190 from allauth.headless.usersessions.response import (
191 get_config_data as get_usersessions_config_data,
192 )
193
194 data.update(get_usersessions_config_data(request))
195 return super().__init__(request, data=data)
196
197
198 class RateLimitResponse(APIResponse):
199 def __init__(self, request: HttpRequest) -> None:
200 super().__init__(request, status=HTTPStatus.TOO_MANY_REQUESTS)