Disabled user by default on FOSUserbundle - symfony

I'm using FOSUserBundle and I want when each user registers to be disabled by default. The administrator will contact every user by phone and he will make user active if it's appropriate. I have read about Overriding Default FOSUserBundle Controllers but I can't figure out how to make it working. I have created RegistrationController.php in src/AppBundle/Controller/RegistrationController.php with this method inside:
<?php
/*
* This file is part of the FOSUserBundle package.
*
* (c) FriendsOfSymfony <http://friendsofsymfony.github.com/>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace FOS\UserBundle\Controller;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use FOS\UserBundle\Model\UserInterface;
/**
* Controller managing the registration
*
* #author Thibault Duplessis <thibault.duplessis#gmail.com>
* #author Christophe Coevoet <stof#notk.org>
*/
class RegistrationController extends ContainerAware
{
/**
* Receive the confirmation token from user email provider, login the user
*/
public function confirmAction($token)
{
$user = $this->container->get('fos_user.user_manager')->findUserByConfirmationToken($token);
if (null === $user) {
throw new NotFoundHttpException(sprintf('The user with confirmation token "%s" does not exist', $token));
}
$user->setConfirmationToken(null);
$user->setEnabled(false);
$user->setLastLogin(new \DateTime());
$this->container->get('fos_user.user_manager')->updateUser($user);
$response = new RedirectResponse($this->container->get('router')->generate('fos_user_registration_confirmed'));
$this->authenticateUser($user, $response);
return $response;
}
}
, but nothing works, maybe I need someone to show me the way to do it, nothing more.

For those still struggling with this question, set an observer listening the event: fos_user.registration.initialize like this (adapt you code path) :
app.listener.disable_registered_user:
class: AppBundle\Observer\DisableRegisteredUserListener
arguments:
- "#templating"
tags:
# split to multiple line for readability
# can be made into a single line like - { name: ..., event: ... , method: ... }
-
name: "kernel.event_listener"
event: "fos_user.registration.initialize"
method: "disableUser"
Then this is the content of your event listener class :
namespace AppBundle\Observer;
use FOS\UserBundle\Event\GetResponseUserEvent;
/**
* Class DisableRegisteredUserListener
* #package AppBundle\Observer
*/
class DisableRegisteredUserListener
{
/**
* #param \FOS\UserBundle\Event\GetResponseUserEvent $event
*/
public function disableUser(GetResponseUserEvent $event)
{
$user = $event->getUser();
/** #var \AppBundle\Entity\User $user */
$user->setEnabled(false);
}
}

You could just listen to the FOSUserEvents::REGISTRATION_CONFIRM and disable the registered user again before it gets persisted to the database.
As the FOSUserBundle automatically forwards the new user to the confirmedAction that requires a user to be logged in, you would need to provide your own response to override this.
Your listener...
class DisableRegisteredUserListener
{
/**
* #var EngineInterface
*/
private $templating;
/**
* #var EngineInterface $templating
*/
public function __construct(EngineInterface $templating)
{
$this->templating = $templating;
}
/**
* #var GetResponseUserEvent $event
* #return null
*/
public function disableUser(GetResponseUserEvent $event)
{
$user = $event->getUser();
$user->setEnabled(false);
$response = $this->templating->renderResponse(
'AppBundle:Registration:registration_complete.html.twig',
array(
'user' => $user,
)
);
}
}
Your services file (YAML)...
services:
app.listener.disable_registered_user:
class: AppBundle\EventListener\DisableRegisteredUserListener
arguments:
- "#templating"
tags:
# split to multiple line for readability
# can be made into a single line like - { name: ..., event: ... , method: ... }
-
name: "kernel.event_listener"
event: "fos_user.registration.confirm"
method: "disableUser"
Your AppBundle:Registration:registration_complete.html.twig could then be used to tell the new users that their account had been created but disabled and they would then be contacted by a member of your team to complete the process.

Related

Manually send password resetting email for user in FOSUserBundle

