如何在YII上为用户登录添加更多错误代码?

cod*_*ama 1 yii

在yii我可以使用:

self::ERROR_USERNAME_INVALID;
Run Code Online (Sandbox Code Playgroud)

我想要另一个:

self::ERROR_USER_BANNED;
Run Code Online (Sandbox Code Playgroud)

那必须给出错误:

Sorry, but you cannot login because you account has been blocked.
Run Code Online (Sandbox Code Playgroud)

我该如何设置?

boo*_*dev 5

将其直接添加到protected/components/UserIdentity.php:

class UserIdentity extends CUserIdentity {
    const ERROR_USER_BANNED = -1; // say -1 you have to give some int value

    public function authenticate() {
        // ... code ...
        if (/* condition to check for banning */) { // you might want to put this check right after any other username checks, and before password checks
            $this->errorCode=self::ERROR_USER_BANNED;
            $this->errorMessage='Sorry, but you cannot login because your account has been blocked.'
            return $this->errorCode;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

LoginForm.php模型的默认方式:

添加一个新的验证器规则,比如你的username字段:

public function rules() {
    return array(
        // ... other rules ...
        array('username','isBanned')
    );
}

// the isbanned validator
public function isBanned($attribute,$params) {
    if($this->_identity===null)
        $this->_identity=new UserIdentity($this->username,$this->password);

    if($this->_identity->authenticate() === UserIdentity::ERROR_USER_BANNED){
        $this->addError($attribute,$this->_identity->errorMessage);
}
Run Code Online (Sandbox Code Playgroud)

当然你可以在UserIdentity中声明另一个函数来检查禁止,并从isBanned验证器调用该函数,而不是在authenticate函数中有东西.