Intereting Posts
Как выбрать первые 10 слов предложения? помощь по созданию базовой поисковой системы php Преобразование данных формы HTML в файл PDF с использованием PHP Выбор варианта Laravel – проблема по умолчанию Как определить, открывают ли пользователь две вкладки для одного сеанса? php и jquery progress bar получить строку ошибки сокета при сбое асинхронного подключения Как получить строку из HTML с регулярным выражением? Веб-сайт подходит для экрана для планшетов, видовое окно не работает? отправка запроса с https на http из chrome extension Функция php mail (): как отображать изображения и использовать стиль в сообщении html Сохранить удаленный файл, который подталкивает заголовки, чтобы принудительно загрузить Проблема с обновлением поля MySQL с помощью PHP Получение видеоинформации с использованием FFMPEG или, возможно, HTML5 Как сначала сделать первую часть сайта? (Как в Google PageSpeed)

перенаправить после входа в систему fos user bundle symfony

У меня есть пакет, который расширяет набор пользователей fos и другой пакет.
Я хочу, чтобы пользователь аутентифицировался, чтобы перенаправить его в зависимости от его роли администратора или простого пользователя в разных представлениях.
Моя проблема в том, что я не могу найти контроллер логина, откуда я буду перенаправлять.

Роль – это атрибут объекта User который поступает из базы данных.

Solutions Collecting From Web of "перенаправить после входа в систему fos user bundle symfony"

Вы должны добавить LoginSuccessHandler, который реализует интерфейс AuthenticationSuccessHandler,

Затем вы можете настроить логику перенаправления в onAuthenticationSuccess() следующим образом:

 namespace XXX\YourBundler\Handler; use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\SecurityContext; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\Routing\Router; class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface { protected $router; protected $security; public function __construct(Router $router, SecurityContext $security) { $this->router = $router; $this->security = $security; } public function onAuthenticationSuccess(Request $request, TokenInterface $token) { if ($this->security->isGranted('ROLE_XXXX_1')) { $response = new RedirectResponse($this->router->generate('route_1')); } elseif ($this->security->isGranted('ROLE_XXXX_2')) { $response = new RedirectResponse($this->router->generate('route_2')); } // ... } } 

Вы также должны быть зарегистрированы как служба,

 parameters: security.authentication.success_handler.class: XXX\YourBundler\Handler\AuthenticationSuccessHandler services: security.authentication.customized_success_handler: class: %security.authentication.success_handler.class% public: false arguments: [@router, @security.context] 

Затем вы должны добавить следующую строку в конфигурацию безопасности брандмауэра,

  success_handler: security.authentication.customized_success_handler 

Вы можете перезаписать функцию renderLogin следующим образом:

 class SecurityController extends BaseController { /** * Renders the login template with the given parameters. Overwrite this function in * an extended controller to provide additional data for the login template. * * @param array $data * * @return \Symfony\Component\HttpFoundation\Response */ protected function renderLogin(array $data) { $securityContext = $this->get('security.context'); $router = $this->container->get('router'); // if ($this->get('security.context')->getToken()->getUser() instanceof \FOS\UserBundle\Propel\User) { // $url = $this->container->get('router')->generate('dashboard'); // return new RedirectResponse($url); // } if ($securityContext->isGranted('ROLE_ADMIN')) { return new RedirectResponse($router->generate('dashboard'), 307); } if ($securityContext->isGranted('ROLE_USER')) { return new RedirectResponse($router->generate('front_page_home'), 307); } $requestAttributes = $this->container->get('request')->attributes; if ($requestAttributes->get('_route') == 'admin_fos_user_security_login') { $template = sprintf('FOSUserBundle:Security:login.html.twig'); $data['admin'] = true; } else { $template = sprintf('FOSUserBundle:Security:login.html.twig'); $data['admin'] = false; } return $this->container->get('templating')->renderResponse($template, $data); } }