Archives de
Tag: fosuser

API Platform + FOSUserBundle + LexikJWTAuthenticationBundle

API Platform + FOSUserBundle + LexikJWTAuthenticationBundle

  • Symfony: 3.2.2
  • API Platform: 2.0.3
  • FOSUserBundle: 2.0.0-beta2
  • LexikJWTAuthenticationBundle: 2.1.1

En premier lieu nous allons cloner le dépôt API Plaftorm:

composer create-project api-platform/api-platform bookshop-api

Une fois fait, nous installons FOSUserBundle et LexikJWTAuthenticationBundle via composer:

composer require friendsofsymfony/user-bundle:2.0.0-beta-2
composer require lexik/jwt-authentication-bundle

Puis nous activons les bundles fraichement installé dans AppKernel.php:

public function registerBundles()
{
    return array(
        // ...
        new FOS\UserBundle\FOSUserBundle(),
        new Lexik\Bundle\JWTAuthenticationBundle\LexikJWTAuthenticationBundle(),
    );
}

Nous créons notre entité User.php:

<?php

namespace AppBundle\Entity;

use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use FOS\UserBundle\Model\User as BaseUser;
use FOS\UserBundle\Model\UserInterface;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * @ORM\Entity
 * @ApiResource(attributes={
 *     "normalization_context"={"groups"={"user", "user-read"}},
 *     "denormalization_context"={"groups"={"user", "user-write"}}
 * })
 */
class User extends BaseUser
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @Groups({"user"})
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Groups({"user"})
     */
    protected $fullname;

    /**
     * @Groups({"user-write"})
     */
    protected $plainPassword;

    /**
     * @Groups({"user"})
     */
    protected $username;

    public function setFullname($fullname)
    {
        $this->fullname = $fullname;

        return $this;
    }
    public function getFullname()
    {
        return $this->fullname;
    }

    public function isUser(UserInterface $user = null)
    {
        return $user instanceof self && $user->id === $this->id;
    }
}

Nous poursuivons par la génération des clés, notez bien la pass phrase qu’il faudra copié dans le fichier parameters.yml

mkdir -p var/jwt # For Symfony3+, no need of the -p option
openssl genrsa -out var/jwt/private.pem -aes256 4096
openssl rsa -pubout -in var/jwt/private.pem -out var/jwt/public.pem

Nous mettons a jours les fichier suivants:

config.yml:

framework:
    translator:      { fallbacks: ["%locale%"] }

fos_user:
    db_driver: orm # other valid values are 'mongodb', 'couchdb' and 'propel'
    firewall_name: main
    user_class: AppBundle\Entity\User

lexik_jwt_authentication:
    private_key_path: '%jwt_private_key_path%'
    public_key_path:  '%jwt_public_key_path%'
    pass_phrase:      '%jwt_key_pass_phrase%'
    token_ttl:        '%jwt_token_ttl%'

routing.yml

api:
    resource: '.'
    type:     'api_platform'

app:
    resource: '@AppBundle/Action/'
    type:     'annotation'

api_login_check:
    path: /api/login_check

fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /profile

security.yml

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: bcrypt

    role_hierarchy:
        ROLE_READER: ROLE_USER
        ROLE_ADMIN: ROLE_READER

    providers:
        fos_userbundle:
            id: fos_user.user_provider.username_email

    firewalls:
        login:
            pattern:  ^/login
            stateless: true
            anonymous: true
            provider: fos_userbundle
            form_login:
                check_path: /login_check
                username_parameter: _username
                password_parameter: _password
                success_handler: lexik_jwt_authentication.handler.authentication_success
                failure_handler: lexik_jwt_authentication.handler.authentication_failure
                require_previous_session: false

        main:
            pattern: ^/
            provider: fos_userbundle
            stateless: true
            anonymous: true
            lexik_jwt: ~

        # disables authentication for assets and the profiler, adapt it according to your needs
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

    access_control:
        - { path: ^/login, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/books, roles: [ ROLE_READER ] }
        - { path: ^/, roles: [ ROLE_READER ] }

parameters.yml.dist et parameters.yml, n’oubliez pas la pass phrase pour les clés

parameters:
    # ...
    jwt_private_key_path: '%kernel.root_dir%/../var/jwt/private.pem' # ssh private key path
    jwt_public_key_path:  '%kernel.root_dir%/../var/jwt/public.pem'  # ssh public key path
    jwt_key_pass_phrase:  ''                                         # ssh key pass phrase
    jwt_token_ttl:        3600

