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;
|
|
|
|
|
2023-11-28 10:23:04 +00:00
|
|
|
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')) {
|
2023-11-28 10:23:04 +00:00
|
|
|
return $next($request);
|
2022-09-20 19:59:52 +00:00
|
|
|
}
|
2023-11-28 10:23:04 +00:00
|
|
|
|
2024-02-23 10:54:12 +00:00
|
|
|
$form = Form::where('slug', $request->route('slug'))->firstOrFail();
|
2023-11-28 10:23:04 +00:00
|
|
|
$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)) {
|
2023-11-28 10:23:04 +00:00
|
|
|
return response([
|
|
|
|
'status' => 'Unauthorized',
|
|
|
|
'message' => 'Form is protected.',
|
|
|
|
], 403);
|
|
|
|
}
|
|
|
|
|
2022-09-20 19:59:52 +00:00
|
|
|
return $next($request);
|
|
|
|
}
|
|
|
|
|
2023-11-28 10:23:04 +00:00
|
|
|
public static function isProtected(Request $request, Form $form)
|
|
|
|
{
|
2024-02-23 10:54:12 +00:00
|
|
|
if (! $form->has_password) {
|
2023-11-28 10:23:04 +00:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-02-23 10:54:12 +00:00
|
|
|
return ! self::hasCorrectPassword($request, $form);
|
2023-11-28 10:23:04 +00:00
|
|
|
}
|
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
}
|