授权不起作用yii2

时间:2016-11-14 19:33:09

标签: php yii2

我正在尝试: 当用户授权进入主页时 未经授权的用户进入登录页面 但现在当我把(正确的)用户电子邮件和密码总是刷新登录页面并且没有登录到系统时。

用户(ActiveRecord的)

class User extends ActiveRecord implements IdentityInterface
{
    public function setPassword($user_password)
    {
        $this->password = sha1($user_password);
    }
    public function validatePassword($user_password)
    {
        return $this->user_password === sha1($user_password);
    }
    public static function findIdentity($id)
    {
        return self::findOne($id);
    }
    public static function findIdentityByAccessToken($token, $type = null)
    {

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

    }
    public function validateAuthKey($authKey)
    {

    }
}

登录模式:

class Login extends Model
{
    public $user_email;
    public $user_password;
    public function rules()
    {
        return [
            [['user_email', 'user_password'],'required'],
            ['user_email','email'],
            ['user_password','validatePassword']
        ];
    }
    public function validatePassword($attribute,$params)
    {
        if(!$this->hasErrors())
        {
            $user = $this->getUser();
            if(!$user || !$user->validatePassword($this->user_password))
            {
                $this->addError($attribute, 'Пароль или пользователь введенны не верно');
            }
        }
    }
    public function getUser()
    {
        return User::findOne(['user_email'=>$this->user_email]);
    }
}

 ?>

SiteController(仅限登录功能)

public function actionLogin()
    {

        if(!Yii::$app->user->isGuest)
        {
            return $this->goHome();
        }
        else {
            $login_model = new Login();
            return $this->render('login',['login_model'=>$login_model]);
        }
    }

1 个答案:

答案 0 :(得分:0)

输入用户名和密码是不够的,您还应该执行登录

public function actionLogin()
{

    if(!Yii::$app->user->isGuest)
    {
        return $this->goHome();
    }
    if ($model->load(Yii::$app->getRequest()->post())) {
        // you should perform  login 
        \Yii::$app->getUser()->login($model->user, $this->rememberMe ? $model->module->rememberFor : 0);
        return $this->goBack();
    }

    else {
        $login_model = new Login();
        return $this->render('login',['login_model'=>$login_model]);
    }
}