Reputation: 93
I have a Dashboard controller with Route setup as /Dashboard[/:action][/:id]
I do not want to check $auth->hasIdentity()
in index , edit, add, delete Actions of my
Dashboard controller, I want a detect that from the top level. After reading many blogs
and documentation I found getControllerConfig()
is the right place for any initial
setup a controller may need.
Unfortunately I can not do redirect()
from within getControllerConfig()
function
I have already checked ZfcUser
but that is too much for my small scenario.
Can some one throw light on this and thanks.
Upvotes: 2
Views: 406
Reputation: 93
This is the best solutions from the zf2 forums to handle the request from the very top level and do the redirect before even initializing your controller logic.
Secondly through this technique you do not require to check $auth->hasIndentity() inside your controller anyAction() which gives you piece of mind working on some special route where you want to make certain the user must be logged in. i.e. /Dashboard
That works for me i hope it helps all.
public function onBootstrap(MvcEvent $e)
{
$serviceManager = $e->getApplication()->getServiceManager();
$path = $e->getRequest()->getUri()->getPath();
if(strripos($path, 'Dashboard') !== false) {
$authService = $serviceManager->get('MyApp\Authentication\Service');
if (!$authService->hasIdentity()) {
$e->getResponse()
->setStatusCode(302)
->getHeaders()->addHeaderLine('location', '/path/to/login');
return $e->getResponse();
}
}
}
Upvotes: 1
Reputation: 1576
If you are willing to use the 2.1 branch there is a controller plugin that will do the work for you. Inside a controller just do:
$identity = $this->identity()
Upvotes: 0