Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions .agents/tasks/T23_api_form_fields_preview_hook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# Task T23 - Preview access for non-public forms in form-fields API

Goal
- Allow authenticated staff with `unfold_fobi.view_formentryproxy` permission
to preview non-public forms via `GET /api/fobi-form-fields/{slug}/`.
- No new settings or configuration — use Django's built-in permission system.

Problem statement
- The endpoint filters `FormEntry.objects.get(slug=slug, is_public=True)`,
so non-public forms always return 404.
- Admin users building forms need to preview them before publishing.

Suggested Skills
- Primary: `$unfold-dev-advanced`.

Dependencies
- T17/T17a, T18, T19 (current form-fields endpoint features).

Scope
- `src/unfold_fobi/api/views.py` — modify `get_form_fields` access logic.
- `tests/api/` — tests for preview access.

Non-goals
- No configurable hook or setting.
- No site-scope logic in the package.
- No changes to the PUT submission endpoint.

Implementation requirements
- Change the lookup from `get(slug=slug, is_public=True)` to `get(slug=slug)`.
- After lookup, apply access control:
- Public form: serve to anyone (unchanged).
- Non-public form: serve only if `request.user.has_perm("unfold_fobi.view_formentryproxy")`.
- Otherwise: return 404 (not 403, to prevent information leakage).
- Add `"is_preview": true/false` to the response envelope so the frontend can
show a preview indicator or disable submission.
- Keep `@never_cache`.

Deliverables
- Updated `get_form_fields` view.
- `is_preview` flag in response.
- Tests:
- Public form: anonymous gets 200, `is_preview` is false.
- Non-public form: anonymous gets 404.
- Non-public form: staff with permission gets 200, `is_preview` is true.
- Non-public form: staff without permission gets 404.
- `poetry run pytest -q` passes.

Acceptance Criteria
- Public forms behave exactly as before.
- Non-public forms are accessible to users with `view_formentryproxy` permission.
- `is_preview` flag distinguishes preview from public access.
- `poetry run pytest -q` passes.

Tests to run
- `poetry run pytest -q`
110 changes: 60 additions & 50 deletions src/unfold_fobi/api/views.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
"""DRF API views for unfold_fobi."""

from django.forms.fields import EmailField
from django.middleware.csrf import get_token
from django.utils.translation import gettext_lazy as _
from django.views.decorators.cache import never_cache
from fobi.contrib.apps.drf_integration.dynamic import get_declared_fields
from fobi.models import FormEntry
from rest_framework.decorators import api_view
from rest_framework.exceptions import NotFound
from rest_framework.response import Response


Expand Down Expand Up @@ -57,8 +60,6 @@ def _coerce_choice_pair(choice):

def _build_widget_map(form_entry):
"""Map field names to their Django widget class names."""
from django.forms.fields import EmailField

widget_map = {}
for element_entry in form_entry.formelemententry_set.all().order_by("position"):
try:
Expand Down Expand Up @@ -93,59 +94,68 @@ def _build_widget_map(form_entry):
@never_cache
def get_form_fields(request, slug):
"""
Custom API endpoint to get form fields structure for frontend rendering.
Return form fields for frontend rendering with permission (preview mode).
"""
try:
form_entry = FormEntry.objects.get(slug=slug, is_public=True)

from fobi.contrib.apps.drf_integration.dynamic import get_declared_fields

fields_result = get_declared_fields(form_entry)

if isinstance(fields_result, tuple):
fields = fields_result[0]
form_entry = FormEntry.objects.get(slug=slug)
except FormEntry.DoesNotExist:
raise NotFound(_("Form not found"))

is_preview = False
if not form_entry.is_public:
if (
request.user.is_authenticated
and request.user.has_perm("fobi.view_formentry")
Comment on lines +107 to +108

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 question (security): Preview access is granted solely on a global permission, which may be too broad for private forms.

Using only the global fobi.view_formentry permission means any user with that permission can preview all non-public forms, regardless of ownership or relationship to the form. If previews are meant to be more restricted, consider changing this to an object-level or ownership-based check, or introducing a dedicated, narrower preview permission.

):
is_preview = True
else:
fields = fields_result

widget_map = _build_widget_map(form_entry)

