2013-10-18 83 views
0

我已經寫了一個用戶控制器,如果提交的用戶名和密碼(用cakephp的Security :: hash()=>例如6b0deec0d563224524da45691584643bc78c96ea加密,沒有額外的哈希設置)行在數據庫中。但它不起作用,我不知道爲什麼。Auth登錄在cakephp中不起作用

這是我UsersController.php

public function add() { 
    $this->set("title_for_layout", "Register"); 

    if($this->request->is("post")) { 
     $this->User->set($this->request->data); 

    if($this->User->save(array("password" => Security::hash($this->request->data["User"]["password"])))) { 
      $this->Session->setFlash(__("Successfully registred."), "flash_success"); 
      $this->redirect("/login"); 
    } else { 
     $this->Session->setFlash(__("Validation failed."), "flash_danger"); 
    } 
    } 
} 

登記工作正常,並在數據庫中的行創建在那裏我有colums「用戶名」,其中包含的用戶名平淡如的一個片段包含散列字符串的「myuser」和「password」。我不認爲這個問題可以在這裏解決。

這是我UsersController.php

public function login() { 
    $this->set("title_for_layout", "Login"); 

    if($this->request->is("post")) { 
     if($this->Auth->login()) { 
      $this->Session->setFlash("Login successfull.", "flash_success"); 
     } else { 
      $this->Session->setFlash("Login failed.", "flash_danger"); 
     } 
    } 
} 

的另一個片段這裏是視圖login.ctp

<?php echo $this->Form->create('User'); ?> 
<?= $this->Form->input("username"); ?> 
<?= $this->Form->password("password"); ?> 
<?= $this->Form->end("submit"); ?> 

這是我的問題:登錄總是失敗。另外,我在$component陣列中沒有任何設置。

我該如何解決問題?

+0

您不應該在控制器中手動散列。請參閱[此處]的文檔(http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/)。另外調用save()和set()之後傳遞的數據聽起來像是可以輕易破解的東西。爲了完整起見:你也缺少create()。 – mark

+0

現在我改變了方式,新用戶將被保存,但這並不能解決我的問題。在數據庫中保存的數據與以前相同(但這種新方法更清潔,謝謝)。現在我發現,'$ this-> Auth-> login()'的sql查詢只查找數據庫中的用戶名,而不是密碼。這個查詢看起來像這樣:'[']'users'AS'User'WHERE'User'。'username'='xxx'LIMIT 1'。但查詢中的密碼在哪裏? – user2626702

+0

嘗試'$ this-> Form-> input(「password」)'儘管兩者都應該工作。併發布您的控制器身份驗證配置。這可能是您的配置關閉的地方。 – mark

回答

0

如果你使用CakePHP的2.x的,那麼你可以設置在模型中的回調函數beforeSave()密碼加密作爲

<?php 
// app/Model/User.php 
App::uses('AuthComponent', 'Controller/Component'); 
class User extends AppModel { 

// ... 

public function beforeSave($options = array()) { 
    if (isset($this->data[$this->alias]['password'])) { 
     $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']); 
    } 
    return true; 
} 

?> 

欲瞭解更多信息,請按照link。如果你仍然想要在控制器中加密密碼,那麼你可以使用類似的代碼。

public function add() { 
    $this->set("title_for_layout", "Register"); 

    if($this->request->is("post")) { 
     $this->User->set($this->request->data); 

    if($this->User->save(array("password" => $this->Auth->password($this->request->data["User"]["password"])))) { 
      $this->Session->setFlash(__("Successfully registred."), "flash_success"); 
      $this->redirect("/login"); 
    } else { 
     $this->Session->setFlash(__("Validation failed."), "flash_danger"); 
    } 
    } 
} 

?> 

如果你使用CakePHP的2.4或更高版本然後按照文檔here