Question

I'm new to Yii. I have an issue with authenticating for different locations. I have an app that needs admin and user authentication. While admin uses google auth, users use the de facto username/password combo.

Below is my code. What am I missing. Basically, I want when a user types /admin her/she should get the admin login - which I have sorted and when he/she types /account/login the user should get the regular username/password login.

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);
}

No correct solution

OTHER TIPS

I believe that .htaccess might be translating your requests from 1 to another.

Even if your url might be /admin it might be translating to something else with .htaccess and that is actually your URI.

Either that or I am very tired now :(.

I found a not so elegant solution for this issue:

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').'">'; 

}

It strikes me as strange you would be doing this with a beforeAction. If I understand your need, I would write two actions. One would be site/login and would handle the regular users and one would be site/admin and would handle your admin users.

I'd have the regular login for your normal users:

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,
        ]);
    }
}

and then I'd have a second action for the admin case.

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>
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top