Beautiful Open-Source Form Builder
Refactor TemplateController and FormTemplateRequest for improved attr… (#1138)
Chirag Chhatralaad8340dc2623
diff --git a/api/app/Http/Controllers/Forms/TemplateController.php b/api/app/Http/Controllers/Forms/TemplateController.phpindex 5bc628a88..78063ebc9 100644--- a/api/app/Http/Controllers/Forms/TemplateController.php+++ b/api/app/Http/Controllers/Forms/TemplateController.php@@ -88,7 +88,7 @@ class TemplateController extends Controller$template = Template::findOrFail($id);$this->authorize('update', $template);- $template->update($request->all());+ $template->update($request->getUpdateAttributes());return $this->success(['message' => 'Template was updated.',diff --git a/api/app/Http/Requests/Templates/FormTemplateRequest.php b/api/app/Http/Requests/Templates/FormTemplateRequest.phpindex 4ca14ec68..aef1cba31 100644--- a/api/app/Http/Requests/Templates/FormTemplateRequest.php+++ b/api/app/Http/Requests/Templates/FormTemplateRequest.php@@ -7,6 +7,13 @@ use Illuminate\Foundation\Http\FormRequest;class FormTemplateRequest extends FormRequest{+ private const LIST_FIELDS = [+ 'types',+ 'industries',+ 'related_templates',+ 'questions',+ ];+public const IGNORED_KEYS = ['id','creator',@@ -33,54 +40,98 @@ class FormTemplateRequest extends FormRequest];/**- * Get the validation rules that apply to the request.- ** @return array<string, mixed>*/public function rules(){$slugRule = '';- if ($this->id) {- $slugRule = ',' . $this->id;+ $templateId = $this->route('id');+ if ($templateId !== null) {+ $slugRule = ',' . $templateId;}return ['form' => 'required|array',- 'publicly_listed' => 'boolean',+ 'publicly_listed' => 'sometimes|boolean','name' => 'required|string|max:60','slug' => 'required|string|alpha_dash|unique:templates,slug' . $slugRule,'short_description' => 'required|string|max:1000','description' => 'required|string','image_url' => 'required|string',- 'types' => 'nullable|array',- 'industries' => 'nullable|array',- 'related_templates' => 'nullable|array',+ 'types' => 'array',+ 'industries' => 'array',+ 'related_templates' => 'array','questions' => 'array',];}public function getTemplate(): Template{- $structure = $this->form;- foreach ($structure as $key => $val) {- if (in_array($key, self::IGNORED_KEYS)) {- unset($structure[$key]);+ $template = new Template($this->getMutableAttributes(includeOptionalListFields: true));+ $template->creator_id = $this->user()?->id;++ return $template;+ }++ /**+ * @return array<string, mixed>+ */+ public function getUpdateAttributes(): array+ {+ return $this->getMutableAttributes(includeOptionalListFields: false);+ }++ /**+ * @return array<string, mixed>+ */+ private function getMutableAttributes(bool $includeOptionalListFields): array+ {+ $attributes = [+ 'name' => $this->input('name'),+ 'slug' => $this->input('slug'),+ 'short_description' => $this->input('short_description'),+ 'description' => $this->input('description'),+ 'image_url' => $this->input('image_url'),+ 'structure' => $this->cleanFormStructure($this->input('form', [])),+ ];++ foreach (self::LIST_FIELDS as $key) {+ if ($includeOptionalListFields || $this->has($key)) {+ $attributes[$key] = $this->arrayInput($key);}}- return new Template([- 'creator_id' => $this->user()?->id ?? null,- 'publicly_listed' => $this->publicly_listed,- 'name' => $this->name,- 'slug' => $this->slug,- 'short_description' => $this->short_description,- 'description' => $this->description,- 'image_url' => $this->image_url,- 'structure' => $structure,- 'types' => $this->types ?? [],- 'industries' => $this->industries ?? [],- 'related_templates' => $this->related_templates ?? [],- 'questions' => $this->questions ?? [],- ]);+ if ($this->canSetPubliclyListed() && $this->has('publicly_listed')) {+ $attributes['publicly_listed'] = $this->boolean('publicly_listed');+ }++ return $attributes;+ }++ /**+ * @param array<string, mixed> $structure+ * @return array<string, mixed>+ */+ private function cleanFormStructure(array $structure): array+ {+ foreach (self::IGNORED_KEYS as $key) {+ unset($structure[$key]);+ }++ return $structure;+ }++ private function arrayInput(string $key): array+ {+ $value = $this->input($key);++ return is_array($value) ? $value : [];+ }++ private function canSetPubliclyListed(): bool+ {+ $user = $this->user();++ return $user !== null && ($user->admin || $user->template_editor);}}diff --git a/api/app/Models/Template.php b/api/app/Models/Template.phpindex 6ad1c568e..04fd19ed7 100644--- a/api/app/Models/Template.php+++ b/api/app/Models/Template.php@@ -15,7 +15,6 @@ class Template extends Modeluse HasSlug;protected $fillable = [- 'creator_id','name','slug','description',@@ -37,6 +36,7 @@ class Template extends Model'industries' => 'array','types' => 'array','related_templates' => 'array',+ 'publicly_listed' => 'boolean','created_at' => 'datetime','updated_at' => 'datetime',];diff --git a/api/tests/Feature/TemplateTest.php b/api/tests/Feature/TemplateTest.phpindex 7f0bc4e2b..02dec529f 100644--- a/api/tests/Feature/TemplateTest.php+++ b/api/tests/Feature/TemplateTest.php@@ -1,5 +1,6 @@<?php+use App\Models\Forms\Form;use App\Models\Template;it('can create template', function () {@@ -43,7 +44,6 @@ it('returns single template object when fetching by slug', function () {// Create a template directly in the database$template = Template::create([- 'creator_id' => $user->id,'name' => 'Test Template for Show','slug' => 'test-template-for-show','short_description' => 'A test template',@@ -55,6 +55,8 @@ it('returns single template object when fetching by slug', function () {'industries' => [],'types' => [],]);+ $template->creator_id = $user->id;+ $template->save();// Fetch the template by slug - should return a single object, not an array$response = $this->getJson(route('templates.show', ['slug' => $template->slug]));@@ -128,3 +130,245 @@ it('sanitizes FAQ answers and strips tags from FAQ questions', function () {->and($faq['answer'] ?? '')->not->toContain('<script')->and($faq['answer'] ?? '')->not->toContain('onclick=');});++function templateRequestPayload(Form $form, array $overrides = []): array+{+ return array_merge([+ 'name' => 'Updated Template',+ 'slug' => 'updated-template',+ 'short_description' => 'Updated short description',+ 'description' => 'Updated description',+ 'image_url' => 'https://example.com/image.jpg',+ 'publicly_listed' => true,+ 'form' => $form->getAttributes(),+ 'types' => [],+ 'industries' => [],+ 'related_templates' => [],+ 'questions' => [],+ ], $overrides);+}++it('does not allow changing creator_id on template update', function () {+ $owner = $this->createUser(['email' => '[email protected]']);+ $attacker = $this->createUser(['email' => '[email protected]']);+ $this->actingAsUser($attacker);++ $workspace = $this->createUserWorkspace($owner);+ $form = $this->makeForm($owner, $workspace);++ $template = Template::create([+ 'name' => 'Owned Template',+ 'slug' => 'owned-template',+ 'short_description' => 'Short description',+ 'description' => 'Description',+ 'image_url' => 'https://example.com/image.jpg',+ 'publicly_listed' => false,+ 'structure' => $form->getAttributes(),+ 'questions' => [],+ 'industries' => [],+ 'types' => [],+ ]);+ $template->creator_id = $owner->id;+ $template->save();++ config(['opnform.admin_emails' => [$attacker->email]]);++ $this->putJson(route('templates.update', ['id' => $template->id]), templateRequestPayload($form, [+ 'creator_id' => $attacker->id,+ 'name' => 'Hijacked Template',+ ]))->assertSuccessful();++ $template->refresh();++ expect($template->creator_id)->toBe($owner->id)+ ->and($template->name)->toBe('Hijacked Template');+});++it('does not allow regular users to list templates publicly on update', function () {+ $user = $this->createUser(['email' => '[email protected]']);+ $this->actingAsUser($user);++ $workspace = $this->createUserWorkspace($user);+ $form = $this->makeForm($user, $workspace);++ $template = Template::create([+ 'name' => 'Private Template',+ 'slug' => 'private-template',+ 'short_description' => 'Short description',+ 'description' => 'Description',+ 'image_url' => 'https://example.com/image.jpg',+ 'publicly_listed' => false,+ 'structure' => $form->getAttributes(),+ 'questions' => [],+ 'industries' => [],+ 'types' => [],+ ]);+ $template->creator_id = $user->id;+ $template->save();++ $this->putJson(route('templates.update', ['id' => $template->id]), templateRequestPayload($form, [+ 'slug' => 'private-template',+ 'publicly_listed' => true,+ ]))->assertSuccessful();++ expect($template->fresh()->publicly_listed)->toBeFalse();+});++it('allows template editors to update publicly_listed on update', function () {+ config(['opnform.template_editor_emails' => ['[email protected]']]);++ $user = $this->createUser(['email' => '[email protected]']);+ $this->actingAsUser($user);++ $workspace = $this->createUserWorkspace($user);+ $form = $this->makeForm($user, $workspace);++ $template = Template::create([+ 'name' => 'Editor Template',+ 'slug' => 'editor-template',+ 'short_description' => 'Short description',+ 'description' => 'Description',+ 'image_url' => 'https://example.com/image.jpg',+ 'publicly_listed' => false,+ 'structure' => $form->getAttributes(),+ 'questions' => [],+ 'industries' => [],+ 'types' => [],+ ]);+ $template->creator_id = $user->id;+ $template->save();++ $this->putJson(route('templates.update', ['id' => $template->id]), templateRequestPayload($form, [+ 'slug' => 'editor-template',+ 'publicly_listed' => true,+ ]))->assertSuccessful();++ expect($template->fresh()->publicly_listed)->toBeTrue();+});++it('does not change publicly_listed when editors omit the field on update', function () {+ config(['opnform.template_editor_emails' => ['[email protected]']]);++ $user = $this->createUser(['email' => '[email protected]']);+ $this->actingAsUser($user);++ $workspace = $this->createUserWorkspace($user);+ $form = $this->makeForm($user, $workspace);++ $template = Template::create([+ 'name' => 'Listed Editor Template',+ 'slug' => 'listed-editor-template',+ 'short_description' => 'Short description',+ 'description' => 'Description',+ 'image_url' => 'https://example.com/image.jpg',+ 'publicly_listed' => true,+ 'structure' => $form->getAttributes(),+ 'questions' => [],+ 'industries' => [],+ 'types' => [],+ ]);+ $template->creator_id = $user->id;+ $template->save();++ $payload = templateRequestPayload($form, [+ 'slug' => 'listed-editor-template',+ 'name' => 'Renamed Editor Template',+ ]);+ unset($payload['publicly_listed']);++ $this->putJson(route('templates.update', ['id' => $template->id]), $payload)+ ->assertSuccessful();++ $template->refresh();++ expect($template->name)->toBe('Renamed Editor Template')+ ->and($template->publicly_listed)->toBeTrue();+});++it('preserves template list fields when omitted on update', function () {+ config(['opnform.template_editor_emails' => ['[email protected]']]);++ $user = $this->createUser(['email' => '[email protected]']);+ $this->actingAsUser($user);++ $workspace = $this->createUserWorkspace($user);+ $form = $this->makeForm($user, $workspace);++ $template = Template::create([+ 'name' => 'Array Template',+ 'slug' => 'array-template',+ 'short_description' => 'Short description',+ 'description' => 'Description',+ 'image_url' => 'https://example.com/image.jpg',+ 'publicly_listed' => false,+ 'structure' => $form->getAttributes(),+ 'questions' => [['question' => 'Q1', 'answer' => 'A1']],+ 'industries' => ['healthcare'],+ 'types' => ['survey'],+ 'related_templates' => ['other-template'],+ ]);+ $template->creator_id = $user->id;+ $template->save();++ $payload = templateRequestPayload($form, [+ 'slug' => 'array-template',+ 'name' => 'Renamed Array Template',+ ]);+ unset($payload['types'], $payload['industries'], $payload['related_templates'], $payload['questions']);++ $this->putJson(route('templates.update', ['id' => $template->id]), $payload)+ ->assertSuccessful();++ $template->refresh();++ expect($template->name)->toBe('Renamed Array Template')+ ->and($template->types)->toBe(['survey'])+ ->and($template->industries)->toBe(['healthcare'])+ ->and($template->related_templates)->toBe(['other-template'])+ ->and($template->questions)->toBe([['question' => 'Q1', 'answer' => 'A1']]);+});++it('stores empty arrays instead of null for template list fields on update', function () {+ config(['opnform.template_editor_emails' => ['[email protected]']]);++ $user = $this->createUser(['email' => '[email protected]']);+ $this->actingAsUser($user);++ $workspace = $this->createUserWorkspace($user);+ $form = $this->makeForm($user, $workspace);++ $template = Template::create([+ 'name' => 'Array Template',+ 'slug' => 'array-template',+ 'short_description' => 'Short description',+ 'description' => 'Description',+ 'image_url' => 'https://example.com/image.jpg',+ 'publicly_listed' => false,+ 'structure' => $form->getAttributes(),+ 'questions' => [['question' => 'Q1', 'answer' => 'A1']],+ 'industries' => ['healthcare'],+ 'types' => ['survey'],+ 'related_templates' => ['other-template'],+ ]);+ $template->creator_id = $user->id;+ $template->save();++ $payload = templateRequestPayload($form, [+ 'slug' => 'array-template',+ 'types' => null,+ 'industries' => null,+ 'related_templates' => null,+ 'questions' => null,+ ]);++ $this->putJson(route('templates.update', ['id' => $template->id]), $payload)+ ->assertUnprocessable()+ ->assertJsonValidationErrors(['types', 'industries', 'related_templates', 'questions']);++ $template->refresh();++ expect($template->types)->toBe(['survey'])+ ->and($template->industries)->toBe(['healthcare'])+ ->and($template->related_templates)->toBe(['other-template'])+ ->and($template->questions)->toBe([['question' => 'Q1', 'answer' => 'A1']]);+});