flintci/jquery-ujs-bundle

Symfony bundle adapter for jQuery-ujs and CSRF protection

Installs: 89

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 2

Forks: 0

Open Issues: 0

Type:symfony-bundle

v0.1.0 2018-02-02 00:41 UTC

This package is not auto-updated.

Last update: 2024-10-27 05:09:53 UTC


README

Symfony bundle adapter for jQuery-ujs and CSRF protection.

Latest Stable Version Latest Unstable Version License

Total Downloads Monthly Downloads Daily Downloads

Build Status Coverage Status

Installation

Install the bundle with composer:

composer require flintci/jquery-ujs-bundle

Configuration

Enable the bundle. It is already done if you use Symfony Flex.

// config/bundles.php

return [
    FlintCI\jQueryUJSBundle\FlintCIjQueryUJSBundle::class => ['all' => true],
];

Add the metas.html.twig template file on the <head> part:

{# base.html.twig #}

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        {% include '@FlintCIjQueryUJS/metas.html.twig' %}
    </head>
    {# ... #}
</html>

Finally, install jquery-ujs with Yarn or NPM and include the rails.js file.

Example on a app.js file using WebPack:

import 'jquery-ujs';

Then, you are good to go!

Usage

Start using jquery-ujs by writing this special link:

<a href="{{ path('account_delete') }}" data-method="delete" data-confirm="Are you sure?">

Then you can manually verify the CSRF validity on the controller:

namespace App\Controller;

use FlintCI\jQueryUJSBundle\Security\Csrf\UjsCsrfManager;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;

/**
 * @Route("/account")
 */
final class AccountController extends Controller
{
    /**
     * @Route("/")
     * @Method("DELETE")
     */
    public function deleteAction(UjsCsrfManager $ujsCsrfManager): Response
    {
        if (!$ujsCsrfManager->isTokenValid()) {
            throw new BadRequestHttpException('Invalid token.');
        }
        
        // ...
    }
}

Or directly with the annotation:

namespace App\Controller;

use FlintCI\jQueryUJSBundle\Annotations\UjsCsrf;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("/account")
 */
final class AccountController extends Controller
{
    /**
     * @Route("/")
     * @Method("DELETE")
     * @UjsCsrf
     */
    public function deleteAction(): Response
    {
        // Nothing to check here. A bad request excpetion will be thrown if the token is invalid.
    }
}