2014-10-11 60 views
0

嗨,我有一個表名chat_usersCakePHP:如何使用非默認用戶模型進行身份驗證?

我已連接users表爲最後幾個項目工作正常。但是,這是我的第一個項目,我有chat_users

我想登錄此表usernamepassword

我都試過,但無法登錄不同的表名。

請幫幫我。

代碼 -

AppController.php

<?php 
App::uses('Controller', 'Controller'); 

class AppController extends Controller { 
    public $components = array('Auth', 'Session', 'Email', 'Cookie', 'RequestHandler', 'Custom'); 
    public $helpers = array('Html', 'Form', 'Cache', 'Session','Custom'); 

    function beforeFilter() { 
     parent::beforeFilter(); 

     $this->Auth->authenticate = array(
      'Form' => array (
       'scope' => array('ChatUser.is_active' => 1), 
       'fields' => array('ChatUser.username' => 'username', 'ChatUser.password' => 'password'), 
      ) 
     );   
    } 
} 
?> 

UsersController.php

<?php 
App::uses('AppController', 'Controller'); 
class UsersController extends AppController { 

    public $name = 'Users'; //Controller name 
    public $uses = array('ChatUser'); 
    public function beforeFilter() { 
     parent::beforeFilter(); 
     $this->Auth->allow('login'); 
    } 
    public function index() { 
    } 
    public function login() { 
     $this->layout='login'; 
     if ($this->request->is('post')) { 
      if (!$this->Auth->login()) { 
       $this->Session->setFlash(__('Invalid username or password, try again'), 'error_message'); 
       $this->redirect($this->Auth->redirect()); 
      } 
     } 
     if ($this->Session->read('Auth.ChatUser')) { 
       return $this->redirect(array('action' => 'index')); 
       exit; 
     } 
    } 

    public function logout() { 
     return $this->redirect($this->Auth->logout()); 
    } 
} 

上面的查詢我收到失蹤表。

見screenshot-

enter image description here

+0

能否請您讓我們知道所謂的,當你登錄登錄方法?如果是這樣,那麼在登錄方法中執行哪個條件?另外,您可以參考這個[URL](http://technet.weblineindia.com/web/working-with-auth-component-in-cakephp/) – 2014-10-11 04:22:54

+0

請始終提及您的確切CakePHP版本並相應地標記您的問題!另外,當收到錯誤時,請發佈確切的錯誤消息。 – ndm 2014-10-11 05:28:20

回答

0

你的身份驗證組件配置不正確。你缺少適當的userModel選項,定義模型的名稱使用

而且fields配置不工作,你正在使用它的方式,密鑰必須命名爲usernamepassword,和值就可以包含實際的列名稱,但是由於您的列顯然使用默認名稱,因此根本不需要使用此選項。

$this->Auth->authenticate = array(
    'Form' => array (
     'scope' => array('ChatUser.is_active' => 1), 
     'userModel' => 'ChatUser' 
    ) 
); 

而且會話密鑰永遠是Auth.User,除非你明確地通過AuthComponent::$sessionKey改變它:

$this->Auth->sessionKey = 'Auth.ChatUser'; 

但是,你正在使用的身份驗證組件反正訪問用戶數據的更好:

// Use anywhere 
AuthComponent::user('id') 

// From inside a controller 
$this->Auth->user('id'); 

看到LSO

+0

嗨,你告訴我鑰匙必須命名爲'用戶名'和'密碼'。假設我有'email'字段而不是'username',那麼我該怎麼辦? – Developer 2014-10-13 05:14:41

+0

'$ this-> Auth-> user('id');'不在視圖中工作。它會是'$ this-> Session-> read('Auth.User.id');' – Developer 2014-10-13 05:19:49

+0

@chatfun正如我所說的,實際的列名被定義爲數組值(''username'=>' email'')。只要閱讀鏈接的文檔,它就會顯示在那裏。當然'$ this-> Auth-> user('id');'在視圖中不起作用,這就是爲什麼它說「_From在controller_中」。在視圖中,您可以使用'AuthComponent :: user('id')',它可以是「_used anwhere_」,或者只是將控制器中的值傳遞給視圖。 – ndm 2014-10-13 11:56:05

相關問題