From: Johan Cwiklinski Date: Sat, 20 Nov 2021 10:31:48 +0000 (+0100) Subject: Add CSRF exclusion mechanism for plugins X-Git-Tag: 0.9.6~29 X-Git-Url: https://git.agnieray.net/?a=commitdiff_plain;h=f6dcc32cd3c95514d2c57377efe17e94e23fe761;p=galette.git Add CSRF exclusion mechanism for plugins --- diff --git a/galette/includes/dependencies.php b/galette/includes/dependencies.php index 845993692..1040b9bd0 100644 --- a/galette/includes/dependencies.php +++ b/galette/includes/dependencies.php @@ -34,8 +34,8 @@ */ use Psr\Container\ContainerInterface; -use Galette\Entity\PdfModel; -use Slim\Event\SlimEventManager; +use Psr\Http\Message\ResponseInterface; +use Psr\Http\Message\ServerRequestInterface; use Slim\Views\SmartyPlugins; $container = $app->getContainer(); @@ -432,6 +432,13 @@ $container->set( ) ); +$container->set( + 'CsrfExclusions', + function (ContainerInterface $c): array { + return $c->get('plugins')->getCsrfExclusions(); + } +); + $container->set( 'csrf', function (ContainerInterface $c) { @@ -445,7 +452,14 @@ $container->set( true ); - $guard->setFailureCallable(function ($request, $response, $next) { + $exclusions = $c->get('CsrfExclusions'); + $guard->setFailureCallable(function (ServerRequestInterface $request, ResponseInterface $response, $next) use ($exclusions) { + foreach ($exclusions as $exclusion) { + if (preg_match($exclusion, $request->getAttribute('route')->getname())) { + //route is excluded form CSRF checks + return $next($request, $response); + } + } Analog::log( 'CSRF check has failed', Analog::CRITICAL diff --git a/galette/lib/Galette/Core/Plugins.php b/galette/lib/Galette/Core/Plugins.php index 79885bdce..a74167e30 100644 --- a/galette/lib/Galette/Core/Plugins.php +++ b/galette/lib/Galette/Core/Plugins.php @@ -63,6 +63,7 @@ class Plugins protected $path; protected $modules = array(); protected $disabled = array(); + protected $csrf_exclusions = array(); protected $id; protected $mroot; @@ -812,4 +813,27 @@ class Plugins { return str_replace(' ', '', $this->modules[$id]['name']); } + + /** + * Set CRSF excluded routes + * + * @param array $exclusions Array of regular expressions patterns to be excluded + * + * @return $this + */ + public function setCsrfExclusions(array $exclusions): self + { + $this->csrf_exclusions = $exclusions; + return $this; + } + + /** + * Get CSRF excluded routes patterns + * + * @return array + */ + public function getCsrfExclusions(): array + { + return $this->csrf_exclusions; + } }