【问题标题】:How to do preDispatch forwarding in Zend Framework?如何在 Zend Framework 中进行 preDispatch 转发?
【发布时间】:2010-02-19 23:47:45
【问题描述】:

在检查用户是否在每个控制器中都登录后,我想在preDispatch 中使用_forward()

场景很简单:如果用户未登录,则应将其转发到同一控制器或另一个控制器中的loginAction

这将导致无限循环,因为调度过程重新开始,再次调用preDispatch,转发将重新开始一切。

我能想出的唯一解决方案是检查loginAction 是否已在请求中设置。

所以我的问题是,老练的开发人员将如何处理这个问题?

更新 就在按下发送按钮后,神圣意识的幽灵出现了;) 另一个想法是建立一个LoginController 来处理登录请求。还是有更好的方法?

【问题讨论】:

    标签: php zend-framework controller dispatcher forwarding


    【解决方案1】:

    我结合使用 Zend_Controller_Plugin 和 AuthController 来保护我的站点。它支持密码重置、强制密码更改和自动帐户锁定,因此复杂度适中。

    请注意,我使用的是 Doctrine,因此显然不能将其剪切并粘贴到您的应用程序中,但它应该只需进行最少的更改即可运行。我删除了一些特定于我的应用程序的方法,但所有常规身份验证 foo 都在那里。

    插件

    <?php
    class Hobo_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
    {
        public function preDispatch(Zend_Controller_Request_Abstract $request)
        {
            $auth = Zend_Auth::getInstance();
            if ($auth->hasIdentity()) {
                if ('logout' != $request->getActionName()) {
                    if (! $request->getParam('force_password_change')
                        && $this->_checkPasswordExpiry($auth->getIdentity()->username)
                    ) {
                        $request->setParam('force_password_change', true);
                        $request->setModuleName('default')
                            ->setControllerName('auth')
                            ->setActionName('change-password');
                    }
                }
            } else {
                // Defer more complex authentication logic to AuthController
                if ('auth' != $this->getRequest()->getControllerName()) {
                    $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
                    $redirector->gotoSimple('restricted', 'auth');
                }
            }
        }
    
        protected function _checkPasswordExpiry($username)
        {
            // Look up user and return true if password is expired
        }
    }
    

    AuthController

    <?php
    
    class AuthController extends Zend_Controller_Action
    {
        public function init()
        {
            $this->_auth = Zend_Auth::getInstance();
    
            $this->_errorMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
            $this->_errorMessenger->setActionController($this)->init();
            $this->_errorMessenger->setNamespace('error');
    
            $this->_noticeMessenger = new Zend_Controller_Action_Helper_FlashMessenger();
            $this->_noticeMessenger->setActionController($this)->init();
            $this->_noticeMessenger->setNamespace('notice');
    
            $this->view->errors = $this->_errorMessenger->getMessages();
            $this->view->notices = $this->_noticeMessenger->getMessages();
        }
    
        public function preDispatch()
        {
            if (! $this->_auth->hasIdentity()) {
                if (! in_array($this->_request->getActionName(), array(
                        'logout', 'identify', 'forgot-password', 'reset-password', 'restricted'))
                    ) {
                    $this->_redirect('/auth/restricted');
                }
            }
        }
    
        public function restrictedAction()
        {
            // Shows access restricted page
        }
    
        public function logoutAction()
        {
            $this->_auth->clearIdentity();
            Zend_Session::destroy();
            $this->_redirect('/');
        }
    
        public function identifyAction()
        {
            if ($this->_request->isPost()) {
                $username = $this->_getParam('username');
                $password = $this->_getParam('password');
    
                if (empty($username) || empty($password)) {
                    $this->_flashError('Username or password cannot be blank.');
                } else {
                    $user = new dUser();
                    $result = $user->login($username, $password);
    
                    if ($result->isValid()) {
                        $user->fromArray((array) $this->_auth->getIdentity());
    
                        if ($this->_getParam('changepass') || $user->is_password_expired) {
                            $this->_redirect('auth/change-password');
                            return;
                        }
                        $this->_doRedirect($user);
                        return;
                    } else {
                        $this->_doFailure($result->getIdentity());
                    }
                }
            }
            $this->_redirect('/');
        }
    
        public function changePasswordAction()
        {
            if ($this->_request->isPost()) {
                $username = $this->_auth->getIdentity()->username;
                $formData = $this->_request->getParams();
    
                if (empty($formData['password'])
                    || empty($formData['new_password'])
                    || empty($formData['confirm_password'])
                ) {
                    $this->_flashError('Password cannot be blank.');
                    $this->_redirect('auth/change-password');
                } elseif ($formData['new_password'] !== $formData['confirm_password']) {
                    $this->_flashError('Password and confirmation do not match.');
                    $this->_redirect('auth/change-password');
                } else {
                    $user = new dUser();
                    $result = $user->login($username, $formData['password']);
    
                    if ($result->isValid()) {
    
                        $user->updatePassword($username, $formData['new_password']);
                        $this->_flashNotice('Password updated successfully!');
                        $this->_redirect('/');
                    } else {
                        $this->_flashError('Invalid username or password!');
                        $this->_redirect('auth/change-password');
                    }
                }
    
            }
    
            if ($this->_getParam('force_password_change')) {
                $this->view->notice = 'Your password has expired. You must change your password to continue.';
            }
        }
    
        public function forgotPasswordAction()
        {
            if ($this->_request->isPost()) {
                // Pseudo-random uppercase 6 digit hex value
                $resetCode = strtoupper(substr(sha1(uniqid(rand(),true)),0,6));
    
                Doctrine_Query::create()
                    ->update('dUser u')
                    ->set('u.reset_code', '?', array($resetCode))
                    ->where('u.username = ?', array($this->_getParam('username')))
                    ->execute();
    
                $this->_doMail($this->_getParam('username'), $resetCode);
    
                $this->_flashNotice("Password reset request received.");
                $this->_flashNotice("An email with further instructions, including your <em>Reset Code</em>, has been sent to {$this->_getParam('username')}.");
                $this->_redirect("auth/reset-password/username/{$this->_getParam('username')}");
            }
        }
    
        public function resetPasswordAction()
        {
            $this->view->username = $this->_getParam('username');
            $this->view->reset_code = $this->_getParam('reset_code');
    
            if ($this->_request->isPost()) {
                $formData = $this->_request->getParams();
                if (empty($formData['username']) || empty($formData['reset_code'])) {
                    $this->_flashError('Username or reset code cannot be blank.');
                    $this->_redirect('auth/reset-password');
                } elseif ($formData['new_password'] !== $formData['confirm_password']) {
                    $this->_flashError('Password and confirmation do not match.');
                    $this->_redirect('auth/reset-password');
                } else {
                    $user = new dUser();
                    $result = $user->loginWithResetCode($formData['username'], $formData['reset_code']);
    
                    if ($result->isValid()) {
                        $user->updatePassword($result->getIdentity(), $formData['new_password']);
    
                        $user->fromArray((array) $this->_auth->getIdentity());
    
                        $this->_flashNotice('Password updated successfully!');
                        $this->_doRedirect($user);
                    } else {
                        $this->_doFailure($result->getIdentity());
                        $this->_redirect('auth/reset-password');
                    }
                }
            }
        }
    
        protected function _doRedirect($user)
        {
            $this->_helper->Redirector->gotoUserDefault($user);
        }
    
        protected function _flashError($message)
        {
            $this->_errorMessenger->addMessage($message);
        }
    
        protected function _flashNotice($message)
        {
            $this->_noticeMessenger->addMessage($message);
        }
    
        protected function _doFailure($username)
        {
            $user = Doctrine_Query::create()
                ->from('dUser u')
                ->select('u.is_locked')
                ->where('u.username = ?', array($username))
                ->fetchOne();
    
            if ($user->is_locked) {
                $this->_flashError('This account has been locked.');
            } else {
                $this->_flashError('Invalid username or password');
            }
        }
    }
    

    【讨论】:

    • 感谢您的回答!很好的例子,如何快速合理地进行设置。
    • 干得好,$this->_redirect();没用只对你有用。
    【解决方案2】:

    或者,您可以使用以下内容:

      $request->setParam('skippredispatch',true);
      $this->_forward('index');
    

    在你的控制器中,然后[之前]这个

    // If overwriting jump the pre-dispatchy bits
    if ($request->getParam('skippredispatch')){
      $request->setParam('skippredispatch',null);
      return;
    }
    

    有效地跳过似乎工作正常的预调度循环。

    【讨论】:

      【解决方案3】:

      这个过程可以在任何action中,但是为什么不能loginAction,或者LoginController中的indexAction呢?

      1. 检查登录身份:找到了吗?重定向到索引
      2. 检查帖子参数:找到了吗?验证、设置身份或设置错误消息
      3. 打印表格

      编辑:可能已经太累而没有意识到真正的问题。我会从每个受登录保护的控制器中的受保护/私有成员之类的东西开始,例如protected $authNeeded = true;,然后在Zend_Controller_Action::init() 中检查它。这可能会导致代码重复,因此另一种选择是在所有受登录保护的控制器扩展的AuthNeededController 中执行此代码。

      【讨论】:

      • 感谢您的回答。我将使用 hobodave 提出的这种设计。他的回答更详细,所以他得到了打勾。
      猜你喜欢
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-24
      • 2012-03-08
      • 2011-07-10
      • 2013-03-08
      相关资源
      最近更新 更多