How to force a login using YII?

你离开我真会死。 提交于 2019-12-25 07:06:23

问题


I have a user that needs to authenticate his account via an OTP. TO authenticate, he fills in his OTP and it verifies the cellphone number. Once authenticated, I want to force him to log in. I.e. So he doesn't still have to manually login. So, for this form, I basically have:

if($model->validate())
{
   // Force Login
   $this->redirect(array('/site/index'));    
}

Using only one of his credentials (namely his cellphone number), I need to force him to login. How would I do that?


回答1:


The procedure is explained in the documentation for CWebUser:

  1. The user provides information needed for authentication.
  2. An identity instance is created with the user-provided information.
  3. Call IUserIdentity::authenticate to check if the identity is valid.
  4. If valid, call CWebUser::login to login the user, and Redirect the user browser to returnUrl.

You should already have an identity class that implements IUserIdentity. Usually this is a class deriving from CUserIdentity, which takes a username and a password on construction. There is a great degree of freedom here: you can decide not to derive from CUserIdentity and use your own custom identity class that authenticates any way you wish, or you can derive from CUserIdentity and override the authenticate method to authenticate with the OTP.

The procedure would then be exactly as above:

$identity = new MyIdentity(...); // you decide what params it takes
if ($identity->authenticate()) {
    $user = Yii::app()->user;
    $user->login($identity);
    $this->redirect($user->returnUrl);
}


来源:https://stackoverflow.com/questions/14769234/how-to-force-a-login-using-yii

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