我现在正在使用Zend Framework,我使用Zend_Auth编写了身份验证代码。我试图找到一种方法来确保用户在他们可以查看任何内容之前登录,但我不想在每个控制器的基础上执行此操作。
我在想一个插件,但我所拥有的所有书籍在这方面都非常垃圾。
答案 0 :(得分:2)
Zend_Auth::getInstance()->hasIdentity()
您可以使用它来确定用户是否已登录,然后使用重定向器重定向到登录页面。
但是,更简单的方法是使用Redirector Zend Controller Action Helper。
答案 1 :(得分:1)
插件是个好主意。 我在这里回答了类似的问题:
How do i centralize code from my init functions in all controllers ?
另请查看文档页面Zend Controller Plugins
答案 2 :(得分:1)
查看Zend___Acl,可用于定义用户是否可以访问某些资源。资源几乎可以是任何东西,但在此上下文中,您可以使用ACL将控制器和操作定义为资源。然后为每个登录用户分配许多角色(我们将它们存储在数据库中)。在插件中,在路由完成后检查Controller和Action的请求。通过Zend_Auth收集用户的角色,并根据ACL检查它们。如果ACL表示用户有权访问资源,则不执行任何操作,否则您可以转发/重定向到错误控制器并打印错误。
// 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's 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;
}
}
答案 3 :(得分:1)
如何设置扩展Zend_Controller_Action的全局控制器,然后让控制器从全局控制器扩展。然后你的全局控制器在init()或preDispatch中放置Zend_Auth :: getInstance() - > hasIdentity()吗?
答案 4 :(得分:0)
我最近正在考虑相同的主题(ZF新手),并考虑在引导程序中进行身份验证检查(可能带有“绕过的”控制器/操作列表)。