/**
* Execute the middleware.
*
* @param ServerRequestInterface $request
* @param ResponseInterface $response
* @param callable $next
*
* @return ResponseInterface
*/
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
{
if (!Middleware::hasAttribute($request, FormatNegotiator::KEY)) {
throw new RuntimeException('Csrf middleware needs FormatNegotiator executed before');
}
if (!Middleware::hasAttribute($request, ClientIp::KEY)) {
throw new RuntimeException('Csrf middleware needs ClientIp executed before');
}
if ($this->storage === null) {
if (session_status() !== PHP_SESSION_ACTIVE) {
throw new RuntimeException('Csrf middleware needs an active php session or a storage defined');
}
if (!isset($_SESSION[$this->sessionIndex])) {
$_SESSION[$this->sessionIndex] = [];
}
$this->storage =& $_SESSION[$this->sessionIndex];
}
if (FormatNegotiator::getFormat($request) !== 'html') {
return $next($request, $response);
}
if (Utils\Helpers::isPost($request) && !$this->validateRequest($request)) {
return $response->withStatus(403);
}
$response = $next($request, $response);
return $this->insertIntoPostForms($response, function ($match) use($request) {
preg_match('/action=["\']?([^"\'\\s]+)["\']?/i', $match[0], $matches);
$action = empty($matches[1]) ? $request->getUri()->getPath() : $matches[1];
return $match[0] . $this->generateTokens($request, $action);
});
}