]> git.agnieray.net Git - galette.git/commitdiff
Add CSRF exclusion mechanism for plugins
authorJohan Cwiklinski <johan@x-tnd.be>
Sat, 20 Nov 2021 10:31:48 +0000 (11:31 +0100)
committerJohan Cwiklinski <johan@x-tnd.be>
Sat, 20 Nov 2021 18:39:44 +0000 (19:39 +0100)
galette/includes/dependencies.php
galette/lib/Galette/Core/Plugins.php

index 845993692e76f17c6f674a2da58de94405ae4a74..1040b9bd00c3e16d64833cc602bed6b4a10c1bf9 100644 (file)
@@ -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
index 79885bdceafbcb7970d8cb7ce63da4aba2069370..a74167e303a1fcdae8f937321114cff9b9dc4478 100644 (file)
@@ -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;
+    }
 }