从Symfony2中的身份验证失败处理程序访问doctrine

时间:2012-02-28 23:51:40

标签: authentication symfony doctrine-orm

我正在尝试从自定义身份验证处理程序在数据库中编写一些登录失败信息。 我的问题是访问数据库,因为我不知道Doctrine对象可能存储在哪里

这是我现在的代码:

namespace MyApp\FrontBundle\Controller;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request as Request;
use Symfony\Component\HttpFoundation\RedirectResponse as RedirectResponse;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Security\Http\Authentication as Auth;
use Symfony\Component\Security\Core\Exception\AuthenticationException as AuthException;

class SecurityHandler implements Auth\AuthenticationFailureHandlerInterface
{
    public function onAuthenticationFailure(Request $request, AuthException $token)
    {
        try
        {
            $lastLoginFailure = new DateTime();

            // get database object here
        }
        catch(\Exception $ex)
        {
        }
    }
}

有什么想法吗?

3 个答案:

答案 0 :(得分:4)

将SecurityHandler转换为服务,然后将doctrine实体管理器注入其中。

http://symfony.com/doc/current/book/service_container.html

答案 1 :(得分:3)

  1. 启动命令php app / console container:debug。
  2. 复制doctrine.orm.entity_manager并粘贴到您的hadler构造函数参数,例如
    [....,@ doctrine.orm.entity_manager]。
  3. 在hadler中使用Doctrine\ORM\EntityManager;

答案 2 :(得分:-1)

如果您想使用服务,我认为您应该使用ContainerAware扩展您的类“SecurityHandler”,因为您的安全处理程序不是控制器。

class SecurityHandler extend ContainerAware implements Auth\AuthenticationFailureHandlerInterface{
    public function onAuthenticationFailure(Request $request, AuthException $token)
    {
        try
        {
        $lastLoginFailure = new DateTime();

        // get database object here
        $doctrine = $this->container->get('doctrine');
        $repository = $doctrine->getRepository('*NAME OF REPO*');
        }
        catch(\Exception $ex)
        {
        }
    }
}
相关问题