flintci/jquery-ujs-bundle

Symfony组件适配器,用于jQuery-ujs和CSRF保护

安装: 89

依赖: 0

建议者: 0

安全: 0

星标: 0

关注者: 2

分支: 0

开放问题: 0

类型:symfony-bundle

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

This package is not auto-updated.

Last update: 2024-09-15 04:31:35 UTC


README

Symfony组件适配器,用于jQuery-ujs和CSRF保护。

Latest Stable Version Latest Unstable Version License

Total Downloads Monthly Downloads Daily Downloads

Build Status Coverage Status

安装

使用Composer安装组件

composer require flintci/jquery-ujs-bundle

配置

启用组件。如果你使用Symfony Flex,则已自动完成。

// config/bundles.php

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

在部分添加metas.html.twig模板文件

{# base.html.twig #}

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

最后,使用YarnNPM安装jquery-ujs,并包含rails.js文件。

使用Webpack的app.js文件示例

import 'jquery-ujs';

然后,你就可以开始使用了!

用法

通过编写这个特殊链接开始使用jQuery-ujs:

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

然后在控制器上手动验证CSRF的有效性

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.');
        }
        
        // ...
    }
}

或直接使用注解

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.
    }
}