2014-01-14 24 views
1

我想重定向我的用戶激活頁面(user.activate),如果用戶沒有激活。我主要希望在登錄時做到這一點,但是即使用戶已登錄,也可以檢查它。

我試着擴展Symfony\Component\Security\Core\User\UserChecker並且返回一個RedirectResponse,如果它捕獲一個DisabledException但它不處理一個響應。

我試着在AuthenticationEvents::AUTHENTICATION_FAILUREAuthenticationEvents::AUTHENTICATION_SUCCESS事件中檢查if ($user->isDisabled()),但那也沒有處理響應。

回答

0

而不是做與安全有關,我會做另一種方式,與請求偵聽器。

使用onCoreRequest函數創建一個新類,如果事件調度程序爲kernel.request事件註冊它。它將獲得一個Symfony\Component\HttpKernel\Event\GetResponseEvent實例作爲單個參數。

在那裏你可以檢查是否有用戶登錄,如果它被禁用,然後使用事件的setResponse事件做重定向。

+0

,我意識到,有它做它所有的請求的是不是最好的選擇。 –

1

我加入這個類

class LoginSuccessHandler implements AuthenticationSuccessHandlerInterface 
{ 
    protected $app; 

    public function __construct(Application $app) 
    { 
     $this->app = $app; 
    } 

    public function onAuthenticationSuccess(Request $request, TokenInterface $token) 
    { 
     $user = $token->getUser(); 

     if (!$user->isEnabled()) 
     { 
      // Logout 
      $this->app['user.manager']->logout(); 

      $response = $this->app->redirect($this->app['url_generator']->generate('user.activate', array('id' => $user->id))); 
     } 
     else 
     { 
      // redirect the user to where they were before the login process begun. 
      $referer_url = $request->headers->get('referer'); 

      $response = new RedirectResponse($referer_url); 
     } 

     return $response; 
    } 
} 

然後添加了這個:

$app['security.authentication.success_handler.secured_area'] = $app->share(function ($app) { 
    return new \Kidtrips\Lib\LoginSuccessHandler($app); 
});