Puis nous mettons à jour la base de données et créons notre premier utilisateur:

php bin/console doctrine:schema:update --force
php bin/console fos:user:create testuser test@example.com p@ssword
php bin/console fos:user:promote testuser ROLE_READER

Pour tester ca un petit coup de Curl:

curl -X POST http://127.0.0.1:8000/login_check -d _username=test@example.com -d _password=p@ssword

Et comme réponse nous avons:

{"token":"eyJhbGciOiJSUzI1NiJ9.eyJyb2xlcyI6WyJST0xFX1JFQURFUiIsIlJPTEVfVVNFUiJdLCJ1c2VybmFtZSI6InRlc3R1c2VyIiwiZXhwIjoxNDg2NDk5MjczLCJpYXQiOjE0ODY0OTU2NzN9.RL8VS8MuKhvg0uW23TPnlxsZusUIE86YuE_cg44F4rToe8c7zV6s-2lmuOhP5CyeB50IVfLlb4-RC1frKQFTIrEA1LJ2FewxKFO2Mb2sIQwQonAew3MTwnxbnPRWrS0sQCsb1NbXTxohc5WH-BU1U3IkuAjuTVLcB3g7JlPor0yedUU766BRXjIhklN7IuILKsjhteqGK6F9Ilg0zmLyjQV3-BUg1nnWygQ-O4BLrU_InvhpHZVOnPfikMftcKVAhn_Z4GKGVVORQxplhc4i0lJgzdV83AaImYqOzn3WBJxKnzmitb6rnOJ-SKXjdAYRix_rFwqIzzWNdcAg1-C731b08I3qcfWXmmadI2GsygVpemlagH8v6tcFjwVsyazblqFCA8oy37N0CfSVt7av8GIbenWtIDUS5Tl3a0SMxmcwg6rlTL_1pE0-E8mPa8ZbLho-nON2hKoQcG1LhIeuatzIi7lUSLCQv_uzy29Hpq7PPJ_43cZZDdex-vk3BVHbjZCOcggVxp-mDDTcU7VxZFwmi8AiP9ZAg8AFXviKcfM7D5Er2tB2k3HHsnCqTSGRJe9czNs-GaW55748BK_u0UiEBvBdDHUgmbGw4UTRw8aNTY8p8M_tavezC36p5zilyd2CB6knsLtm0aRkqyZaiK27uvajYMt65BpxqsmXzLw"}

Et voila !!!

Disponible sur github.

Ajouter un champ a un utilisateur avec le bundle sonatauserbundle [FR]

Ajouter un champ a un utilisateur avec le bundle sonatauserbundle [FR]

Si vous utilisez le bundle sonata-user-bundle il y a de fortes chances pour que vous ayez utilisé le bundle sonata-easy-extends afin de généré votre bundle de gestion des utilisateurs.

J’ai découvert ce weekend qu’afin d’ajouter un nouveau champ sur un utilisateur lors de l’utilisation du bundle sonatauserbundle, il faut modifier le fichier Application/Sonata/UserBundle/Resources/config/doctrine/User.orm.xml

 

Symfony2.1 + sonata-admin + sonata-user +fos-userbundle [EN]

Symfony2.1 + sonata-admin + sonata-user +fos-userbundle [EN]

Hy, everybody, today we will see how to install Symfony2.1 and the following bundles:

  • FOSUserBundle
  • SonataAdminBundle
  • SonataUserBundle

tl;dr: There is a GitHub repository with the project.

The first step is to create the project with the following command line:

composer create-project symfony/framework-standard-edition sonataadmin.fr

Then we edit the composer.json file to add the bundles:

"sonata-project/admin-bundle": "dev-master",
"friendsofsymfony/user-bundle": "dev-master",
"sonata-project/user-bundle": "dev-master",
"sonata-project/doctrine-orm-admin-bundle": "dev-master"

Update the AppKernel.php file to add the following bundles:

new FOS\UserBundle\FOSUserBundle(),
new Sonata\jQueryBundle\SonatajQueryBundle(),
new Sonata\AdminBundle\SonataAdminBundle(),
new Sonata\BlockBundle\SonataBlockBundle(),
new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),

As Sonata Admin Bundle need the translation, we turn in on in the config.yml

