1

我正在为 Symfony 使用 FOSUser Bundle...我的问题是;我有两组不同的用户....例如;教师和学生,在系统注册时设置。(使用 FOSUser Bundle 的用户表)

成功登录后,我希望用户转到正确的登录页面。因此,如果用户是老师,我希望用户转到 /teacher,让学生转到 /student。

解决这个问题的最佳方法是什么?

谢谢

4

1 回答 1

4

您需要一个事件侦听器来侦听登录事件。然后,您可以根据他们的角色将客户端路由到不同的页面。

服务.yml:

services:
    login_listener:
        class: Acme\UserBundle\Listener\LoginListener
        arguments: [@security.context, @doctrine]
        tags:
            - { name: kernel.event_listener, event: security.interactive_login }

登录监听器:

<?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();

        // ...
    }
}

来自:http ://www.metod.si/login-event-listener-in-symfony2/

于 2013-02-05T18:46:50.843 回答