form_structure = {
"id": form_entry.id,
"slug": form_entry.slug,
"title": form_entry.name,
"is_active": form_entry.is_active,
"active_date_from": form_entry.active_date_from,
"active_date_to": form_entry.active_date_to,
"success_page_title": form_entry.success_page_title or "",
"success_page_message": form_entry.success_page_message or "",
"csrf_token": get_token(request),
"fields": [],
raise NotFound(_("Form not found"))

fields_result = get_declared_fields(form_entry)

if isinstance(fields_result, tuple):
fields = fields_result[0]
else:
fields = fields_result

widget_map = _build_widget_map(form_entry)

form_structure = {
"id": form_entry.id,
"slug": form_entry.slug,
"title": form_entry.name,
"is_active": form_entry.is_active,
"is_preview": is_preview,
"active_date_from": form_entry.active_date_from,
"active_date_to": form_entry.active_date_to,
"success_page_title": form_entry.success_page_title or "",
"success_page_message": form_entry.success_page_message or "",
"csrf_token": get_token(request),
"fields": [],
}

for field_name, field in fields.items():
field_info = {
"name": field_name,
"type": field.__class__.__name__,
"widget": widget_map.get(field_name),
"label": getattr(field, "label", field_name),
"required": getattr(field, "required", False),
"help_text": getattr(field, "help_text", ""),
}

for field_name, field in fields.items():
field_info = {
"name": field_name,
"type": field.__class__.__name__,
"widget": widget_map.get(field_name),
"label": getattr(field, "label", field_name),
"required": getattr(field, "required", False),
"help_text": getattr(field, "help_text", ""),
}

if hasattr(field, "choices") and field.choices:
field_info["choices"] = normalize_field_choices(field, field_name)
if hasattr(field, "choices") and field.choices:
field_info["choices"] = normalize_field_choices(field, field_name)

if hasattr(field, "min_value"):
field_info["min_value"] = field.min_value
if hasattr(field, "max_value"):
field_info["max_value"] = field.max_value
if hasattr(field, "min_length"):
field_info["min_length"] = field.min_length
if hasattr(field, "max_length"):
field_info["max_length"] = field.max_length
if hasattr(field, "min_value"):
field_info["min_value"] = field.min_value
if hasattr(field, "max_value"):
field_info["max_value"] = field.max_value
if hasattr(field, "min_length"):
field_info["min_length"] = field.min_length
if hasattr(field, "max_length"):
field_info["max_length"] = field.max_length

form_structure["fields"].append(field_info)
form_structure["fields"].append(field_info)

return Response(form_structure)
except FormEntry.DoesNotExist:
return Response({"error": _("Form not found")}, status=404)
return Response(form_structure)
97 changes: 90 additions & 7 deletions tests/api/test_form_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,20 +144,103 @@ def test_nonexistent_slug_returns_404(self, admin_client):
response = admin_client.get("/api/fobi-form-fields/does-not-exist/")
assert response.status_code == 404

def test_private_form_returns_404(self, db, admin_user, admin_client):
FormEntry.objects.create(
def test_existing_form_entry_fixture_works(self, admin_client, form_entry):
"""The shared form_entry fixture (text element) returns valid data."""
response = admin_client.get(f"/api/fobi-form-fields/{form_entry.slug}/")
assert response.status_code == 200
data = response.json()
assert len(data["fields"]) >= 1
assert data["fields"][0]["widget"] == "TextInput"


class TestFormFieldsPreviewAccess:
"""Preview access for non-public forms."""

@pytest.fixture()
def private_form(self, db, admin_user):
entry = FormEntry.objects.create(
user=admin_user,
name="Private Form",
slug="private-form",
is_public=False,
)
response = admin_client.get("/api/fobi-form-fields/private-form/")
FormElementEntry.objects.create(
form_entry=entry,
plugin_uid="text",
plugin_data=json.dumps(
{"label": "Name", "name": "name", "required": True}
),
position=1,
)
FormHandlerEntry.objects.get_or_create(
form_entry=entry, plugin_uid="db_store"
)
return entry

@pytest.fixture()
def staff_with_perm(self, db):
from django.contrib.auth.models import Permission, User
from django.contrib.contenttypes.models import ContentType
from fobi.models import FormEntry

user = User.objects.create_user(
username="previewer", password="pass", is_staff=True
)
ct = ContentType.objects.get_for_model(FormEntry)
perm = Permission.objects.get(
codename="view_formentry", content_type=ct
)
user.user_permissions.add(perm)
return user

@pytest.fixture()
def staff_without_perm(self, db):
from django.contrib.auth.models import User

return User.objects.create_user(
username="noperm", password="pass", is_staff=True
)

def test_public_form_anonymous_gets_200(self, client, multi_field_form):
response = client.get(f"/api/fobi-form-fields/{multi_field_form.slug}/")
assert response.status_code == 200
assert response.json()["is_preview"] is False

def test_public_form_staff_gets_200_not_preview(self, admin_client, multi_field_form):
response = admin_client.get(f"/api/fobi-form-fields/{multi_field_form.slug}/")
assert response.status_code == 200
assert response.json()["is_preview"] is False

def test_private_form_anonymous_gets_404(self, client, private_form):
response = client.get(f"/api/fobi-form-fields/{private_form.slug}/")
assert response.status_code == 404

def test_existing_form_entry_fixture_works(self, admin_client, form_entry):
"""The shared form_entry fixture (text element) returns valid data."""
response = admin_client.get(f"/api/fobi-form-fields/{form_entry.slug}/")
def test_private_form_staff_without_perm_gets_404(
self, staff_without_perm, private_form
):
from django.test import Client

c = Client()
c.login(username="noperm", password="pass")
response = c.get(f"/api/fobi-form-fields/{private_form.slug}/")
assert response.status_code == 404

def test_private_form_staff_with_perm_gets_200(
self, staff_with_perm, private_form
):
from django.test import Client

c = Client()
c.login(username="previewer", password="pass")
response = c.get(f"/api/fobi-form-fields/{private_form.slug}/")
assert response.status_code == 200
data = response.json()
assert data["is_preview"] is True
assert len(data["fields"]) >= 1
assert data["fields"][0]["widget"] == "TextInput"

def test_private_form_superuser_gets_preview(
self, admin_client, private_form
):
response = admin_client.get(f"/api/fobi-form-fields/{private_form.slug}/")
assert response.status_code == 200
assert response.json()["is_preview"] is True
Loading