Cakephp中的身份验证问题

时间:2013-09-13 07:03:40

标签: cakephp-2.0 cakephp-2.3

我是CakePhp的新手,我在登录用户时遇到问题, 我正在使用CakePhp 2.4,我使用blowfish这里的密码是我用户模型的代码

App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');

/**
 * User Model
 *
 */
class User extends AppModel {

    /**
     * Validation rules
     *
     * @var array
     */
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A username is required'
            )
        ),
        'password' => array(
            'alphanumeric' => array(
                'rule' => array('alphanumeric'),
                'message' => 'Password needs to be alphanumeric',
                'allowEmpty' => false,
                'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
            /*'minlength' => array(
                'rule' => array('minlength'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),*/
        ),
        'firstname' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'middlename' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
        'lastname' => array(
            'notempty' => array(
                'rule' => array('notempty'),
                //'message' => 'Your custom message here',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                //'on' => 'create', // Limit validation to 'create' or 'update' operations
            ),
        ),
    );      

    public function beforeSave($options = array()){
        //Override beforeSave to set modified field to NULL
        if(!empty($this->data[$this->alias]['modified']) || isset($this->data[$this->alias]['modified']))
            unset($this->data[$this->alias]['modified']); 

        //Hash passwords before saving to database
        if(!empty($this->data[$this->alias]['password']) || isset($this->data[$this->alias]['password'])){
            $hashedPassword = Security::hash($this->data[$this->alias]['password'],"blowfish");
            $this->data[$this->alias]['password'] = $hashedPassword;
        }
        return true;
    }
}

现在当我尝试登录用户时,那就是出现问题的地方, 即使我提供了错误的凭证

  

(未在数据库中注册的用户),   用户仍然会登录。这是我的AppController

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

  class AppController extends Controller {
  public $components = array(
    'DebugKit.Toolbar',
    'Session',
    'Auth' => array(
        'authenticate' => array('Blowfish'),
        'loginRedirect' => array('controller' => 'computers', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'users', 'action' => 'index')         
    )
   );

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

这是我的UsersController

<?php
App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 * @property PaginatorComponent $Paginator
 * @property RequestHandlerComponent $RequestHandler
 */
class UsersController extends AppController {

/**
 * Helpers
 * @var array
 */
public $helpers = array('Session');

/**
 * Components
 * @var array
 */
public $components = array('Paginator', 'RequestHandler');

public function beforeFilter(){
    parent::beforeFilter();
    $this->Auth->allow(array('signup','check_user'));//Letting users register themselves
}

/**
 * index method
 * @return void
 */
public function index() {
    $this->layout = 'custom_layouts/default';
    $data = array(
        'id' => 'myLayout',
        'title_for_layout' => 'Reservation . Better Reservation'
    );
    $this->set($data);
    /*
    $this->User->recursive = 0;
    $this->set('users', $this->Paginator->paginate());*/
}

public function login(){
    if($this->request->is('post')){
        if($this->Auth->login()){ return $this->redirect($this->Auth->redirectUrl()); }
        $this->Session->setFlash(__('Invalid username or password, try again.'));
    }       
    $this->layout = 'custom_layouts/default';
    $data = array(
        'id' => 'signin',
        'title_for_layout' => 'Reservation . Sign in'
    );
    $this->set($data);      
}   

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

/*
* signup method
* @return void
*/
public function signup(){
    if($this->request->is('post')){
        $this->User->create();          
        if($this->User->save($this->request->data)){
            $this->Session->setFlash(__('Your Account has been successfully added.'));
            return $this->redirect(array('action' => 'login'));
        }
        else{ $this->Session->setFlash(__('The user could not be saved. Please, try again.')); }
    }
    $this->layout = 'custom_layouts/default';
    $data = array(
        'id' => 'signup',
        'title_for_layout' => 'Reservation . Sign up'
    );
    $this->set($data);  
}   

/*
* check_user method
* @return json
*/
public function check_user(){
    $user = NULL;
    if($this->request->is('get')){
        $this->disableCache();
        $ajax_query = $this->request->query('requested_user');
        $isExisting = $this->User->find(
            'first',
            array(
                'condition' => array(
                    'User.username' => $ajax_query
                )
            )
        );
        if($isExisting){
            $user = $this->User->find(
                'first',
                array(
                    'fields' => array(
                        'User.username',
                        'User.firstname',
                        'User.lastname'
                    ),
                    'conditions' => array('User.username' => $ajax_query)
                )
            );
        }
        $this->set('response', $user);
        $this->set('_serialize','response');
    }
}

//Baked methods
/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
 /*
public function view($id = null) {
    if (!$this->User->exists($id)) {
        throw new NotFoundException(__('Invalid user'));
    }
    $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
    $this->set('user', $this->User->find('first', $options));
}*/

/**
/*
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
 /*
public function edit($id = null) {
    if (!$this->User->exists($id)) {
        throw new NotFoundException(__('Invalid user'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('The user has been saved.'));
            return $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
        }
    } else {
        $options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
        $this->request->data = $this->User->find('first', $options);
    }
}*/

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
 /*
public function delete($id = null) {
    $this->User->id = $id;
    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid user'));
    }
    $this->request->onlyAllow('post', 'delete');
    if ($this->User->delete()) {
        $this->Session->setFlash(__('The user has been deleted.'));
    } else {
        $this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
    }
    return $this->redirect(array('action' => 'index'));
}*/
}

我已经做了很多谷歌搜索来解决这个问题无济于事, 在cakephp文档上,我已阅读此笔记

  

在2.x $ this-&gt; Auth-&gt;登录($ this-&gt; request-&gt; data)将使用所发布的任何数据记录用户,而在1.3 $ this-&gt; Auth- &gt;登录($ this-&gt; data)将首先尝试识别用户,并且仅在成功时登录。   如果这是原因,如果为什么即使提供的用户凭据未在数据库中注册,用户仍将进行身份验证,是否有任何类型的解决方法?

1 个答案:

答案 0 :(得分:0)

我认为您应该在appcontroller中定义userModel

'loginAction' => array('controller'=>'Admin', 'action'=>'login'),
                'loginRedirect' => array('contoller'=>'Admin', 'action'=>'login'),
                'logoutRedirect' => array('controller'=>'Admin', 'action'=>'logout'),
                'authError' => '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button>
                                    You are not authorized to access this location</div>',
                'authenticate' => array(
                    'Form' => array(
                        'userModel' => 'User',
                        'fields' => array(
                            'username' => 'email',
                            'password'=>'password')
                    )
                )
            );