|
<?php |
|
/** |
|
* @copyright Copyright (c) 2009-2014 Steven TITREN - www.webaki.com |
|
* @package Webaki\UserBundle\Redirection |
|
* @author Steven Titren <[email protected]> |
|
*/ |
|
|
|
namespace Webaki\UserBundle\Redirection; |
|
|
|
|
|
use Symfony\Component\HttpFoundation\RedirectResponse; |
|
use Symfony\Component\HttpFoundation\Request; |
|
use Symfony\Component\Routing\RouterInterface; |
|
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; |
|
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; |
|
|
|
class AfterLoginRedirection implements AuthenticationSuccessHandlerInterface |
|
{ |
|
/** |
|
* @var \Symfony\Component\Routing\RouterInterface |
|
*/ |
|
private $router; |
|
|
|
/** |
|
* @param RouterInterface $router |
|
*/ |
|
public function __construct(RouterInterface $router) |
|
{ |
|
$this->router = $router; |
|
} |
|
|
|
/** |
|
* @param Request $request |
|
* @param TokenInterface $token |
|
* @return RedirectResponse |
|
*/ |
|
public function onAuthenticationSuccess(Request $request, TokenInterface $token) |
|
{ |
|
// Get list of roles for current user |
|
$roles = $token->getRoles(); |
|
// Tranform this list in array |
|
$rolesTab = array_map(function($role){ |
|
return $role->getRole(); |
|
}, $roles); |
|
// If is a admin or super admin we redirect to the backoffice area |
|
if (in_array('ROLE_ADMIN', $rolesTab, true) || in_array('ROLE_SUPER_ADMIN', $rolesTab, true)) |
|
$redirection = new RedirectResponse($this->router->generate('backoffice_homepage')); |
|
// otherwise, if is a commercial user we redirect to the crm area |
|
elseif (in_array('ROLE_COMMERCIAL', $rolesTab, true)) |
|
$redirection = new RedirectResponse($this->router->generate('crm_homepage')); |
|
// otherwise we redirect user to the member area |
|
else |
|
$redirection = new RedirectResponse($this->router->generate('member_homepage')); |
|
|
|
return $redirection; |
|
} |
|
} |
@notabigboy:
1- An user have many roles. In this code the redirection is make depending the principal role of the user
for example the list roles of the user is
The principal role here is "ROLE_ADMIN"
2-The role is an attribute of the user entity. So no relationship context here.
In case, if you want to have separate roles for each user, you can create Role entity, that should implementing Symfony\Component\Security\Core\Role\RoleInterface