检查用户是否已登录

时间:2012-12-12 08:56:24

标签: php zend-framework2

我有一个Dashboard控制器,路径设置为/Dashboard[/:action][/:id]

我不想在索引中检查$auth->hasIdentity(),编辑,添加,删除我的操作 仪表板控制器,我想从顶层检测到。看了很多博客 我发现getControllerConfig()的文档是任何首字母的正确位置 设置控制器可能需要。

很遗憾,我无法在redirect()函数内执行getControllerConfig() 我已经检查了ZfcUser,但这对我的小情况来说太过分了。

有人可以对此表示赞赏并表示感谢。

2 个答案:

答案 0 :(得分:1)

这是来自zf2论坛的最佳解决方案,可以处理来自最高级别的请求,并在初始化控制器逻辑之前进行重定向。

其次通过这种技术,你不需要在里面检查$ auth-> hasIndentity() 你的控制器anyAction()让你在一些特殊的事情上工作 您要确定用户必须登录的路线。即/ Dashboard

这对我有用,我希望它能帮助所有人。

public function onBootstrap(MvcEvent $e)
{
    $serviceManager = $e->getApplication()->getServiceManager();
    $path = $e->getRequest()->getUri()->getPath();

    if(strripos($path, 'Dashboard') !== false) {
        $authService = $serviceManager->get('MyApp\Authentication\Service');
        if (!$authService->hasIdentity()) {
            $e->getResponse()
                ->setStatusCode(302)
                ->getHeaders()->addHeaderLine('location', '/path/to/login');
            return $e->getResponse();
        }
    }
}

答案 1 :(得分:0)

如果您愿意使用2.1分支,那么有一个控制器插件可以为您完成工作。在控制器内部只需:

$identity = $this->identity()