Zend Framework 2, Module Redirect

我的未来我决定 提交于 2019-12-11 02:38:18

问题


I have a function in my module.php with the following function which is called before everything else starts to load, it verifies that the user is logged on but I need it to redirect to the login page if the user is not logged in, I could just use "header" but I want to learn the "Zend" way of doing things.

public function preDispatch($e)
{
    if (!isset($_SESSION)) session_start();

    $sm = $e->getApplication()->getServiceManager();
    $adapters = $sm->get('dbAdapters');
    if (!isset($_SESSION['auth'])) $_SESSION['auth'] = new MyAuth($adapters[1]);

    if ($_SESSION['auth']->IsValid())
    {
        echo 'Valid<br />';
    }
    else
    {
        $e->getControllerClass()->redirect()->toRoute('login-success');
        echo '!Valid<br />';
        //REDIRECT TO LOGIN PAGE HERE!!!!!
    }
}

回答1:


This is specifically what you were asking about:

        //REDIRECT TO LOGIN PAGE HERE!!!!!

        /**
         * grab Controller instance from event and use the native redirect plugin
         */
        $controller = $e->getTarget();
        $controller->plugin('redirect')->toUrl('/logout?' . $query);

        /**
         * optionally stop event propagation and return FALSE
         */
        $e->stopPropagation();
        return FALSE;

That being said, you might want to reconsider using the raw session. Example (assumes you've configured a custom authAdapter):

public function checkSession($e)
{
    $controller = $e->getTarget(); // grab Controller instance from event

    $app          = $e->getApplication();
    $locator      = $app->getServiceManager();
    if ($controller instanceof LogoutController) return;
    $authService = $locator->get('ds_auth_service');
    $authAdapter = $locator->get('ds_auth_adapter');

    /*
     * try to authenticate
     */
    if (!$authService->hasIdentity()){
        $result = $authService->authenticate($authAdapter);
        if ($authService->hasIdentity()) {
            $this->getEventManager()->trigger('authenticate', $this, array('result' => $result));
        }
    }

    /*
     * If we are not in an exempt controller and no valid identity, redirect
     */
    $isExempt = $controller instanceof \Application\Controller\LogoutController;
    if (!$isExempt && !$authService->hasIdentity()) {
        $query = http_build_query($result->getMessages());
        $controller->plugin('redirect')->toUrl('/logout?' . $query);
        $e->stopPropagation();
        return FALSE;
    }

    // User is logged in
    return TRUE;

}


来源:https://stackoverflow.com/questions/13317037/zend-framework-2-module-redirect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!