opnform/app/Http/Middleware/Form/ProtectedForm.php

55 lines
1.6 KiB
PHP
Raw Normal View History

2022-09-20 19:59:52 +00:00
<?php
namespace App\Http\Middleware\Form;
use App\Models\Forms\Form;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ProtectedForm
2022-09-20 19:59:52 +00:00
{
2024-02-23 10:54:12 +00:00
public const PASSWORD_HEADER_NAME = 'form-password';
2022-09-20 19:59:52 +00:00
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
2024-02-23 10:54:12 +00:00
if (! $request->route('slug')) {
return $next($request);
2022-09-20 19:59:52 +00:00
}
2024-02-23 10:54:12 +00:00
$form = Form::where('slug', $request->route('slug'))->firstOrFail();
$request->merge([
'form' => $form,
]);
$userIsFormOwner = Auth::check() && Auth::user()->ownsForm($form);
2024-02-23 10:54:12 +00:00
if (! $userIsFormOwner && $this->isProtected($request, $form)) {
return response([
'status' => 'Unauthorized',
'message' => 'Form is protected.',
], 403);
}
2022-09-20 19:59:52 +00:00
return $next($request);
}
public static function isProtected(Request $request, Form $form)
{
2024-02-23 10:54:12 +00:00
if (! $form->has_password) {
return false;
}
2024-02-23 10:54:12 +00:00
return ! self::hasCorrectPassword($request, $form);
}
2022-09-20 19:59:52 +00:00
public static function hasCorrectPassword(Request $request, Form $form)
{
return $request->headers->has(self::PASSWORD_HEADER_NAME) && $request->headers->get(self::PASSWORD_HEADER_NAME) == hash('sha256', $form->password);
}
}