refactor(actions): centralize POST/CSRF guard flow

This commit is contained in:
2026-04-24 17:59:57 +02:00
parent 87652e55da
commit cfd867bcd7
16 changed files with 175 additions and 75 deletions

View File

@@ -4,6 +4,9 @@ use MintyPHP\Http\Input\FormErrors;
use MintyPHP\Http\Input\RequestInput;
use MintyPHP\Http\Input\RequestInputFactory;
use MintyPHP\Http\Request;
use MintyPHP\Router;
use MintyPHP\Service\Access\AuthorizationDecision;
use MintyPHP\Session;
use MintyPHP\Support\Flash;
function requestInput(): RequestInput
@@ -38,6 +41,92 @@ function flashFormErrors(FormErrors $errors, ?string $scope = null, string $keyP
}
}
/**
* Enforce POST request method for mutation actions.
*
* Browser requests are redirected to $redirect.
* Optional JSON mode returns 405 with a JSON error payload.
*/
function actionRequirePost(
string $redirect,
bool $jsonAware = false,
string $jsonError = 'method_not_allowed'
): bool {
if (requestInput()->isMethod('POST')) {
return true;
}
if ($jsonAware && Request::wantsJson()) {
header('Allow: POST');
http_response_code(405);
Router::json(['error' => trim($jsonError) !== '' ? trim($jsonError) : 'method_not_allowed']);
return false;
}
Router::redirect($redirect);
return false;
}
/**
* Enforce CSRF protection for POST actions.
*
* Returns false after responding/redirecting when token validation fails.
*/
function actionRequireCsrf(
string $redirect,
?string $flashScope = null,
string $flashKeyPrefix = 'csrf_expired',
bool $jsonAware = false,
string $jsonError = 'csrf',
bool $flashOnFailure = true
): bool {
if (Session::checkCsrfToken()) {
return true;
}
if ($jsonAware && Request::wantsJson()) {
http_response_code(400);
Router::json(['error' => trim($jsonError) !== '' ? trim($jsonError) : 'csrf']);
return false;
}
if ($flashOnFailure) {
$errorBag = formErrors();
$errorBag->addGlobal(t('Form expired, please try again'));
flashFormErrors($errorBag, $flashScope ?? $redirect, $flashKeyPrefix);
}
Router::redirect($redirect);
return false;
}
/**
* Handle authorization decisions consistently for JSON and browser requests.
*/
function actionAllowOrDeny(
AuthorizationDecision $decision,
string $redirect = 'error/forbidden',
bool $jsonAware = true
): bool {
if ($decision->isAllowed()) {
return true;
}
if ($jsonAware && Request::wantsJson()) {
http_response_code($decision->status());
Router::json(['error' => $decision->error()]);
return false;
}
if ($redirect === 'error/forbidden') {
Router::redirect('error/forbidden?url=' . urlencode(Request::pathWithQuery()));
return false;
}
Router::redirect($redirect);
return false;
}
/**
* Consume and remove flash messages matching any provided scope.
*