I have to create a simple user administration for a symfony 3 project.
One part of it is to start the password reset process for users.
(Yes, I know every user can trigger it himself but this is a request from our customer.)
Now I don't know how to start the process with a simple click in the admin interface for every user. Is there a method or a service in the UserBundle I can use?
There is no all in one method but this can be achieved by:
if (null === $user->getConfirmationToken()) {
$user->setConfirmationToken($this->tokenGenerator->generateToken());
}
// send email you requested
$this->mailer->sendResettingEmailMessage($user);
// this depends on requirements
$user->setPasswordRequestedAt(new \DateTime());
$this->userManager->updateUser($user);
with proper dependencies set.
Here's a service based solution written with Symfony 4.1 you can use without having to call in services form the container via get()
First you have to add an alias to services.yaml because the FOS mailer can't auto-wire:
FOS\UserBundle\Mailer\Mailer:
alias: fos_user.mailer.default
public: true
With that in place you can create the below class as service:
namespace App\Service; # change to your namespace
use FOS\UserBundle\Mailer\Mailer;
use FOS\UserBundle\Model\UserInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
/**
* Class UserPasswordResetService
*/
class UserPasswordResetService
{
/**
* #var Mailer
*/
private $mailer;
/**
* #var UserManagerInterface
*/
private $userManager;
/**
* #var TokenGeneratorInterface
*/
private $tokenGenerator;
/**
* UserPasswordResetService constructor.
*
* #param Mailer $mailer
* #param UserManagerInterface $userManager
*/
public function __construct(
Mailer $mailer,
UserManagerInterface $userManager,
TokenGeneratorInterface $tokenGenerator
)
{
$this->mailer = $mailer;
$this->userManager = $userManager;
$this->tokenGenerator = $tokenGenerator;
}
/**
* #param UserInterface $user
*/
public function resetPassword(UserInterface $user)
{
if (null === $user->getConfirmationToken()) {
$user->setConfirmationToken($this->tokenGenerator->generateToken());
}
// send email you requested
$this->mailer->sendResettingEmailMessage($user);
// this depends on requirements
$user->setPasswordRequestedAt(new \DateTime());
$this->userManager->updateUser($user);
}
}
Assuming you then add that service to a class via DI you can use it like this within a given method:
$this->passwordResetService->resetPassword($user);
From the information Kamil provided, this would be a full working function
/**
* Sends the user a new password
*
* #Route("reset_password/{id}", name="user_reset_password")
* #Security("has_role('ROLE_ADMIN')")
*
* #param User $user
* #return \Symfony\Component\HttpFoundation\RedirectResponse
*/
public function resetPasswordAction(User $user)
{
if (null === $user->getConfirmationToken()) {
/** #var $tokenGenerator TokenGeneratorInterface */
$tokenGenerator = $this->get('fos_user.util.token_generator');
$user->setConfirmationToken($tokenGenerator->generateToken());
}
$this->get('fos_user.mailer')->sendResettingEmailMessage($user);
$user->setPasswordRequestedAt(new \DateTime());
$this->get('fos_user.user_manager')->updateUser($user);
$this->addFlash('notice', "User {$user->getFullName()} got an email for resetting his password!");
return $this->redirectToRoute('user_index');
}

How to use the registration procedure of FOSUserBundle from a third controller

