How do I force the user to log in to view any page?
I am currently playing with Zend Framework and I have an authentication code using Zend_Auth. I'm trying to find a way to make sure the user is logged in before they can view anything, but I don't want to do this on a per controller basis.
I think it's a plugin, but all the books I have on it are pretty rubbish in that regard.
a source to share
A plugin is a good idea. I answered a similar question:
How do I centralize the code from my init functions across all controllers?
Also check the documentation page for Zend Controller Plugins
a source to share
Zend_Auth::getInstance()->hasIdentity()
You can use this to determine if the user is logged in and then use a redirector to redirect to the login page if not.
However, it is easiest to use the Redirector Zend Controller Action Helper .
a source to share
Have a look at Zend ___ Acl which can be used to determine if a user has access to certain resources. A resource can be almost anything, but in this context, you can use an ACL to define your controllers and actions as resources. Each registered user is assigned several roles (we store them in the database). In the plugin, you check the controller request and action after routing is complete. Collect user roles via Zend_Auth and check them against ACLs. If the ACL says the user has permission to access the resource, do nothing, otherwise you can redirect / redirect to your error controller and print the error.
// Pseudo-code. You need to define the ACL and roles somehow.
class AclPlugin extends Zend_Controller_Plugin {
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$controller = $request->getControllerName();
$action = $request->getActionName();
$roles = Zend_Auth::getInstance()->getRoles();
$acl = new MyAcl();
if($acl->hasAccess($roles, $controller, $action)) { return; }
// None of the user roles gave her access to the requested
// controller/action, so re-write the request to the error controller
$request->setControllerName('error')
->setActionName('authorizationFailed')
->setParam('resource', array('controller' => $controller
'action' => $action));
}
}
class MyAcl extends Zend_Acl {
public function hasAccess($roles, $controller, $action) {
foreach($roles as $role) {
if($acl->isAllowed($role, $controller, $action)) {
return true; // Simplified. Here we say if one of the user roles can
// access a resource, that is good enough.
// Might want to do something a bit more complicated.
}
}
return false;
}
}
a source to share