Debian Codegraph @

allauth/headless/internal/decorators.py

raw
1 from __future__ import annotations
2
3 from functools import wraps
4 from types import SimpleNamespace
5 from typing import Any
6
7 from django.http import HttpRequest
8 from django.middleware.csrf import get_token
9 from django.views.decorators.csrf import csrf_exempt
10
11 from allauth.account.internal.decorators import login_not_required
12 from allauth.headless.constants import Client
13 from allauth.headless.internal import authkit
14
15
16 def mark_request_as_headless(request: HttpRequest, client: Client) -> None:
17 request.allauth.headless = SimpleNamespace() # type: ignore[attr-defined]
18 request.allauth.headless.client = client # type: ignore[attr-defined]
19
20
21 def app_view(
22 function=None,
23 ):
24 def decorator(view_func):
25 @login_not_required
26 @wraps(view_func)
27 def _wrapper_view(request: HttpRequest, *args: Any, **kwargs: Any):
28 mark_request_as_headless(request, Client.APP)
29 with authkit.authentication_context(request):
30 return view_func(request, *args, **kwargs)
31
32 return _wrapper_view
33
34 ret = decorator
35 if function:
36 ret = decorator(function)
37 return csrf_exempt(ret)
38
39
40 def browser_view(
41 function=None,
42 ):
43 def decorator(view_func):
44 @login_not_required
45 @wraps(view_func)
46 def _wrapper_view(request: HttpRequest, *args: Any, **kwargs: Any):
47 mark_request_as_headless(request, Client.BROWSER)
48 # Needed -- so that the CSRF token is set in the response for the
49 # frontend to pick up.
50 get_token(request)
51 return view_func(request, *args, **kwargs)
52
53 return _wrapper_view
54
55 ret = decorator
56 if function:
57 ret = decorator(function)
58 return ret