| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import json |
| 4 |
from typing import Any |
| 5 |
|
| 6 |
from django.http import HttpRequest, HttpResponseBadRequest, HttpResponseBase |
| 7 |
from django.views.generic import View |
| 8 |
|
| 9 |
from allauth.core.exceptions import ImmediateHttpResponse |
| 10 |
from allauth.headless.internal.restkit.inputs import Input |
| 11 |
from allauth.headless.internal.restkit.response import ErrorResponse |
| 12 |
|
| 13 |
|
| 14 |
class RESTView(View): |
| 15 |
input_class: dict[str, type[Input]] | None | type[Input] = None |
| 16 |
handle_json_input = True |
| 17 |
|
| 18 |
def dispatch( |
| 19 |
self, request: HttpRequest, *args: Any, **kwargs: Any |
| 20 |
) -> HttpResponseBase: |
| 21 |
return self.handle(request, *args, **kwargs) |
| 22 |
|
| 23 |
def handle( |
| 24 |
self, request: HttpRequest, *args: Any, **kwargs: Any |
| 25 |
) -> HttpResponseBase: |
| 26 |
if self.handle_json_input and request.method != "GET": |
| 27 |
self.data = self._parse_json(request) |
| 28 |
response = self.handle_input(self.data) |
| 29 |
if response: |
| 30 |
return response |
| 31 |
return super().dispatch(request, *args, **kwargs) |
| 32 |
|
| 33 |
def get_input_class(self) -> type[Input] | None: |
| 34 |
input_class = self.input_class |
| 35 |
if isinstance(input_class, dict): |
| 36 |
input_class = input_class.get(self.request.method) # type:ignore[arg-type] |
| 37 |
return input_class |
| 38 |
|
| 39 |
def get_input_kwargs(self) -> dict: |
| 40 |
return {} |
| 41 |
|
| 42 |
def handle_input(self, data) -> ErrorResponse | None: |
| 43 |
input_class = self.get_input_class() |
| 44 |
if not input_class: |
| 45 |
return None |
| 46 |
input_kwargs = self.get_input_kwargs() |
| 47 |
if data is None: |
| 48 |
# Make form bound on empty POST |
| 49 |
data = {} |
| 50 |
self.input = input_class(data=data, **input_kwargs) |
| 51 |
if not self.input.is_valid(): |
| 52 |
return self.handle_invalid_input(self.input) |
| 53 |
return None |
| 54 |
|
| 55 |
def handle_invalid_input(self, input) -> ErrorResponse: |
| 56 |
return ErrorResponse(self.request, input=input) |
| 57 |
|
| 58 |
def _parse_json(self, request: HttpRequest): |
| 59 |
if request.method == "GET" or not request.body: |
| 60 |
return |
| 61 |
try: |
| 62 |
return json.loads(request.body.decode("utf8")) |
| 63 |
except (UnicodeDecodeError, json.JSONDecodeError): |
| 64 |
raise ImmediateHttpResponse(response=HttpResponseBadRequest()) |