CakePHP 2 AuthComponent

时间:2012-08-11 13:37:11

标签: cakephp cakephp-2.x

我无法使用AuthComponent登录任何用户。 用户表的名称是用户,有一些重要的字段,如user_id,user_password,密码字段上没有散列。

这是我的AppController

class AppController extends Controller {
  public $components = array(
    'Session',
    'Auth' => array(
      'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
      'logoutRedirect' => array('controller' => 'users', 'action' => 'home'),
      'authError' => 'You cannot view this page',
      'authorize' => array('controller')
    )
  );

  public function isAuthorize($user) {
    return true;
  }

  public function beforeFilter() {
    $this->Auth->allow('home');
  }
}

这是我的UsersController

class UsersController extends AppController {
  public function login() {
    if ($this->request->is('post')) {
      if ($this->Auth->login()) {
        $this->redirect($this->Auth->redirect());
      } else {
        $this->Session->setFlash('Cannot login in');  
      }
    }
  }
}

这是我的用户模型。

class User extends AppModel {
  public $name = 'User';
  public $primaryKey = 'user_id';
  public $belongsTo = 'Group'; 
}

这是我的观点

<h2>Login</h2>

<?php

echo $this->Form->create();
echo $this->Form->input('user_id', array('label' => 'User ID', 'type' => 'text'));
echo $this->Form->input('user_password', array('label' => 'Password', 'type' => 'password'));
echo $this->Form->end('Login');

?>

当我输入更正后的user_id和密码然后按下“登录”按钮时,我收到了来自UsersController的无法登录的消息。这里出了什么问题???

另外,我真的不了解AuthComponent的概念:login(),如何检查数据库中的user_id和密码,如何知道哪个字段包含user_id,哪个包含密码? ??

请帮忙。 谢谢。 Kongthap

1 个答案:

答案 0 :(得分:1)

我注意到的一些事情:

public function isAuthorize($user) {

此方法最后缺少'd'。它应该是

public function isAuthorized($user) {

接下来,默认情况下,Cake希望通过名为“username”和“password”的字段来标识用户。所以,如果你想改变它,你需要这样做:

class AppController extends Controller {
  public $components = array(
    'Session',
    'Auth' => array(
      'loginRedirect' => array('controller' => 'users', 'action' => 'index'),
      'logoutRedirect' => array('controller' => 'users', 'action' => 'home'),
      'authError' => 'You cannot view this page',
      'authorize' => array('controller'),
      'authenticate' => array(
          'Form' => array( // THIS IS WHERE YOU CHANGE THE DEFAULT FIELDS
             'fields' => array('username' => 'user_id','password' => 'user_password')
          )
       )
    )
  );

该代码未经过测试,但应该让您走上正轨。但正如戴夫所说,真正值得通过完整的doco来阅读它是如何运作的:http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html

最后,我不确定'user_id'是列名的好选择。您希望列名'user_id'是某个表中的外键,指向'users'表的'id'列。如果这不是它所服务的功能,你应该使用不同的名称。

相关问题