|
| 1 | +"""``POST /api/v1/<app>/<model>/<pk>/action/<name>/`` — run an object action. |
| 2 | +
|
| 3 | +Wire contract: ``docs/api-contract.md`` §5 (an addition the human reviewer |
| 4 | +must land — see the PR/report note). |
| 5 | +
|
| 6 | +Object-level change-page actions are the django-object-actions affordance |
| 7 | +(``ModelAdmin.change_actions`` / ``get_change_actions``). This endpoint |
| 8 | +runs one named action against a single object. It is the per-object |
| 9 | +counterpart to the changelist ``actions`` runner (``views/actions.py``); |
| 10 | +both never trust the client-supplied name as a callable lookup. |
| 11 | +
|
| 12 | +Hard rules (`SECURITY.md` §3, `ACCEPTANCE.md` §3.1): |
| 13 | +
|
| 14 | +- Rule 1: Staff + ``AdminSite.has_permission`` gate. |
| 15 | +- Rule 3: Model resolved through ``admin.site._registry`` (B-7). |
| 16 | +- Rule 5: ``has_change_permission(request, obj)`` per-object gate — object |
| 17 | + actions are change-shaped, matching how django-object-actions |
| 18 | + wires them onto the change view. |
| 19 | +- Rule 10: Object loaded through ``ModelAdmin.get_object`` / |
| 20 | + ``get_queryset`` — never ``Model.objects.all()`` (B-2). |
| 21 | +- Rule 12: The action ``name`` is verified against the *permitted* set |
| 22 | + (``get_change_actions``) before the callable runs; an unknown / |
| 23 | + non-permitted name is a 404 and the callable never executes. |
| 24 | + Action callables may raise — we catch and return a clean 400 |
| 25 | + ``{ok: false, error}`` rather than a 500 (per the issue brief). |
| 26 | +- CSRF: No ``@csrf_exempt`` — Django's middleware enforces. |
| 27 | +""" |
| 28 | + |
| 29 | +from __future__ import annotations |
| 30 | + |
| 31 | +from typing import Any |
| 32 | + |
| 33 | +from django.http import HttpRequest |
| 34 | +from django.http import HttpResponse |
| 35 | +from django.http import JsonResponse |
| 36 | +from django.views.generic import View |
| 37 | + |
| 38 | +from django_admin_react.api.object_actions import permitted_action_names |
| 39 | +from django_admin_react.api.object_actions import resolve_action_callable |
| 40 | +from django_admin_react.api.permissions import forbidden_response |
| 41 | +from django_admin_react.api.permissions import is_admin_user |
| 42 | +from django_admin_react.api.registry import get_admin_site |
| 43 | +from django_admin_react.api.registry import resolve_model |
| 44 | +from django_admin_react.api.writes import load_object_or_none |
| 45 | +from django_admin_react.api.writes import not_found_response |
| 46 | + |
| 47 | + |
| 48 | +class ObjectActionView(View): |
| 49 | + """``POST /api/v1/<app_label>/<model_name>/<pk>/action/<name>/``.""" |
| 50 | + |
| 51 | + http_method_names = ["post"] |
| 52 | + |
| 53 | + def post( |
| 54 | + self, |
| 55 | + request: HttpRequest, |
| 56 | + app_label: str, |
| 57 | + model_name: str, |
| 58 | + pk: str, |
| 59 | + name: str, |
| 60 | + *args: Any, |
| 61 | + **kwargs: Any, |
| 62 | + ) -> HttpResponse: |
| 63 | + """Run one permitted object action against a single object. |
| 64 | +
|
| 65 | + Gates, in order: |
| 66 | +
|
| 67 | + 1. ``is_admin_user`` — 403 if not authenticated active staff. |
| 68 | + 2. ``resolve_model`` — 404 if the model is unknown / unviewable. |
| 69 | + 3. ``load_object_or_none`` — 404 if the pk doesn't resolve under |
| 70 | + the admin's queryset (rule 10) or parse-fails. |
| 71 | + 4. ``has_change_permission(request, obj)`` — per-object gate |
| 72 | + (object actions are change-shaped). |
| 73 | + 5. ``permitted_action_names`` — 404 unless ``name`` is in the set |
| 74 | + the admin permits for this user + object (the callable never |
| 75 | + runs for a name not in that set). |
| 76 | +
|
| 77 | + On success the response is ``{ok: true, message?, redirect?}``: if |
| 78 | + the callable returns a redirect ``HttpResponse`` we surface its URL |
| 79 | + as ``redirect`` (the API itself returns 200, never a 302, so the |
| 80 | + SPA controls navigation). If the callable raises, the response is |
| 81 | + ``{ok: false, error}`` with status 400 — never a 500. |
| 82 | + """ |
| 83 | + admin_site = get_admin_site() |
| 84 | + if not is_admin_user(request, admin_site=admin_site): |
| 85 | + return forbidden_response(request) |
| 86 | + |
| 87 | + resolved = resolve_model(admin_site, request, app_label, model_name) |
| 88 | + if resolved is None: |
| 89 | + return not_found_response() |
| 90 | + model, model_admin = resolved |
| 91 | + |
| 92 | + obj = load_object_or_none(model, model_admin, request, pk) |
| 93 | + if obj is None: |
| 94 | + return not_found_response() |
| 95 | + |
| 96 | + # Object actions are change-shaped — gate on change permission for |
| 97 | + # this object, the same posture django-object-actions takes by |
| 98 | + # wiring the buttons onto the change view. |
| 99 | + if not model_admin.has_change_permission(request, obj): |
| 100 | + return forbidden_response(request) |
| 101 | + |
| 102 | + # Never trust the URL ``name``: it must be in the admin's own |
| 103 | + # permitted set. ``None`` means the admin exposes no object actions |
| 104 | + # at all → 404 (the endpoint doesn't exist for this model). |
| 105 | + permitted = permitted_action_names(model_admin, request, obj) |
| 106 | + if permitted is None or name not in permitted: |
| 107 | + return not_found_response() |
| 108 | + |
| 109 | + action_callable = resolve_action_callable(model_admin, name) |
| 110 | + if action_callable is None: |
| 111 | + return not_found_response() |
| 112 | + |
| 113 | + # The action manages its own writes (it may or may not mutate), so |
| 114 | + # we do NOT force a surrounding ``transaction.atomic()`` — matching |
| 115 | + # django-object-actions, which calls the bound method directly. A |
| 116 | + # raising callable is caught and returned as a clean 400, never a |
| 117 | + # 500 (per the issue brief). |
| 118 | + try: |
| 119 | + result = action_callable(request, obj) |
| 120 | + except Exception: |
| 121 | + # The action callable raised — return a clean 400, never a 500. |
| 122 | + # The exception text can disclose internal detail, so we surface |
| 123 | + # only a generic, safe message (``SECURITY.md`` §3 rule 12); the |
| 124 | + # real cause is in the consumer's server logs, not the wire. |
| 125 | + return _json_response( |
| 126 | + {"ok": False, "error": "The action could not be completed."}, |
| 127 | + status=400, |
| 128 | + ) |
| 129 | + |
| 130 | + return _success_response(result) |
| 131 | + |
| 132 | + |
| 133 | +def _success_response(result: Any) -> HttpResponse: |
| 134 | + """Build the ``{ok: true, message?, redirect?}`` success envelope. |
| 135 | +
|
| 136 | + A redirect ``HttpResponse`` from the callable is surfaced as a |
| 137 | + ``redirect`` URL (we never echo a 302 — the SPA navigates client-side |
| 138 | + without a full-page reload). Any other ``HttpResponse`` is treated as |
| 139 | + "ran successfully" with no extra payload. The django-object-actions |
| 140 | + contract is that an action returns ``None`` (just ran) or an |
| 141 | + ``HttpResponse`` (commonly a redirect). |
| 142 | + """ |
| 143 | + body: dict[str, Any] = {"ok": True} |
| 144 | + if isinstance(result, HttpResponse): |
| 145 | + # A redirect response carries a ``Location`` header (3xx). Mirror |
| 146 | + # the changelist action runner (``views/actions.py``): surface the |
| 147 | + # target so the SPA navigates client-side. ``url`` is set on |
| 148 | + # ``HttpResponseRedirect`` subclasses; the header is the fallback. |
| 149 | + target = getattr(result, "url", None) or result.get("Location", None) |
| 150 | + if target: |
| 151 | + body["redirect"] = str(target) |
| 152 | + return _json_response(body, status=200) |
| 153 | + |
| 154 | + |
| 155 | +def _json_response(body: dict[str, Any], status: int) -> HttpResponse: |
| 156 | + """JSON envelope with the package's standard no-store cache header.""" |
| 157 | + response = JsonResponse(body, status=status) |
| 158 | + response["Cache-Control"] = "no-store" |
| 159 | + return response |
0 commit comments