From 50078155e181e31f5af77dc4fc52b3cae09932c5 Mon Sep 17 00:00:00 2001 From: Awilum Date: Sat, 9 Mar 2019 15:34:42 +0300 Subject: [PATCH] Flextype Core: Csrf Twig Extension - added --- flextype/bootstrap.php | 17 +++++++++- flextype/twig/CsrfTwigExtension.php | 52 +++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 1 deletion(-) create mode 100644 flextype/twig/CsrfTwigExtension.php diff --git a/flextype/bootstrap.php b/flextype/bootstrap.php index 136122aa..3b3ac93a 100755 --- a/flextype/bootstrap.php +++ b/flextype/bootstrap.php @@ -67,6 +67,18 @@ $app = new \Slim\App($config); */ $flextype = $app->getContainer(); +/** + * Add CSRF (cross-site request forgery) protection service to Flextype container + */ +$flextype['csrf'] = function ($container) { + return new \Slim\Csrf\Guard; +}; + +/** + * Add middleware CSRF (cross-site request forgery) protection for all routes + */ +$app->add($flextype->get('csrf')); + /** * Add emitter service to Flextype container */ @@ -276,7 +288,7 @@ $flextype['view'] = function ($container) { // Add Emitter Twig Extension $view->addExtension(new EmitterTwigExtension($container)); - // Add Emitter Twig Extension + // Add Flash Twig Extension $view->addExtension(new FlashTwigExtension($container)); // Add I18n Twig Extension @@ -285,6 +297,9 @@ $flextype['view'] = function ($container) { // Add Assets Twig Extension $view->addExtension(new AssetsTwigExtension()); + // Add Csrf Twig Extension + $view->addExtension(new CsrfTwigExtension($container->get('csrf'))); + // Return view return $view; }; diff --git a/flextype/twig/CsrfTwigExtension.php b/flextype/twig/CsrfTwigExtension.php new file mode 100644 index 00000000..3c900569 --- /dev/null +++ b/flextype/twig/CsrfTwigExtension.php @@ -0,0 +1,52 @@ + + * @link http://romanenko.digital + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace Flextype; + +class CsrfTwigExtension extends \Twig_Extension implements \Twig_Extension_GlobalsInterface +{ + + /** + * @var \Slim\Csrf\Guard + */ + protected $csrf; + + public function __construct(\Slim\Csrf\Guard $csrf) + { + $this->csrf = $csrf; + } + + public function getGlobals() + { + // CSRF token name and value + $csrfNameKey = $this->csrf->getTokenNameKey(); + $csrfValueKey = $this->csrf->getTokenValueKey(); + $csrfName = $this->csrf->getTokenName(); + $csrfValue = $this->csrf->getTokenValue(); + + return [ + 'csrf' => [ + 'keys' => [ + 'name' => $csrfNameKey, + 'value' => $csrfValueKey + ], + 'name' => $csrfName, + 'value' => $csrfValue + ] + ]; + } + + public function getName() + { + return 'slim/csrf'; + } +}