2012-08-07 87 views
2

我有一些代碼可以防止被刪除和禁止的用戶登錄。要清除頭腦,狀態爲-2意味着用戶被刪除,-1意味着用戶被禁止。下面是在本地工作正常的代碼,但在實際上它很糟糕。狀態爲-1或-2的用戶仍可以登錄。我找不到問題所在。CakePHP 2.x無法阻止已刪除和禁止的用戶登錄

if ($this->Auth->login()) { 
    //first check if the user's status is -1 or -2. 
    $status = $this->Auth->user('status'); 

    if ($status == '-1') { 
     $this->Auth->logout(); 
     $this->Session->setFlash(__('This account has been banned. Please contact with us.')); 
     $this->redirect('/'); 
    } elseif ($status == '-2') { 
     $this->Auth->logout(); 
     $this->Session->setFlash(__('This account has been deleted, and is not usable anymore.')); 
     $this->redirect('/'); 
    } 

    //something else 
} 

回答

10

通過在要登錄的用戶檢查呼叫$this->Auth->login()

你可能避免這種情況,並檢查之前用戶信息登錄,或者您可以在狀態標誌添加到範圍,爲用戶。

$this->Auth->authenticate = array(
    AuthComponent::ALL => array(
     'userModel' => 'User', 
     'scope' => array('User.status' => '> 0) 
    ), 
    'Form', 
    'Basic' 
); 

這將status字段檢查添加到登錄過程。

如果您希望自定義郵件作爲你的榜樣,您可以處理在登錄前檢查用戶信息的值:

$user = $this->User->findByUsername($this->data['User']['username']); 
if (!empty($user)) { 
    if ($user['User']['status'] == -1) { 
     // Set message for banned account 
    } 
    if ($user['User']['status'] == -2) { 
     // Set message for deleted account 
    } 
    $this->redirect(...); // Redirect away 
} 

if ($this->Auth->login()) { 
    // Normal login process 
} 
+0

我不知道的範圍鍵,這是2.2版本中的新功能。謝謝(你的)信息!但現在這不適合我。第二種解決方案在當地運作良好,但不在現場。我做了很多調試,但仍然無法解決問題。 – hswner 2012-08-07 02:39:00

+0

你好。現在它也可以在現場使用。我沒有做任何承諾,除了刪除一個緩存文件,它具有路徑app/tmp/cache/persisten/myapp_cake_core_file_map。這很奇怪! – hswner 2012-08-07 02:47:35

+2

範圍鍵對CakePHP 2並不新鮮。 – Predominant 2012-08-07 02:51:59

2

範圍的回答是最好的,但有一個小錯誤的條件,而不是

'scope' => array('User.status' => '> 0) 

該行應

'scope' => array('User.status >' => 0) 

這是典型的CakePHP的方式在狀態陣列添加比較運算符

(我剛纔評論這一點,但它是更容易地創建一個答案時,新來這個網站。)