2017 © Pedro Peláez
 

library csrf-twig-helpers

CSRF (Cross-Site Request Forgery) protection helpers for the Twig templating engine.

image

schnittstabil/csrf-twig-helpers

CSRF (Cross-Site Request Forgery) protection helpers for the Twig templating engine.

  • Friday, April 8, 2016
  • by schnittstabil
  • Repository
  • 1 Watchers
  • 3 Stars
  • 34,181 Installations
  • PHP
  • 0 Dependents
  • 0 Suggesters
  • 1 Forks
  • 0 Open issues
  • 7 Versions
  • 0 % Grown

The README.md

Csrf\Twig\Helpers Build Status Coverage Status Scrutinizer Code Quality Code Climate

SensioLabsInsight, (*1)

CSRF (Cross-Site Request Forgery) protection helpers for the Twig templating engine :cactus:, (*2)

Install

$ composer require schnittstabil/csrf-twig-helpers

Usage

addExtension(
    new Schnittstabil\Csrf\Twig\Helpers\Extension(getToken, 'X-XSRF-TOKEN')
);
?>

Template functions

{{ csrf_token() }}
{# => result of getToken() #}

{{ csrf_token_name() }}
{# => X-XSRF-TOKEN #}

{{ csrf_input_widget() }}
{# => <input name="X-XSRF-TOKEN" type="hidden" value="...some token..." /> #}

{{ csrf_meta_widget() }}
{# => <meta name="X-XSRF-TOKEN" content="...some token..." /> #}

Slim v3 Example

For complete examples see the examples directory., (*3)

Install Additional Requirements

$ composer require slim/slim slim/twig-view schnittstabil/psr7-csrf-middleware

Twig Templates

<!-- index.html.twig -->
<form role="form" method="post" action="{{ path_for('contact') }}">
    <input type="email" name="email" />
    <textarea name="message"></textarea>
    {{ csrf_input_widget() }}
    <button type="submit">Send!</button>
</form>

Scripts

getContainer()['csrf'] = function ($c) {
    $key = 'This key is not so secret - change it!';

    return CsrfMiddlewareBuilder::create($key)
        ->buildSynchronizerTokenPatternMiddleware();
};
$app->add('csrf');

/**
 * Register Twig Extensions
 */
$app->getContainer()['view'] = function ($c) {
    $view = new Slim\Views\Twig('templates', [
        'cache' => 'cache',
    ]);
    $view->addExtension(new Slim\Views\TwigExtension(
        $c['router'],
        $c['request']->getUri()
    ));
    $view->addExtension(new Schnittstabil\Csrf\Twig\Helpers\Extension(
        [$c['csrf']->getTokenService(), 'generate']
    ));

    return $view;
};

/**
 * Add routes
 */
$app->get('/', function ($request, $response) {
    return $this->view->render($response, 'index.html.twig');
});

$app->post('/contact', function ($request, $response) {
    return $this->view->render($response, 'contact.html.twig');
})->setName('contact');

/**
 * Run app
 */
$app->run();
?>

License

MIT © Michael Mayer, (*4)

The Versions