簡體   English   中英

在自定義控制器中進行身份驗證登錄

[英]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'); 

默認情況下,Cakes Auth也在尋找名為“用戶名”的字段,因此您有2個選項,而不是使用User.nickname

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

(並記住將驗證從昵稱更改為用戶名)

要在$ components數組中為用戶auth配置不同的字段,然后為用戶名配置用戶名:在$ components數組中傳遞設置

public $components = array(
'Auth' => array(
      'authenticate' => array(
          'Form' => array(
              'fields' => array('username' => 'nickname')
          )
      )
  )
);

我強烈建議您閱讀Cake的Auth Auth組件,這樣可以避免類似的錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM