| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.http import HttpRequest |
| 4 |
|
| 5 |
from allauth.account import app_settings as account_settings |
| 6 |
from allauth.account.internal.constants import LoginStageKey as AccountLoginStageKey |
| 7 |
from allauth.account.stages import LoginStage |
| 8 |
from allauth.core.internal.httpkit import headed_redirect_response, is_headless_request |
| 9 |
from allauth.mfa import app_settings |
| 10 |
from allauth.mfa.internal.constants import LoginStageKey |
| 11 |
from allauth.mfa.internal.flows import trust |
| 12 |
from allauth.mfa.models import Authenticator |
| 13 |
from allauth.mfa.utils import is_mfa_enabled |
| 14 |
from allauth.mfa.webauthn.internal.flows import did_use_passwordless_login |
| 15 |
|
| 16 |
|
| 17 |
class AuthenticateStage(LoginStage): |
| 18 |
key = LoginStageKey.MFA_AUTHENTICATE.value |
| 19 |
urlname = "mfa_authenticate" |
| 20 |
|
| 21 |
def handle(self) -> tuple: |
| 22 |
response, cont = None, True |
| 23 |
if self._should_handle(self.request): |
| 24 |
self.state["authentication_required"] = True |
| 25 |
response = headed_redirect_response("mfa_authenticate") |
| 26 |
return response, cont |
| 27 |
|
| 28 |
def _should_handle(self, request: HttpRequest) -> bool: |
| 29 |
if self.login.user is None: |
| 30 |
return False |
| 31 |
if not is_mfa_enabled( |
| 32 |
self.login.user, [Authenticator.Type.TOTP, Authenticator.Type.WEBAUTHN] |
| 33 |
): |
| 34 |
return False |
| 35 |
if did_use_passwordless_login(request): |
| 36 |
return False |
| 37 |
if trust.is_trusted_browser(request, self.login.user): |
| 38 |
return False |
| 39 |
return True |
| 40 |
|
| 41 |
|
| 42 |
class TrustStage(LoginStage): |
| 43 |
key = LoginStageKey.MFA_TRUST.value |
| 44 |
urlname = "mfa_trust" |
| 45 |
|
| 46 |
def handle(self) -> tuple: |
| 47 |
lbc_stage = self.controller.get_stage(AccountLoginStageKey.LOGIN_BY_CODE) |
| 48 |
auth_stage = self.controller.get_stage(AuthenticateStage.key) |
| 49 |
|
| 50 |
if ( |
| 51 |
not app_settings.TRUST_ENABLED |
| 52 |
or not auth_stage |
| 53 |
or not auth_stage.state.get("authentication_required") |
| 54 |
) and ( |
| 55 |
not account_settings.LOGIN_BY_CODE_TRUST_ENABLED |
| 56 |
or not lbc_stage |
| 57 |
or not lbc_stage.state.get("login_by_code_required") |
| 58 |
): |
| 59 |
return None, True |
| 60 |
client = is_headless_request(self.request) |
| 61 |
if client and client == "app": |
| 62 |
# Trust-this-browser relies on cookies. |
| 63 |
return None, True |
| 64 |
response = headed_redirect_response("mfa_trust") |
| 65 |
return response, True |