| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from http import HTTPStatus |
| 4 |
from typing import Any |
| 5 |
|
| 6 |
from django.forms.utils import ErrorList |
| 7 |
from django.http import HttpRequest, JsonResponse |
| 8 |
from django.utils.cache import add_never_cache_headers |
| 9 |
|
| 10 |
from allauth.headless.internal import authkit, sessionkit |
| 11 |
|
| 12 |
|
| 13 |
class APIResponse(JsonResponse): |
| 14 |
def __init__( |
| 15 |
self, |
| 16 |
request: HttpRequest, |
| 17 |
errors=None, |
| 18 |
data=None, |
| 19 |
meta: dict | None = None, |
| 20 |
status: int = HTTPStatus.OK, |
| 21 |
) -> None: |
| 22 |
d: dict[str, Any] = {"status": status} |
| 23 |
if data is not None: |
| 24 |
d["data"] = data |
| 25 |
meta = self._add_session_meta(request, meta) |
| 26 |
if meta is not None: |
| 27 |
d["meta"] = meta |
| 28 |
if errors: |
| 29 |
d["errors"] = errors |
| 30 |
super().__init__(d, status=status) |
| 31 |
add_never_cache_headers(self) |
| 32 |
|
| 33 |
def _add_session_meta(self, request: HttpRequest, meta: dict | None) -> dict | None: |
| 34 |
session_token = sessionkit.expose_session_token(request) |
| 35 |
access_token_payload = authkit.expose_access_token(request) |
| 36 |
if session_token: |
| 37 |
meta = meta or {} |
| 38 |
meta["session_token"] = session_token |
| 39 |
if access_token_payload: |
| 40 |
meta = meta or {} |
| 41 |
meta.update(access_token_payload) |
| 42 |
return meta |
| 43 |
|
| 44 |
|
| 45 |
class ErrorResponse(APIResponse): |
| 46 |
def __init__( |
| 47 |
self, |
| 48 |
request: HttpRequest, |
| 49 |
exception=None, |
| 50 |
input=None, |
| 51 |
status=HTTPStatus.BAD_REQUEST, |
| 52 |
) -> None: |
| 53 |
errors = [] |
| 54 |
if exception is not None: |
| 55 |
error_datas = ErrorList(exception.error_list).get_json_data() |
| 56 |
errors.extend(error_datas) |
| 57 |
if input is not None: |
| 58 |
for field, error_list in input.errors.items(): |
| 59 |
error_datas = error_list.get_json_data() |
| 60 |
for error_data in error_datas: |
| 61 |
if field != "__all__": |
| 62 |
error_data["param"] = field |
| 63 |
errors.extend(error_datas) |
| 64 |
super().__init__(request, status=status, errors=errors) |