2017-03-02 10 views
0

FOSUserBundle이 통합 된 Symfony 2.5 프로젝트가 있습니다. 나는 로그인 된 사용자가 자동으로 로그 아웃되어 로그인 페이지로 리다이렉트되도록 앱의 X 유휴 시간을 요구한다.Symfony 2.5 - 비활성 기간 후 자동 리디렉션

지금까지 나는 꽤 유사 여기 How to log users off automatically after a period of inactivity?

<?php 
namespace MyProject\UserBundle\EventListener; 

use Symfony\Component\Routing\RouterInterface; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Component\HttpFoundation\Session\SessionInterface; 
use Symfony\Component\Security\Core\SecurityContextInterface; 
use Symfony\Component\HttpKernel\HttpKernelInterface; 
use Symfony\Component\HttpKernel\Event\FilterControllerEvent; 


class UserInactivityListener 
{ 

    protected $session; 
    protected $securityContext; 
    protected $router; 
    protected $maxIdleTime; 

    public function __construct(
     SessionInterface $session, 
     SecurityContextInterface $securityContext, 
     RouterInterface $router, 
     $maxIdleTime = 0) 
    { 
     $this->session = $session; 
     $this->securityContext = $securityContext; 
     $this->router = $router; 
     $this->maxIdleTime = $maxIdleTime; 
    } 

    /** 
    * user will be logged out after 30 minutes of inactivity 
    * 
    * @param FilterControllerEvent $event 
    * @return type 
    */ 
    public function onKernelController(FilterControllerEvent $event) 
    { 
     if (HttpKernelInterface::MASTER_REQUEST != $event- >getRequestType()) { 
      return; 
     } 

     if ($this->maxIdleTime > 0) { 
      try { 
       $this->session->start(); 
       $lapse = time() - $this->session->getMetadataBag()->getLastUsed(); 
       $isFullyAuthenticated = $this->securityContext->isGranted('IS_AUTHENTICATED_FULLY'); 

       if (($lapse > $this->maxIdleTime) && $isFullyAuthenticated == true) { 
        $this->securityContext->setToken(null); 
        $url = $this->router->generate('fos_user_security_login'); 

        $event->setController(function() use ($url) { 
         return new RedirectResponse($url); 

        }); 
       } 
      } catch (\Exception $ex) { 
       return; 
      } 
     } 
    } 
} 

에 제안, 솔루션을 구현했습니다 문제입니다이 이벤트가 트리거되고 사용자가하려고 할 때 리디렉션은 일어날 것입니다 유휴 시간이 지난 후에 앱에 아무것도로드하지 마세요. 내가 원하는 것은 사용자가 어떤 상호 작용없이 앱을 자동으로 가입 페이지로 리디렉션하는 것입니다.

새로 고침 메타 태그 How to auto redirect a user in Symfony after a session time out?을 사용하라는 제안이 나왔지만 지금 새로 고침 이벤트를 발생시키는 또 다른 좋은 방법이 있는지 궁금해하고 있었습니까?

답변

1

정기적인 페이지를 새로 고침해도 사용자를 괴롭히지 않으면 메타 새로 고침이 좋습니다. 그것은 아마도 가장 신뢰할 수 있습니다. 당신은 또한 같은 자바 스크립트/jQuery를 스 니펫 (snippet)을 구현할 수 있도록 핑 반복해서 서버가이 경우에

setTimeout(checkIdleTime, 2000);

모든 2000 밀리 초 또는 2 초마다.

function checkIdleTime() { 
    $.get('/idle', function()) { 
     // If HTTP_OK response, do nothing, otherwise handle error 
    } 
} 

는 "게으름"을 확인하는 작업에 /idle URL을 매핑합니다. 행동은 물론 그 자체에 대한 요청을 무시해야합니다. 유휴 상태가 아니라면 성공을 리턴하고, 그렇지 않으면 사용자를 강제로 로그 아웃하고 어떤 종류의 오류를 리턴하십시오. jQuery 응답에서 오류를 처리하십시오. 아마도 간단한 리다이렉트가 가능할 것입니다 : window.location.href = '/login';

URL을 하드 코딩 할 필요가 없도록 symfony 경로를 jQuery에서 우아하게 사용하려면 FOSJsRoutingBundle을 확인하십시오.

+1

감사합니다. @nurikable. 솔루션이 작동합니다. –