| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from http import HTTPStatus |
| 4 |
from typing import TYPE_CHECKING |
| 5 |
|
| 6 |
from django.http import HttpRequest, HttpResponseRedirect |
| 7 |
from django.shortcuts import render |
| 8 |
from django.urls import reverse |
| 9 |
|
| 10 |
from allauth import app_settings as allauth_settings |
| 11 |
from allauth.account import app_settings as account_settings |
| 12 |
from allauth.account.utils import user_display |
| 13 |
from allauth.core.exceptions import ImmediateHttpResponse |
| 14 |
from allauth.socialaccount import app_settings |
| 15 |
from allauth.socialaccount.adapter import get_adapter |
| 16 |
from allauth.socialaccount.internal import flows |
| 17 |
|
| 18 |
|
| 19 |
if TYPE_CHECKING: |
| 20 |
from allauth.socialaccount.models import SocialLogin |
| 21 |
|
| 22 |
from allauth.socialaccount.providers.base import AuthError |
| 23 |
|
| 24 |
|
| 25 |
def render_authentication_error( |
| 26 |
request: HttpRequest, |
| 27 |
provider, |
| 28 |
error=AuthError.UNKNOWN, |
| 29 |
exception=None, |
| 30 |
extra_context=None, |
| 31 |
): |
| 32 |
try: |
| 33 |
if extra_context is None: |
| 34 |
extra_context = {} |
| 35 |
get_adapter().on_authentication_error( |
| 36 |
request, |
| 37 |
provider, |
| 38 |
error=error, |
| 39 |
exception=exception, |
| 40 |
extra_context=extra_context, |
| 41 |
) |
| 42 |
if allauth_settings.HEADLESS_ENABLED: |
| 43 |
from allauth.headless.socialaccount import internal |
| 44 |
|
| 45 |
internal.on_authentication_error( |
| 46 |
request, |
| 47 |
provider=provider, |
| 48 |
error=error, |
| 49 |
exception=exception, |
| 50 |
extra_context=extra_context, |
| 51 |
) |
| 52 |
|
| 53 |
except ImmediateHttpResponse as e: |
| 54 |
return e.response |
| 55 |
if error == AuthError.CANCELLED: |
| 56 |
return HttpResponseRedirect(reverse("socialaccount_login_cancelled")) |
| 57 |
context = { |
| 58 |
"auth_error": { |
| 59 |
"provider": provider, |
| 60 |
"code": error, |
| 61 |
"exception": exception, |
| 62 |
} |
| 63 |
} |
| 64 |
context.update(extra_context) |
| 65 |
return render( |
| 66 |
request, |
| 67 |
f"socialaccount/authentication_error.{account_settings.TEMPLATE_EXTENSION}", |
| 68 |
context, |
| 69 |
status=HTTPStatus.UNAUTHORIZED, |
| 70 |
) |
| 71 |
|
| 72 |
|
| 73 |
def complete_social_login(request: HttpRequest, sociallogin: SocialLogin): |
| 74 |
if sociallogin.is_headless: |
| 75 |
from allauth.headless.socialaccount import internal |
| 76 |
|
| 77 |
return internal.complete_login(request, sociallogin) |
| 78 |
return flows.login.complete_login(request, sociallogin) |
| 79 |
|
| 80 |
|
| 81 |
def socialaccount_user_display(socialaccount) -> str: |
| 82 |
func = app_settings.SOCIALACCOUNT_STR |
| 83 |
if not func: |
| 84 |
return user_display(socialaccount.user) |
| 85 |
return func(socialaccount) |