Is there an efficient way to do this? Options I've looked into:
Ideally I'd have this check once, is there any correct way to do this?
Something along the lines of...
$session = new Container('username');
if($session->offsetExists('username')) {
//check im not already at my login route
//else redirect to login route
}
}
You can use below code inside each controller
public function onDispatch(\Zend\Mvc\MvcEvent $e)
{
if (! $this->authservice->hasIdentity()) {
return $this->redirect()->toRoute('login');
}
return parent::onDispatch($e);
}
You can also check session on module's onBootstrap function(), you need to match the route using zf2 events:
$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);
where $list will contain the list of routes not to be processed:
$list = array('login', 'login/authenticate');
As checkout in ZFcAuth plugin in following urls, I found some code for check & redirect.
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;
}
This code chunk show the way to validate/redirect. However they are not in-build way as ZF2 only provide components. You can also use other plugins like ZfcUser, ZfcAcl, ZfcRABC which provide all functionality.
link : https://github.com/ZF-Commons/ZfcUser/issues/187#issuecomment-12088823 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.