2012-12-03 27 views

回答

5

直接將它添加到您的保護/組件/ 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); 
} 

Ofcourse you can declare d UserIdentity中的另一個函數檢查是否禁用,並從驗證程序isBanned中調用該函數,而不是在authenticate函數中具有某些東西。

+0

但我得到它如何顯示我的自定義消息? – coderama

+0

這取決於你如何登錄用戶,默認方式設置LoginForm.php模型文件中的錯誤,你使用的是? –

+0

我是的。但不知道它的確切位置如下所示:「如果(ERROR_USER_BANNED)$ message ='Bla bla bla'...那是我無法匹配的部分。 – coderama

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

Side-Not:記住要根據方法重命名屬性 –