Setting a Default User Role in FOSUserBundle

I had to dig for this information, so I thought I’d collect it all in one place for ease of use in the future.

So, FOSUserBundle doesn’t come with any default permissions for your users. It’s a good thing too, because the implementation may not be suited to your project; however, it does give you a very simple way to set it up.

Events

You need to set up an event subscriber which listens to FOSUserBundle’s REGISTRATION_SUCCESS event. You can configure this in your config/services.yml

services:
    # User Default Role
    app.exception_subscriber:
        class: AppBundle\Event\Subscriber\UserDefaultRole
        tags:
            - { name: kernel.event_subscriber }

Next you need to create your event subscriber

<?php

namespace AppBundle\Event\Subscriber;

use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\FOSUserEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class UserDefaultRole implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return [
            FOSUserEvents::REGISTRATION_SUCCESS => 'onRegistrationSuccess'
        ];
    }

    public function onRegistrationSuccess(FormEvent $event)
    {
        $rolesArr = ['ROLE_USER'];

        /** @var $user \FOS\UserBundle\Model\UserInterface */
        $user = $event->getForm()->getData();
        $user->setRoles($rolesArr);
    }
}

Modification to your User Entity

Unfortunately, your event isn’t capable of doing this by itself, because the default FOSUserBundle behaviour sneakily overrides it, so we’ll need to do some overriding of our own.

Within your User Entity, you’ll need to override the addRoles method to ensure that your new configuration can work as expected.

public function addRole($role)
{
    $role = strtoupper($role);

    if (!in_array($role, $this->roles, true)) {
        $this->roles[] = $role;
    }

    return $this;
}

Summary

What’s happening here in total is that we are setting up an event subscriber that’ll fire each time a user registers in your application – this fires prior to persistence. Within that event, we are setting the role to your default. As mentioned, all of this happens prior to persistence so by the time that comes around, the user object is loaded with the role you want to load.

Credit:

FOSUserBundle Hooking Into Controllers
StackOverflow. A combination between RayOnAir’s answer and andrew’s answer.

Advertisements
Setting a Default User Role in FOSUserBundle

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s