I have to persist an entity (let's call it Entity for simplicity) in the database that has to be referenced to a User handled with FOSUserBundle. To make this reference I have a column entity_table.userId.
When the new Entity is created, I have to:
Create the User through the registration procedure of FosUserBundle;
Get the ID of the new created User: [meta code] $userId = $get->newCreatedUserId();
Set this id in Entity: $entity->setUserId($userId);
Persist the Entity to the database.
How can I integrate the registration procedure of FosUserBundle into the controller that persists my Entity?
MORE DETAILS
In the first time I tried to simply copy the code from the method registerAction() of the RegistrationController of FOSUserBundle: a quick and dirty approach that, anyway didn't work as i get an error as the User class i passed was wrong (I passed my custom User entity I use to overwrite the bundle).
This kind of approach has also other drawbacks:
I cannot control the registration procedure (send or decide to not send confirmation e-mails, for example);
I cannot use the builtin checks on passed data;
I cannot be sure that on FOSUserBundles updates my custom method continue to work
Others I cannot imagine at the moment...
So, I'd like to create the user in the cleanest way possible: how can i do this? Which should be a good approach?
A controller forwarding?
Anyway, an "hardcoded" custom method that emulates the registerAction() method?
A custom registration form?
I have read a lot of discussions here at StackOverflow and on Internet, I read the documentation of FOSUserBundle and of Symfony too, but I cannot decide for the good approach, also because I'm not sure I have understood all the pros and cons of each method.
If someone can put me on the right way... :)
SOMETHING MORE ABOUT MY REGISTRATION FLOW
I have a getStarted procedure handled by the controller GetStarteController.
In it I have two methods:
indexAction(), that displays a registration form with only the field "email";
endAction(), that receive the form and creates a Company using the passed e-mail (it gets the domain part only of the email).
HERE IS A WORKING MESSY CODE (inside it for Companies and Stores are called some methods that exists in the source code but are not in the posted classes below, as setBrand() or setUrl(), for example).
// AppBundle/Controller/getStartedController.php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Request;
use MyVendor\UserBundle\Entity\User;
use AppBundle\Entity\Companies;
use AppBundle\Entity\Stores;
class GetStartedController extends Controller
{
/**
* #Route("getstarted")
* #Template()
*/
public function indexAction()
{
$data = array();
$form = $this->createFormBuilder($data, array(
'action' => $this->generateUrl('getStartedEnd'),
))
->add('email', 'email')
->add('submit', 'submit')
->getForm();
return array(
'form' => $form->createView(),
);
}
/**
* #Route("getstarted/end", name="getStartedEnd")
* #Template()
*/
public function endAction(Request $request)
{
$form = $this->createFormBuilder()
->add('email', 'email')
->add('submit', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$data = $form->getData();
} else {
/** #todo here we have to raise some sort of exception or error */
echo 'no data submitted (See the todo in the code)';exit;
}
// Pass the email to the template
$return['email'] = $data['email'];
// Get the domain part of the email and pass it to the template
$domain = explode('#', $data['email']);
$return['domain'] = $domain[1];
// 1) Create the new user
$user = new User();
// Get the token generator
$tokenGenerator = $this->container->get('fos_user.util.token_generator');
$user->setEmail($return['email']);
$userRandomUsername = substr($tokenGenerator->generateToken(), 0, 12);
$user->setUsername('random-' . $userRandomUsername);
$plainPassword = substr($tokenGenerator->generateToken(), 0, 12);
$encoder = $this->container->get('security.password_encoder');
$encoded = $encoder->encodePassword($user, $plainPassword);
// Set the password for the user
$user->setPassword($encoded);
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
// Perstist the user in the database
$userManager->updateUser($user);
$userId = $user->getId();
// 2) Create the Company object
$company = new Companies();
$company->setBrand($return['domain'])
->setAdded(new \DateTime())
->setOwnerId($userId);
// 3) Create the Store object
$store = new Stores();
$store->setEmail($return['email'])
->setUrl($return['domain'])
->setAdded(new \DateTime());
// Get the Entity Manager
$em = $this->getDoctrine()->getManager();
// Persist Company and get its ID
$em->persist($company);
$em->flush();
$return['companyId'] = $company->getId();
// Set the property branchOf of the Store object
$store->setBranchOf($return['companyId']);
// Persist the Store object
$em->persist($store);
$em->flush();
$return['storeId'] = $store->getId();
return $return;
}
}
Here the User Entity that ovewrites the one provided by FOSUserBundle
// MyVendor/UserBundle/Entity/User.php
namespace MyVendor\UserBundle\Entity;
use FOS\UserBundle\Model\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="prefix_user")
*/
class User extends BaseUser
{
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
public function __construct()
{
parent::__construct();
// your own logic
}
}
Some essential code of Companies.php
// AppBundle/Entity/Companies.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Companies
*
* #ORM\Table(name="companies")
* #ORM\Entity
*/
class Companies
{
/**
* #var integer
*
* #ORM\Column(name="ownerId", type="integer", nullable=false)
*/
private $ownerid;
/**
* Set ownerid
*
* #param integer $ownerid
* #return Companies
*/
public function setOwnerid($ownerid)
{
$this->ownerid = $ownerid;
return $this;
}
/**
* Get ownerid
*
* #return integer
*/
public function getOwnerid()
{
return $this->ownerid;
}
}
Some essential code of Stores.php
// AppBundle/Entity/Stores.php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Stores
*
* #ORM\Table(name="stores", uniqueConstraints={#ORM\UniqueConstraint(name="branchOf", columns={"branchOf"})})
* #ORM\Entity
*/
class Stores
{
/**
* #var integer
*
* #ORM\Column(name="branchOf", type="integer", nullable=false)
*/
private $branchof;
/**
* Set branchof
*
* #param integer $branchof
* #return Stores
*/
public function setBranchof($branchof)
{
$this->branchof = $branchof;
return $this;
}
/**
* Get branchof
*
* #return integer
*/
public function getBranchof()
{
return $this->branchof;
}
}
You can use a custom registration form but the best way is clearly to listen to registration event dispatched by FOSUser.
Here is an example :
class RegistrationListener implements EventSubscriberInterface
{
/**
* L'entity manager
*
* #var EntityManager
*/
private $em;
/**
* Constructeur de l'EventListener
*
* #param \Doctrine\ORM\EntityManager $entityManager
*/
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
/**
* {#inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
FOSUserEvents::REGISTRATION_INITIALIZE => 'onRegistrationInit',
);
}
/**
* Triggered when FOSUserEvents::REGISTRATION_INITIALIZE is caught.
*
* #param \FOS\UserBundle\Event\UserEvent $userEvent
*/
public function onRegistrationInit(UserEvent $userEvent)
{
$user = $userEvent->getUser();
// Define your own logic there
}
}
Don't forget to make this listener a service:
#services.yml
services:
oe_user.registration:
class: OrienteExpress\UserBundle\EventListener\RegistrationListener
# arguments are optional but you still can need them
# so I let the EM as example which is an often used parameter
arguments:
entityManager: "#doctrine.orm.entity_manager"
tags:
- { name: kernel.event_subscriber }
You'll find the complete list of event dispatched by FOSUser here
Moreover, Symfony entities are a model of objects. That said, you need to understand that you don't work with ids within your model, but object.
You should not use thing such as $var->setUserId() within entites. Doctrine is there to manage your relations, so be carefull about this. You might face unexpected problem by not using Symfony & Doctrine the way it has been designed for.
EDIT:
In your company entity, your relation is beetween a Company and a User objects. That means you dont need a User id in your company but just a instance of User.
I think you might go back to the basics before wanting to do advanced stuff.
Your relation beetween the user and the company should not be designed by an integer attribute but a real doctrine relation.
Ex:
class Company {
/**
* #ORM\ManyToOne(targetEntity="Path\To\User")
* #ORM\JoinColumn(nullable=false)
*/
private $owner;
/**
* #param $user User
*/
public function setUser(User $user)
{
$this->user = $user;
}
}
Then when you'll create a new company. You won't need to know the User's id or even insert it to make the link between them. But if you are not aware yet of this, once again, I think you should go back to the basics of Symfony since this is one of the most (maybe the most) important feature to master.