framework:
    #esi:             ~
    translator:      { fallback: "%locale%" }
    secret:          "%secret%"

And we add the configuration for fosuserbundle and sonata admin in the config.yml:

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Application\Sonata\UserBundle\Entity\User

sonata_block:
    default_contexts: [cms]
    blocks:
        sonata.admin.block.admin_list:
            contexts:   [admin]

        #sonata.admin_doctrine_orm.block.audit:
        #    contexts:   [admin]

        sonata.block.service.text:
        sonata.block.service.action:
        sonata.block.service.rss:

        # Some specific block from the SonataMediaBundle
        #sonata.media.block.media:
        #sonata.media.block.gallery:
        #sonata.media.block.feature_media:

sonata_admin:
    title:      Admin Panel
    title_logo: /bundles/sonataadmin/logo_title.png
    templates:
        # default global templates
        layout:  SonataAdminBundle::standard_layout.html.twig
        ajax:    SonataAdminBundle::ajax_layout.html.twig

        # default actions templates, should extend a global templates
        list:    SonataAdminBundle:CRUD:list.html.twig
        show:    SonataAdminBundle:CRUD:show.html.twig
        edit:    SonataAdminBundle:CRUD:edit.html.twig
    dashboard:
        blocks:
            # display a dashboard block
            - { position: left, type: sonata.admin.block.admin_list }

sonata_doctrine_orm_admin:
    # default value is null, so doctrine uses the value defined in the configuration
    entity_manager: ~

    templates:
        form:
            - SonataDoctrineORMAdminBundle:Form:form_admin_fields.html.twig
        filter:
            - SonataDoctrineORMAdminBundle:Form:filter_admin_fields.html.twig
        types:
            list:
                array:      SonataAdminBundle:CRUD:list_array.html.twig
                boolean:    SonataAdminBundle:CRUD:list_boolean.html.twig
                date:       SonataAdminBundle:CRUD:list_date.html.twig
                time:       SonataAdminBundle:CRUD:list_time.html.twig
                datetime:   SonataAdminBundle:CRUD:list_datetime.html.twig
                text:       SonataAdminBundle:CRUD:base_list_field.html.twig
                trans:      SonataAdminBundle:CRUD:list_trans.html.twig
                string:     SonataAdminBundle:CRUD:base_list_field.html.twig
                smallint:   SonataAdminBundle:CRUD:base_list_field.html.twig
                bigint:     SonataAdminBundle:CRUD:base_list_field.html.twig
                integer:    SonataAdminBundle:CRUD:base_list_field.html.twig
                decimal:    SonataAdminBundle:CRUD:base_list_field.html.twig
                identifier: SonataAdminBundle:CRUD:base_list_field.html.twig

            show:
                array:      SonataAdminBundle:CRUD:show_array.html.twig
                boolean:    SonataAdminBundle:CRUD:show_boolean.html.twig
                date:       SonataAdminBundle:CRUD:show_date.html.twig
                time:       SonataAdminBundle:CRUD:show_time.html.twig
                datetime:   SonataAdminBundle:CRUD:show_datetime.html.twig
                text:       SonataAdminBundle:CRUD:base_show_field.html.twig
                trans:      SonataAdminBundle:CRUD:show_trans.html.twig
                string:     SonataAdminBundle:CRUD:base_show_field.html.twig
                smallint:   SonataAdminBundle:CRUD:base_show_field.html.twig
                bigint:     SonataAdminBundle:CRUD:base_show_field.html.twig
                integer:    SonataAdminBundle:CRUD:base_show_field.html.twig
                decimal:    SonataAdminBundle:CRUD:base_show_field.html.twig

Since it’s an admin bundle we setup the security in the security.yml file:

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
        SONATA:
            - ROLE_SONATA_PAGE_ADMIN_PAGE_EDIT  # if you are not using acl then this line must be uncommented

    providers:
        fos_userbundle:
            id: fos_user.user_manager

    firewalls:

        # -> custom firewall for the admin area of the URL
        admin:
            pattern:      /admin(.*)
            form_login:
                provider:       fos_userbundle
                login_path:     /admin/login
                use_forward:    false
                check_path:     /admin/login_check
                failure_path:   null
            logout:
                path:           /admin/logout
            anonymous:    true
        # -> end custom configuration

        # defaut login area for standard users
        main:
            pattern:      .*
            form_login:
                provider:       fos_userbundle
                login_path:     /login
                use_forward:    false
                check_path:     /login_check
                failure_path:   null
            logout:       true
            anonymous:    true

    access_control:
        # URL of FOSUserBundle which need to be available to anonymous users
        - { path: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/_profiler, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }

        # -> custom access control for the admin area of the URL
        - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/login-check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        # -> end

        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }

        # Secured part of the site
        # This config requires being logged for the whole site and having the admin role for the admin part.
        # Change these rules to adapt them to your needs
        - { path: ^/admin, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN] }
        - { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }

