首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Yii2:自定义登录失败消息的确切原因

Yii2:自定义登录失败消息的确切原因
EN

Stack Overflow用户
提问于 2017-09-15 06:16:22
回答 4查看 559关注 0票数 0

我想在Yii2中自定义登录失败消息。现在,当我输入错误的username或错误的password时,它将为这两种情况显示相同的消息。

现在,我在user表中有一列,即is_verified,如果验证了用户电子邮件,则将该字段的值设置为1 one 0。

如果用户注册并不验证他的电子邮件,is_verified=0的值

现在,如果用户想登录,那么它将显示Incorrect username or password.

但我想告诉用户,他的电子邮件没有得到验证。

LoginForm.php中,函数validatePassword将通过此错误

代码语言:javascript
复制
public function validatePassword($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

请在这方面提供帮助,或者告诉我如何覆盖默认的登录功能。

我正在使用yii2-basic-app

还有一件事,$user = $this->getUser();,这将只返回那些status=10默认设置为用户status=0的用户,直到他没有验证他的电子邮件为止。

想做什么:

代码语言:javascript
复制
    if(username not exist in db){
        echo "username not found in db";
    }elseif(password not valid){
        echo "password not valid";
    }elseif(is_verified=0){
        echo "email not verified";
    }elseif(status = 0){
        echo "account is deactive";
    }

app\models\User.php代码

代码语言:javascript
复制
/**
     * @inheritdoc
     */
    public static function findIdentity($id) {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null) {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username) {
        return static::findOne(['email' => $username, 'status' => self::STATUS_ACTIVE]);
    }

    /**
     * Finds user by password reset token
     *
     * @param string $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token) {
        if (!static::isPasswordResetTokenValid($token)) {
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token,
            'status' => self::STATUS_ACTIVE,
        ]);
    }

    /**
     * Finds out if password reset token is valid
     *
     * @param string $token password reset token
     * @return boolean
     */
    public static function isPasswordResetTokenValid($token) {
        if (empty($token)) {
            return false;
        }
        $expire = Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        return $timestamp + $expire >= time();
    }

    /**
     * @inheritdoc
     */
    public function getId() {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey() {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey) {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password) {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password) {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey() {
        $this->auth_key = Yii::$app->security->generateRandomString();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken() {
        $this->password_reset_token = Yii::$app->security->generateRandomString() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken() {
        $this->password_reset_token = null;
    }

app\models\LoginForm.php代码

代码语言:javascript
复制
/**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     *
     * @return boolean whether the user is logged in successfully
     */
    public function login() {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser() {
        if ($this->_user === false) {
            $this->_user = User::findByusername($this->username);
        }

        return $this->_user;
    }

谢谢。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2017-09-15 09:50:24

我已经找到了解决办法,现在正如我所期望的那样起了作用。所有的信用都归@scaisEdge所有。我从他的建议中得到了一些想法。现在,我正在发布实际的代码,这些代码可以工作:

代码语言:javascript
复制
public function validatePassword($attribute, $params) {

    if (!$this->hasErrors()) {
        $user = $this->getUser();
        if (!$user) {
            $this->addError("username", 'Invalid username.');
            return;
        }
        if (!$user->validatePassword($this->password)) {
            $this->addError($attribute, 'Incorrect password.');
            return;
        }
        if (User::find()->where(['email' => $this->username])->andwhere(['verified' => 0])->one()) {

            $this->addError("username", 'email not varified ');
            return;
        }
        if (User::find()->where(['username' => $this->username])->andwhere(['status' => 0])->one()) {

            $this->addError($attribute, 'account is not active');
            return;
        }
    }
}

谢谢你的回答,也感谢你能给我一些时间。

我贴出这个答案是为了让其他人能从中得到帮助。

票数 0
EN

Stack Overflow用户

发布于 2017-09-15 06:52:32

您可以分别检查条件!$user!$user->validatePassword($this->password)

代码语言:javascript
复制
public function validatePassword($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = $this->getUser();
            if (!$user |) {
                $this->addError($attribute, 'Invalid username.');
                return;
            }   
            if ( !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect password.');
                return;
            }
        }
    }

您可以检查用户是否以这种方式正确设置。

假设您有一个用户模型类

代码语言:javascript
复制
  $checkUser = User::find()->where('username' => $your_userName)->one();
  if isset($checkUser){
      if($checkUser->status = 0 ){
      // User not activated 
     }
  } else {
     // user not present 
}

查看您的代码,您可以检查输入的if用户名是否已启用,例如:

代码语言:javascript
复制
public function login() {
    if ($this->validate()) {
        if (  User::find()->where(['username' => $this->username , 'status' => 0  ) {
          // mean the user is not  validated ..  
          $this->addError($attribute, 'User not validated .. ');
          return false 
        } else {
          return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);

      }
    } else {
        return false;
    }
}
票数 1
EN

Stack Overflow用户

发布于 2017-09-15 07:08:36

据我所知,职能部门将:

代码语言:javascript
复制
public function validatePassword($attribute, $params) {
    if (!$this->hasErrors()) {
        $user = $this->getUser();
        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, 'Incorrect username or password.');
            return false;
        }
        if(!$user->is_verified){
           $this->addError('username', 'Email is not verified.');
           return false;
       }    
    }
}

当然,如果您从db获取用户,则在其他情况下,您必须在用户或LoginForm模型中再编写一个方法才能获得电子邮件状态表db,例如使用ActiveRecords

代码语言:javascript
复制
 public function validatePassword($attribute, $params) {
    if (!$this->hasErrors()) {
        $user = $this->getUser();
        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, 'Incorrect username or password.');
            return false;
        }
        if(!$user->getUserEmailStatus()){
           $this->addError('username', 'Email is not verified.');
           return false;
       }    
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46232884

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档