Symfony | FOSRestBundle with FOSFacebookBundle

I have a symfony app which serve a RESTful API(for mobile app) and have backend administration.
I can succesfuly login to the backend via facebook, but how should I allow loggin via the RESTful API?
Wooh.. after almost 12 hours(!) here is the solution for anyone who looking for too:
We need to create new custom firewall
This factory should connect to the FOSFacebook and validate the token
If it using our new firewall it should manually disable any session or cookie.
To use the firewall we need to send our token in every request
The code
First define our firewall listener
GoDisco/UserBundle/Security/Firewall/ApiFacebookListener.php
<?php
/**
* Authored by AlmogBaku
* almog.baku#gmail.com
* http://www.almogbaku.com/
*
* 9/6/13 2:17 PM
*/
namespace Godisco\UserBundle\Security\Firewall;
use FOS\FacebookBundle\Security\Authentication\Token\FacebookUserToken;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Http\Firewall\ListenerInterface;
use Symfony\Component\HttpFoundation\Session\Session;
/**
* API gateway through Facebook oAuth token: Firewall
*
* Class ApiFacebookListener
* #package Godisco\UserBundle\Security\Firewall
*/
class ApiFacebookListener implements ListenerInterface
{
/**
* #var \Symfony\Component\Security\Core\SecurityContextInterface
*/
protected $securityContext;
/**
* #var \Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface
*/
protected $authenticationManager;
/**
* #var Session
*/
protected $session;
/**
* #var string
*/
protected $providerKey;
public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, Session $session, $providerKey)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->securityContext = $securityContext;
$this->authenticationManager = $authenticationManager;
$this->session = $session;
$this->providerKey=$providerKey;
}
/**
* #param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event The event.
*/
public function handle(GetResponseEvent $event)
{
$accessToken = $event->getRequest()->get('access_token');
$token = new FacebookUserToken($this->providerKey, '', array(), $accessToken);
/**
* force always sending token
*/
$_COOKIE=array();
$this->session->clear();
try {
if($accessToken)
$returnValue = $this->authenticationManager->authenticate($token);
$this->securityContext->setToken($returnValue);
}
} catch(AuthenticationException $exception) {
if(!empty($accessToken))
$event->setResponse(new Response(array("error"=>$exception->getMessage()),401));
}
}
}
Than create a new security factory which calling our listener, and will connect the authentication to the FOSFacebookBundle.
GoDisco/UserBundle/DependencyInjection/Security/Factory/ApiFacebookFactory.php
<?php
/**
* Authored by AlmogBaku
* almog.baku#gmail.com
* http://www.almogbaku.com/
*
* 9/6/13 2:31 PM
*/
namespace GoDisco\UserBundle\DependencyInjection\Security\Factory;
use FOS\FacebookBundle\DependencyInjection\Security\Factory\FacebookFactory;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
/**
* API gateway through Facebook oAuth token: Factory
*
* Class ApiFacebookFactory
* #package GoDisco\UserBundle\DependencyInjection\Security\Factory
*/
class ApiFacebookFactory extends FacebookFactory
{
/**
* {#inheritdoc}
*/
public function getKey()
{
return 'api_facebook';
}
/**
* {#inheritdoc}
*/
public function addConfiguration(NodeDefinition $node)
{
$builder = $node->children();
$builder
->scalarNode('provider')->end()
->booleanNode('remember_me')->defaultFalse()->end()
;
foreach ($this->options as $name => $default) {
if (is_bool($default)) {
$builder->booleanNode($name)->defaultValue($default);
} else {
$builder->scalarNode($name)->defaultValue($default);
}
}
}
/**
* {#inheritdoc}
*/
protected function createEntryPoint($container, $id, $config, $defaultEntryPointId)
{
return null;
}
/**
* {#inheritdoc}
*/
protected function createListener($container, $id, $config, $userProvider)
{
$listenerId = "api_facebook.security.authentication.listener";
$listener = new DefinitionDecorator($listenerId);
$listener->replaceArgument(3, $id);
$listenerId .= '.'.$id;
$container->setDefinition($listenerId, $listener);
return $listenerId;
}
}
Defining the listener service, so we can inject the arguments
GoDisco/UserBundle/Resources/config/services.yml
services:
api_facebook.security.authentication.listener:
class: GoDisco\UserBundle\Security\Firewall\ApiFacebookListener
arguments: ['#security.context', '#security.authentication.manager', '#session', '']
Defining our new firewall!
app/config/security.yml
security:
api:
pattern: ^/api
api_facebook:
provider: godisco_facebook_provider
stateless: true
anonymous: true
main:
...
You need to implement oAuth authentication from your client app.
This was answered before:
How to restfully login, Symfony2 Security, FOSUserBundle, FOSRestBundle?

Sonata admin and Custom Security handler

I wanna write a custom Security handler and this will be a simple ACL which restrict data by user id. I don't want use a standart ACL, no need to use all functional and create aditional database with permissions.
So I create my new handler and now I recieve $object as Admin class. With Admin class I can restrict access to services but can't restrict any rows in service.
The question is how I can recieve Entities and check permission on Entities like this:
public function isGranted(AdminInterface $admin, $attributes, $object = null)
{
if ($object->getUserId()==5){
return true
}
}
Overwrite the security handler in sonata config:
sonata_admin:
title: "Admin"
security:
handler: custom.sonata.security.handler.role
Create your service:
custom.sonata.security.handler.role:
class: MyApp\MyBundle\Security\Handler\CustomRoleSecurityHandler
arguments:
- #security.context
- [ROLE_SUPER_ADMIN, ROLE_ADMIN, ROLE_USER]
- %security.role_hierarchy.roles%
Last step, but not less important is to create your class, retrieve your user and based by his credentials allow/deny access:
/**
* Class CustomRoleSecurityHandler
*/
class CustomRoleSecurityHandler extends RoleSecurityHandler
{
protected $securityContext;
protected $superAdminRoles;
protected $roles;
/**
* #param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext
* #param array $superAdminRoles
* #param $roles
*/
public function __construct(SecurityContextInterface $securityContext, array $superAdminRoles, $roles)
{
$this->securityContext = $securityContext;
$this->superAdminRoles = $superAdminRoles;
$this->roles = $roles;
}
/**
* {#inheritDoc}
*/
public function isGranted(AdminInterface $admin, $attributes, $object = null)
{
/** #var $user User */
$user = $this->securityContext->getToken()->getUser();
if ($user->hasRole('ROLE_ADMIN')){
return true;
}
// do your stuff
}
}

FOSUser Bundle, Symfony Landing Page

I am using the FOSUser Bundle for Symfony... My question is;
I have two different group of users.... For example; Teachers and Students, which it is set when they register to the system. (using the user table of FOSUser Bundle)
After a successful login, I want to user to go to the correct landing page.. So
If the user is a teacher, I want the user to go to /teacher and for student to /student.
What is the best way to approach this?
Thanks
You need an event listener to listen for an login event. Then you can route the client to different pages based on their roles.
services.yml:
services:
login_listener:
class: Acme\UserBundle\Listener\LoginListener
arguments: [#security.context, #doctrine]
tags:
- { name: kernel.event_listener, event: security.interactive_login }
LoginListener:
<?php
namespace Acme\UserBundle\Listener;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\SecurityContext;
use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.1.x
// use Symfony\Bundle\DoctrineBundle\Registry as Doctrine; // for Symfony 2.0.x
/**
* Custom login listener.
*/
class LoginListener
{
/** #var \Symfony\Component\Security\Core\SecurityContext */
private $securityContext;
/** #var \Doctrine\ORM\EntityManager */
private $em;
/**
* Constructor
*
* #param SecurityContext $securityContext
* #param Doctrine $doctrine
*/
public function __construct(SecurityContext $securityContext, Doctrine $doctrine)
{
$this->securityContext = $securityContext;
$this->em = $doctrine->getEntityManager();
}
/**
* Do the magic.
*
* #param Event $event
*/
public function onSecurityInteractiveLogin(Event $event)
{
if ($this->securityContext->isGranted('ROLE_1')) {
// redirect 1
}
if ($this->securityContext->isGranted('ROLE_2')) {
// redirect 2
}
// do some other magic here
$user = $this->securityContext->getToken()->getUser();
// ...
}
}
From: http://www.metod.si/login-event-listener-in-symfony2/

Resources