1

在 yii 我可以使用:

self::ERROR_USERNAME_INVALID;

我想要另一个:

self::ERROR_USER_BANNED;

那必须给出错误:

Sorry, but you cannot login because you account has been blocked.

我该如何设置?

4

2 回答 2

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;
        }
    }
}

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);
}

当然,您可以在 UserIdentity 中声明另一个函数来仅检查禁止,并从isBanned验证器调用该函数,而不是在authenticate函数中添加内容。

于 2012-12-03T10:49:48.243 回答
0

在 UserIdentity.php 中添加以下内容

const ERROR_USER_BANNED = 12 ; #or whateve int value you prefer


public function getErrorMessageX() #or whatever method name
{
    switch ($this->errorCode)
    {
        case self::ERROR_USER_BANNED:
            return 'sorry, your account has been banned'; # custom error msg

        case self::ERROR_USERNAME_INVALID:
            return 'User does not exists';

        case self::ERROR_PASSWORD_INVALID:
            return 'Password does not match';

        case self::ERROR_ACCOUNT_NOT_CONFIRMED:           #this one is mine:)
            return 'This Account needs confirmation';
    }
}

现在在 LoginForm.php

public function authenticate( )
{
    $this->_identity = new UserIdentity($this->username,$this->password);

    if( $this->_identity->authenticate() === FALSE )
        $this->addError('username', $this->_identity->errorMessageX); #here

            #some more code

    return !$this->_identity->errorCode;
}
于 2012-12-08T06:46:54.400 回答