Zend框架:如何在登录后重定向到原始URL?

3
我正在尝试实现一个登录系统,该系统足够智能,能够将用户重定向回他们在登录之前所在的页面,无论是自愿还是强制跳转到登录页面。
我知道这似乎与这个这个类似的问题,但它们没有解决我的两种情况。
这里有两种情况:
  1. User specifically decides to go to login page:

    <a href="<?php echo $this->url(array(
        'controller'=>'auth',
        'action'=>'login'), 'default', true); ?>">Log In</a>
    
  2. User is redirected because they tried to access protected content:

    if (!Zend_Auth::getInstance()->hasIdentity()) {
        $this->_helper->redirector('login', 'auth');
    }
    
如何在不在地址栏中显示“重定向到”URL的情况下实现此解决方案?
1个回答

3

将目标URL保存在会话中。我猜你有某种访问预调度插件。可以在那里完成。然后,在登录表单处理程序中,检查会话中的目标URL,并在成功验证后重定向到它。

来自我的项目的示例代码:

class Your_Application_Plugin_Access extends Zend_Controller_Plugin_Abstract {
    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        foreach (self::current_roles() as $role) {
            if (
                Zend_Registry::get('bootstrap')->siteacl->is_allowed(
                    $role,
                    new Site_Action_UriPath($request->getPathInfo())
                )
            ) return; // Allowed
        }

        $this->not_allowed($request);
    }

    private function not_allowed(Zend_Controller_Request_Abstract $request) {
        $destination_url = $request->getPathInfo();

        // If the user is authenticted, but the page is denied for his role, show 403
        // else,
        // save $destination_url to session
        // redirect to login page, with $destination_url saved:
        $request
            ->setPathInfo('/login')
            ->setModuleName('default')
            ->setControllerName('login')
            ->setActionName('index')
            ->setDispatched(false);
    }

    ...

}

在这里,current_roles() 始终包含“guest”,即未经身份验证的用户,对于该用户,Zend_Auth::hasIdentity() 的返回值为 false

不,你需要添加控制器插件,就像我刚刚添加的示例代码一样。此外,请在您的application.ini文件中注册此插件:resources.frontController.plugins.access = "Your_Application_Plugin_Access" - Ivan Krechetov
你介意稍微整理一下插件代码吗?我看到了很多似乎只适用于你的项目,但对我的项目来说是不必要的。此外,我没有看到你在会话中设置原始URL的位置。我是没看到还是这部分被省略了? - Andrew
我把保存到 session 的代码省略了,是的。你可以在 (// save $destination_url to session) 进行保存。你可以使用 Zend_Session 或直接使用 $_SESSION 超全局变量。Andrew,在你的应用程序中具体看起来就取决于你的操作方式。我相信,此时已经足够简单,可以自行解决细节问题。 - Ivan Krechetov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接