Using the smyfony console we now generate the configuration for the user admin thanks to the SonataEasyExtendsBundle: app/console sonata:easy-extends:generate SonataUserBundle The bundle is created into the app folder, move it to src.

Once it done add this new bundle to the AppKernel.php:

new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),

We have now to care of the entity and update them with @ORM annotation:

<?php

namespace Application\Sonata\UserBundle\Entity;

use Sonata\UserBundle\Entity\BaseGroup as BaseGroup;
use Doctrine\ORM\Mapping as ORM;

/**
 * This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/easy-extends )
 *
 * References :
 *   working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
 *
 * @ORM\Entity
 * @ORM\Table(name="group")
 */
class Group extends BaseGroup
{

    /**
     * @var integer $id
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer $id
     */
    public function getId()
    {
        return $this->id;
    }
}
<?php

namespace Application\Sonata\UserBundle\Entity;

use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/easy-extends )
 *
 * References :
 *   working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
 *
 * @ORM\Entity
 * @ORM\Table(name="dayo_user")
 */
class User extends BaseUser
{

    /**
     * @var integer $id
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer $id
     */
    public function getId()
    {
        return $this->id;
    }
}

In the config.yml file, in the doctrine section we have to add the support for json:

doctrine:
    dbal:
        //...
        types:
            json: Sonata\Doctrine\Types\JsonType

That being done, the database need to be created or updated. Depending on your need use one of the following command:

app/console doctrine:schema:create for the creation

app/console doctrine:schema:update --force for the update

After that, install the assets with app/console assets:install web

In order to use our admin dashboard we have to import the route in routing.yml:

fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /change-password

soanata_user:
    resource: '@SonataUserBundle/Resources/config/routing/admin_security.xml'
    prefix: /admin

admin:
    resource: '@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
    prefix: /admin

_sonata_admin:
    resource: .
    type: sonata_admin
    prefix: /admin

# error-prevention
homepage:
 pattern: /

Last step if we didn’t already have a user, we create one:

app/console fos:user:create admintest admin@test.com pass --super-admin

You just have to go to http://sonataadmin.fr.dev/admin/dashboard and log on with the user and you should see this dashboard:

In a next article we will see how to add new elements to the admin dashboard.

P.S. a GitHub repository is available : https://github.com/dayofr/sonataadmin.fr

Symfony2.1 + sonata-admin + sonata-user +fos-userbundle [FR]

Symfony2.1 + sonata-admin + sonata-user +fos-userbundle [FR]

Salut à vous, aujourd’hui nous allons voir comment installer Symfony2.1 et les bundles suivants:

  • FOSUserBundle
  • SonataAdminBundle
  • SonataUserBundle

La première étape est bien entendu la création du projet à l’aide de la commande suivante:

composer create-project symfony/framework-standard-edition sonataadmin.fr

Éditez le fichier composer.json pour y rajouter les bundles suivants :

"sonata-project/admin-bundle": "dev-master",
"friendsofsymfony/user-bundle": "dev-master",
"sonata-project/user-bundle": "dev-master",
"sonata-project/doctrine-orm-admin-bundle": "dev-master"

Mettez à jour votre fichier AppKernel.php avec les bundles suivants :

new FOS\UserBundle\FOSUserBundle(),
new Sonata\jQueryBundle\SonatajQueryBundle(),
new Sonata\AdminBundle\SonataAdminBundle(),
new Sonata\BlockBundle\SonataBlockBundle(),
new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
new Knp\Bundle\MenuBundle\KnpMenuBundle(),
new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),

Modifier votre fichier config.yml afin d’activer la traduction

framework:
    #esi:             ~
    translator:      { fallback: "%locale%" }
    secret:          "%secret%"

Dans votre fichier config.yml rajoutez le contenu suivant:

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: Application\Sonata\UserBundle\Entity\User

