| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from functools import wraps |
| 4 |
|
| 5 |
from django.contrib import messages |
| 6 |
from django.contrib.auth.base_user import AbstractBaseUser |
| 7 |
from django.core.exceptions import ValidationError |
| 8 |
from django.http import HttpRequest, HttpResponseRedirect |
| 9 |
from django.urls import reverse |
| 10 |
|
| 11 |
from allauth.account.adapter import get_adapter as get_account_adapter |
| 12 |
from allauth.account.models import EmailAddress |
| 13 |
from allauth.mfa import app_settings |
| 14 |
from allauth.mfa.adapter import get_adapter |
| 15 |
|
| 16 |
|
| 17 |
def validate_can_add_authenticator(user: AbstractBaseUser) -> None: |
| 18 |
""" |
| 19 |
If we would allow users to enable 2FA with unverified email address, |
| 20 |
that would allow for an attacker to signup, not verify and prevent the real |
| 21 |
owner of the account from ever regaining access. |
| 22 |
""" |
| 23 |
if app_settings.ALLOW_UNVERIFIED_EMAIL: |
| 24 |
return |
| 25 |
email_verified = not EmailAddress.objects.filter( |
| 26 |
user_id=user.pk, verified=False |
| 27 |
).exists() |
| 28 |
if not email_verified: |
| 29 |
raise get_adapter().validation_error("unverified_email") |
| 30 |
|
| 31 |
|
| 32 |
def redirect_if_add_not_allowed(function=None): |
| 33 |
def decorator(view_func): |
| 34 |
@wraps(view_func) |
| 35 |
def _wrapper_view(request: HttpRequest, *args, **kwargs): |
| 36 |
if request.user.is_authenticated: # allow for this to go before reauth |
| 37 |
try: |
| 38 |
validate_can_add_authenticator(request.user) |
| 39 |
except ValidationError as e: |
| 40 |
for message in e.messages: |
| 41 |
adapter = get_account_adapter() |
| 42 |
adapter.add_message(request, messages.ERROR, message=message) |
| 43 |
return HttpResponseRedirect(reverse("mfa_index")) |
| 44 |
return view_func(request, *args, **kwargs) |
| 45 |
|
| 46 |
return _wrapper_view |
| 47 |
|
| 48 |
if function: |
| 49 |
return decorator(function) |
| 50 |
return decorator |