2015-03-25 93 views
2

有沒有一種有效的方法可以做到這一點?選項我看着:如果用戶未登錄,ZF2會重定向到每個頁面上的登錄頁面

  • 檢查會話容器在佈局
  • 檢查在模塊onBootstrap功能()會議容器
  • 每個控制器單獨處理會話容器/動作

理想情況下,我會檢查一次,有沒有正確的方法來做到這一點?

東西線沿線的...

$session = new Container('username'); 
    if($session->offsetExists('username')) { 
     //check im not already at my login route 
     //else redirect to login route 
    } 
} 

回答

4

您可以使用下面的代碼的每個控制器內部

public function onDispatch(\Zend\Mvc\MvcEvent $e) 
{ 
     if (! $this->authservice->hasIdentity()) { 
      return $this->redirect()->toRoute('login'); 
     } 

     return parent::onDispatch($e); 
} 

您還可以在模塊的onBootstrap功能(),您需要使用ZF2事件相匹配的路線查詢會話:

$auth = $sm->get('AuthService'); 
$em->attach(MvcEvent::EVENT_ROUTE, function ($e) use($list, $auth) 
{ 
    $match = $e->getRouteMatch(); 

    // No route match, this is a 404 
    if (! $match instanceof RouteMatch) { 
     return; 
    } 

    // Route is whitelisted 
    $name = $match->getMatchedRouteName(); 

    if (in_array($name, $list)) { 
     return; 
    } 

    // User is authenticated 
    if ($auth->hasIdentity()) { 
     return; 
    } 

    // Redirect to the user login page, as an example 
    $router = $e->getRouter(); 
    $url = $router->assemble(array(), array(
     'name' => 'login' 
    )); 

    $response = $e->getResponse(); 
    $response->getHeaders() 
     ->addHeaderLine('Location', $url); 
    $response->setStatusCode(302); 

    return $response; 
}, - 100); 

其中$列表將包含不需要處理的路線列表:

$list = array('login', 'login/authenticate'); 
0

正如ZFcAuth插件收銀臺下面的網址,我發現檢查&重定向一些代碼。

if (!$auth->hasIdentity() && $routeMatch->getMatchedRouteName() != 'user/login') { 
    $response = $e->getResponse(); 
    $response->getHeaders()->addHeaderLine(
     'Location', 
     $e->getRouter()->assemble(
      array(), 
      array('name' => 'zfcuser/login') 
     ) 
    ); 
    $response->setStatusCode(302); 
    return $response; 
} 

此代碼塊顯示驗證/重定向的方式。但是,由於ZF2僅提供組件,因此它們不是內置方式。您還可以使用其他插件,如提供所有功能的ZfcUser,ZfcAcl,ZfcRABC。

鏈接:https://github.com/ZF-Commons/ZfcUser/issues/187#issuecomment-12088823

相關問題