sonata_block:
    default_contexts: [cms]
    blocks:
        sonata.admin.block.admin_list:
            contexts:   [admin]

        #sonata.admin_doctrine_orm.block.audit:
        #    contexts:   [admin]

        sonata.block.service.text:
        sonata.block.service.action:
        sonata.block.service.rss:

        # Some specific block from the SonataMediaBundle
        #sonata.media.block.media:
        #sonata.media.block.gallery:
        #sonata.media.block.feature_media:

sonata_admin:
    title:      Admin Panel
    title_logo: /bundles/sonataadmin/logo_title.png
    templates:
        # default global templates
        layout:  SonataAdminBundle::standard_layout.html.twig
        ajax:    SonataAdminBundle::ajax_layout.html.twig

        # default actions templates, should extend a global templates
        list:    SonataAdminBundle:CRUD:list.html.twig
        show:    SonataAdminBundle:CRUD:show.html.twig
        edit:    SonataAdminBundle:CRUD:edit.html.twig
    dashboard:
        blocks:
            # display a dashboard block
            - { position: left, type: sonata.admin.block.admin_list }

sonata_doctrine_orm_admin:
    # default value is null, so doctrine uses the value defined in the configuration
    entity_manager: ~

    templates:
        form:
            - SonataDoctrineORMAdminBundle:Form:form_admin_fields.html.twig
        filter:
            - SonataDoctrineORMAdminBundle:Form:filter_admin_fields.html.twig
        types:
            list:
                array:      SonataAdminBundle:CRUD:list_array.html.twig
                boolean:    SonataAdminBundle:CRUD:list_boolean.html.twig
                date:       SonataAdminBundle:CRUD:list_date.html.twig
                time:       SonataAdminBundle:CRUD:list_time.html.twig
                datetime:   SonataAdminBundle:CRUD:list_datetime.html.twig
                text:       SonataAdminBundle:CRUD:base_list_field.html.twig
                trans:      SonataAdminBundle:CRUD:list_trans.html.twig
                string:     SonataAdminBundle:CRUD:base_list_field.html.twig
                smallint:   SonataAdminBundle:CRUD:base_list_field.html.twig
                bigint:     SonataAdminBundle:CRUD:base_list_field.html.twig
                integer:    SonataAdminBundle:CRUD:base_list_field.html.twig
                decimal:    SonataAdminBundle:CRUD:base_list_field.html.twig
                identifier: SonataAdminBundle:CRUD:base_list_field.html.twig

            show:
                array:      SonataAdminBundle:CRUD:show_array.html.twig
                boolean:    SonataAdminBundle:CRUD:show_boolean.html.twig
                date:       SonataAdminBundle:CRUD:show_date.html.twig
                time:       SonataAdminBundle:CRUD:show_time.html.twig
                datetime:   SonataAdminBundle:CRUD:show_datetime.html.twig
                text:       SonataAdminBundle:CRUD:base_show_field.html.twig
                trans:      SonataAdminBundle:CRUD:show_trans.html.twig
                string:     SonataAdminBundle:CRUD:base_show_field.html.twig
                smallint:   SonataAdminBundle:CRUD:base_show_field.html.twig
                bigint:     SonataAdminBundle:CRUD:base_show_field.html.twig
                integer:    SonataAdminBundle:CRUD:base_show_field.html.twig
                decimal:    SonataAdminBundle:CRUD:base_show_field.html.twig

