繁体   English   中英

php yii无法使用useridentity组件登录

[英]php yii unable to login using useridentity component

这是我的身份验证控制器

class AuthController  extends Controller
{

    public function actionLogin()
    {
        $model = new LoginForm;

        $post = Yii::app()->request->getPost('LoginForm');
        // If form is submitted
        if($post) {
            $identity = new UserIdentity($post['username'], $post['password']);

            if($identity->authenticate()) {  // loop enters but could not get id
                echo Yii::app()->user->id;
                echo Yii::app()->user->getId();
            } else {
                echo 'failed';
            }
            //exit;
        }
        $this->render('login', array('model' => $model));   
    }
}

这是我的UserIdentity.php

class UserIdentity extends CUserIdentity
{


    private $_id;

    public function authenticate()
    {   
        $user = SchLogins::model()->findByAttributes(array('username' => $this->username));
        if(is_null($user)) {
            $this->errorCode=self::ERROR_USERNAME_INVALID;
        } else if($user->password != $this->password) {
            $this->errorCode=self::ERROR_PASSWORD_INVALID;
        } else {

            $this->_id = $user->id;

            $this->errorCode=self::ERROR_NONE;
        }

        return !$this->errorCode;
    }


    public function getId()
    {
        return $this->_id;
    }
}

在上面的代码中,我在获取用户ID(即Yii::app()->user->getId();时遇到问题Yii::app()->user->getId(); 这什么都不返回,我在上面的代码中做错了什么

您正在创建一个LoginForm实例$model但从未使用它实际登录。 如果您使用的是标准LoginForm模型,那么它将与UserIdentity类进行交互。 应该是这样的:

if($post) {
    $model->attributes = $_POST['LoginForm'];

    if ($model->validate() && $model->login()) {  // loop enters but could not get id
        echo Yii::app()->user->id;
        echo Yii::app()->user->getId();
    } else {
        echo 'failed';
    }
    //exit;
}

如果您查看LoginForm的login()函数,将会看到它调用Yii::app()->user->login($this->_identity,$duration); 这实际上是设置了跳过您方法的Yii::app()->user内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM