在 yii 我可以使用:
self::ERROR_USERNAME_INVALID;
我想要另一个:
self::ERROR_USER_BANNED;
那必须给出错误:
Sorry, but you cannot login because you account has been blocked.
我该如何设置?
在 yii 我可以使用:
self::ERROR_USERNAME_INVALID;
我想要另一个:
self::ERROR_USER_BANNED;
那必须给出错误:
Sorry, but you cannot login because you account has been blocked.
我该如何设置?
将其直接添加到您的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
函数中添加内容。
在 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;
}