Ensuite au tour du security.yml:

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    role_hierarchy:
        ROLE_ADMIN:       ROLE_USER
        ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
        SONATA:
            - ROLE_SONATA_PAGE_ADMIN_PAGE_EDIT  # if you are not using acl then this line must be uncommented

    providers:
        fos_userbundle:
            id: fos_user.user_manager

    firewalls:

        # -> custom firewall for the admin area of the URL
        admin:
            pattern:      /admin(.*)
            form_login:
                provider:       fos_userbundle
                login_path:     /admin/login
                use_forward:    false
                check_path:     /admin/login_check
                failure_path:   null
            logout:
                path:           /admin/logout
            anonymous:    true
        # -> end custom configuration

        # defaut login area for standard users
        main:
            pattern:      .*
            form_login:
                provider:       fos_userbundle
                login_path:     /login
                use_forward:    false
                check_path:     /login_check
                failure_path:   null
            logout:       true
            anonymous:    true

    access_control:
        # URL of FOSUserBundle which need to be available to anonymous users
        - { path: ^/_wdt, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/_profiler, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }

        # -> custom access control for the admin area of the URL
        - { path: ^/admin/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/logout$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/admin/login-check$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        # -> end

        - { path: ^/register, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/resetting, role: IS_AUTHENTICATED_ANONYMOUSLY }

        # Secured part of the site
        # This config requires being logged for the whole site and having the admin role for the admin part.
        # Change these rules to adapt them to your needs
        - { path: ^/admin, role: [ROLE_ADMIN, ROLE_SONATA_ADMIN] }
        - { path: ^/.*, role: IS_AUTHENTICATED_ANONYMOUSLY }

A l’aide de la commande suivante : app/console sonata:easy-extends:generate SonataUserBundle nous allons généré la partie admin pour les utilisateurs. Le code généré se trouve dans le dossier app, déplacez le dans le dossier src.

Une fois fait, ajoutez le nouveau bundle dans le fichier AppKernel.php.

new Application\Sonata\UserBundle\ApplicationSonataUserBundle(),

Mettez alors a jour les deux entités avec les annotations @ORM.

<?php

namespace Application\Sonata\UserBundle\Entity;

use Sonata\UserBundle\Entity\BaseGroup as BaseGroup;
use Doctrine\ORM\Mapping as ORM;

/**
 * This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/easy-extends )
 *
 * References :
 *   working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
 *
 * @ORM\Entity
 * @ORM\Table(name="group")
 */
class Group extends BaseGroup
{

    /**
     * @var integer $id
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer $id
     */
    public function getId()
    {
        return $this->id;
    }
}
<?php

namespace Application\Sonata\UserBundle\Entity;

use Sonata\UserBundle\Entity\BaseUser as BaseUser;
use Doctrine\ORM\Mapping as ORM;

/**
 * This file has been generated by the Sonata EasyExtends bundle ( http://sonata-project.org/easy-extends )
 *
 * References :
 *   working with object : http://www.doctrine-project.org/projects/orm/2.0/docs/reference/working-with-objects/en
 *
 * @ORM\Entity
 * @ORM\Table(name="dayo_user")
 */
class User extends BaseUser
{

    /**
     * @var integer $id
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * Get id
     *
     * @return integer $id
     */
    public function getId()
    {
        return $this->id;
    }
}

Nous devons ensuite ajouter le support du json a doctrine avec le code suivant dans le fichier config.yml.

doctrine:
    dbal:
        //...
        types:
            json: Sonata\Doctrine\Types\JsonType

Une fois fait, il nous faut créé ou mettre à jour la base données. En fonction de votre besoin, utilisez l’une ou l’autre de ces commandes:

app/console doctrine:schema:create pour la création

app/console doctrine:schema:update --force pour la mise à jour

S’en suis l’installation des assets avec app/console assets:install web

Afin de pouvoir accéder à notre espace admin il faut importer les routes dans le fichier routing.yml

fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

fos_user_profile:
    resource: "@FOSUserBundle/Resources/config/routing/profile.xml"
    prefix: /profile

fos_user_register:
    resource: "@FOSUserBundle/Resources/config/routing/registration.xml"
    prefix: /register

fos_user_resetting:
    resource: "@FOSUserBundle/Resources/config/routing/resetting.xml"
    prefix: /resetting

fos_user_change_password:
    resource: "@FOSUserBundle/Resources/config/routing/change_password.xml"
    prefix: /change-password

soanata_user:
    resource: '@SonataUserBundle/Resources/config/routing/admin_security.xml'
    prefix: /admin

admin:
    resource: '@SonataAdminBundle/Resources/config/routing/sonata_admin.xml'
    prefix: /admin

_sonata_admin:
    resource: .
    type: sonata_admin
    prefix: /admin

# error-prevention
homepage:
 pattern: /

Dernière étape, la création du premier utilisateur avec la commande suivante:

app/console fos:user:create admintest admin@test.com pass --super-admin

Rendez-vous alors sur http://sonataadmin.fr.dev/admin/dashboard puis connectez-vous avec l’utilisateur précédemment créé. Vous devriez alors avoir le dashboard suivant :

Dans un prochain article, nous verrons comment ajouter des éléments au générateur.

P.S. un dépôt github est disponible a l’adresse suivante : https://github.com/dayofr/sonataadmin.fr