2014-03-03 92 views
0

我是Yii的新手。我在验证不同位置时遇到问题。我有一个需要管理员和用户身份验证的应用程序。虽然管理员使用谷歌身份验证,用户使用事实上的用户名/密码组合。Yii认证

以下是我的代码。我错过了什么。基本上,我想当用户输入/管理她/她应该得到管理登录 - 我已经排序,当他/她键入/帐户/登录用户应该得到正规的用户名/密码登录。

public function beforeAction($action) 
{ 


    $host = $_SERVER ['REQUEST_URI']; 
    if (!isset(Yii::app()->session['user_type'])) 
    { 
     if ($host != '/account/login' && $host != '/admin') 
     { 
      //header('Location: /access'); 
      header('Location: /account/login'); 
     } 
     /*else if ($host != '/admin') 
     { 
      header('Location: /admin'); 
     }*/ 

    } 
    else 
    { 
     $access = $this->access(); 
     $currentCont = ucfirst($this->getUniqueId()); 
     if (!empty($access)) 
     { 
      if (!in_array($currentCont, $access)) 
      { 
       Yii::app()->session->clear(); 
       Yii::app()->session->destroy(); 
       header('Location: /account/login'); 
      } 
     } 
     return parent::beforeAction($action); 
    } 


    return parent::beforeAction($action); 
} 
+0

那么是什么问题? –

+0

嗨Mihai,打字/管理应该留在那里不要重定向到/帐户/登录这是一般用户登录和/管理员有登录管理..谢谢。 – Cyberomin

+0

这可能对你有所帮助:https://www.cloudways.com/blog/user-authentication-yii2/ –

回答

0

我相信.htaccess可能会将您的请求从1转换为另一个。

即使您的网址可能是/ admin,它也可能会翻译成其他的.htaccess文件,而这实际上是您的URI。

如果不是这样,我很累,现在:(

+0

只需简单地调试一下$ host的值是什么,那会让你走上正确的轨道。 –

+0

谢谢Mihai,我很感激。 – Cyberomin

+0

我想我明白了:)。标题('Location:/ account/login');应该跟着出口。 YOu在不停止应用程序的情况下进行重定向。看到这里http://au2.php.net/manual/en/function.header.php –

0

我发现这个问题不那么优雅的解决方案:

if ($currentCont != 'admin' && $host != 'login') 
{ 
    echo '<meta http-equiv="refresh" content="0; url='.Yii::app()->createUrl('/account/login').'">'; 

} 
else 
{ 
    echo '<meta http-equiv="refresh" content="0;url='.Yii::app()->createUrl('/admin').'">'; 

} 
0

这令我奇怪的,你会用beforeAction做这个如果我了解你的需要,我会写两个动作,一个是网站/登录,会处理普通用户,一个是网站/管理员,并且会处理你的管理员用户。对于您的普通用户:

public function actionLogin() 
{ 
    if (!\Yii::$app->user->isGuest) { 
     return $this->goHome(); 
    } 

    $model = new LoginForm(); 
    if ($model->load(Yii::$app->request->post()) && $model->login()) { 
     return $this->goBack(); 
    } else { 
     return $this->render('login', [ 
      'model' => $model, 
     ]); 
    } 
} 

然后我会为管理案例做第二个操作。

public function actionAdmin() 
{ 
    if (!\Yii::$app->user->isGuest) { 
     return $this->goHome(); 
    } 

    <do google auth stuff> 
    if (<authenticated by google>) { 
     return $this->goBack(); 
    } else { 
     <deal with authentication failure> 
    } 
}