在自定义控制器中验证登录


Auth login in Custom Controller

在我的应用程序中进行登录功能时,我发现了一个无法解决的问题…

我在IndexController中创建了login()动作,我正在尝试验证给定的数据。主要问题是,我不能将它们与用户模型连接,其中包含登录所需的所有数据,例如昵称(用户名)和密码。代码如下:

IndexController.php

App::uses('AppController', 'Controller');
App::import('Controller', 'Users');
class IndexController extends AppController{
public $helpers = array('Html','Form', 'Session');
public $uses = array('User', 'Registration');
public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow();
} 
public function index(){
    $menu = $this->menu();
    $this->set('menu', $menu);
}
public function login(){
    if ($this->request->is('post')) {
        $this->Auth->authenticate = array('Form' => array('userModel' => 'User' ));
        var_dump($this->Auth->login());
        exit();
        if ($this->Auth->login($this->request->data)) {
            return $this->redirect($this->Auth->redirectUrl());
        }else{
            $this->Session->setFlash(__('Invalid username or password, try again'));
            $this->redirect(array('controller' => 'index', 'action' => 'login'));
        }
        if ($this->Session->read('Auth.User')) {
            $this->Session->setFlash('You are logged in!');
            return $this->redirect(array('controller' => 'index', 'action' => 'index'));
        }            
    }        
}

User.php

App::uses('AppModel', 'Model');
App::uses('SimplePasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
public $displayField = 'name';

//public $belongsTo = array('Role');
    //public $actsAs = array('Acl' => array('type' => 'requester'));
public $validate = array(
    'name' => array(
        'maxLength' => array(
            'rule' => array('maxLength', 20),
            'message' => 'Name field is too long'
        )
    ),
    'nickname' => array(
        'notEmpty' => array(
            'rule' => array('notEmpty'),
            'message' => 'Field cannot be empty'
        ),
        'maxLength' => array(
            'rule' => array('maxLength', 20),
            'message' => 'Nickname field is too long'
        ),
    ),
    'password' => array(
        'notEmpty' => array(
            'rule' => array('notEmpty'),
            'message' => 'Field cannot be empty',
        ),
    ),
    'role_id' => array(
        'numeric' => array(
            'rule' => array('numeric')
        ),
    ),            
    'email' => array(
        'email' => array(
            'rule' => array('email'),
            'message' => 'Wrong email address format'
        ),
        'notEmpty' => array(
            'rule' => array('notEmpty'),
            'message' => 'Field cannot be empty',
        ),
        'maxLength' => array(
            'rule' => array('maxLength', 30),
            'message' => 'Your custom message here'
        ),
    ),
    'avatar' => array(
        'maxLength' => array(
            'rule' => array('maxLength', 50),
        ),
    ),
    'points' => array(
        'numeric' => array(
            'rule' => array('numeric'),
        ),
    ),
);
    public function beforeSave($options = array()) {
        if (isset($this->data[$this->alias]['password'])) {
            $passwordHasher = new SimplePasswordHasher();
            $this->data[$this->alias]['password'] = $passwordHasher->hash(
                $this->data[$this->alias]['password']
            );
        }
        return true;
    }        
}

和UserController.php

App::uses('AppController', 'Controller');
class UsersController extends AppController {
    public $helpers = array('Html', 'Form', 'Session', 'Paginator');
    public $components = array('Auth', 'Session');
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('');
    }
    public function index(){
        $this->User->recursive = 0;
        $this->set('users', $this->paginate());            
    }
    public function view($id = null){
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        $this->set('user', $this->User->read(null, $id));            
    }
    public function edit($id = null){
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->request->is('post','put')) {
            if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('The user has been saved'));
                return $this->redirect(array('action' => 'index'));
            }
            $this->Session->setFlash(
                __('The user could not be saved. Please, try again.')
            );
        } else {
            $this->request->data = $this->User->read(null, $id);
            unset($this->request->data['User']['password']);
        }
        $roles = $this->User->Role->find('list');
        $this->set(compact('roles'));            
    }
    public function add(){
        if($this->request->is('post')){
            $this->User->create();
            if($this->User->save($this->request->data)){
                $this->Session->setFlash('User has been registered');
                return $this->redirect(array('controller' => 'index', 'action' => 'index'));
            }
            $this->Session->setFlash('Unable to register now, try again');
        }
    $roles = $this->User->Role->find('list');
    $this->set(compact('roles'));
    }
    public function delete($id = null) {
        $this->request->onlyAllow('post');
        $this->User->id = $id;
        if (!$this->User->exists()) {
            throw new NotFoundException(__('Invalid user'));
        }
        if ($this->User->delete()) {
            $this->Session->setFlash(__('User deleted'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('User was not deleted'));
        return $this->redirect(array('action' => 'index'));
    }        
    public function login() {
    }

 }

Login.ctp

    <div class="users form">
    <?php echo $this->Session->flash('auth'); ?>
    <?php echo $this->Form->create('User'); ?>
        <fieldset>
            <legend>
                <?php echo __('Please enter your username and password'); ?>
            </legend>
            <?php echo $this->Form->input('User.nickname');
            echo $this->Form->input('User.password');
        ?>
        </fieldset>
    <?php echo $this->Form->end(__('Login')); ?>
    </div>

这里有一个问题:有可能让它变成那样吗?

编辑

对不起,我忘了添加我在AppController中设置的所有Auth规则:

AppController.php

App::uses('Controller', 'Controller');
class AppController extends Controller {
    public $components = array(
        'Session',
        'Acl',
        'Auth' => array(
            'authorize' => array(
                'Actions' => array('actionPath' => 'controllers')
            ),
            'authenticate' => array(
                'Form' => array('username' => 'nickname'),
                'Basic'
            ),
            'loginAction' => array(
                'controller'    => 'index',
                'action'        => 'login'
            ),
            'loginRedirect' => array(
                'controller'    => 'users',
                'action'        => 'index'
            ),
            'logoutRedirect' => array(
                'controller'    => 'index',
                'action'        => 'index',
            )    
        )
    );    
}

首先这一行绝对是错误的:

echo $this->Form->input('Userpassword');

改为

echo $this->Form->input('password'); 

also Cakes Auth默认情况下正在寻找名为"username"的字段,因此您有2个选项而不是User。昵称使用

echo $this->Form->input('username');

(并记住将验证从昵称更改为用户名)

为$components数组中的auth用户配置不同的字段和用户名:在$components array

中传递设置
public $components = array(
'Auth' => array(
      'authenticate' => array(
          'Form' => array(
              'fields' => array('username' => 'nickname')
          )
      )
  )
);

我强烈建议你阅读Cake的Auth组件,这样你就可以避免这样的错误。