简体   繁体   中英

Auth login in Custom Controller

While making login feature in my application, i found a problem i cannot solve..

I created login() action inside IndexController, and i am trying verify given data. Main problem is that i cannot to connect them with User Model which holds all data needed to login , such a nickname (username) and password. The code is below:

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;
    }        
}

And 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>

And here is a question: is it even possible to make it like that?

EDIT

Forgive me, but i forgot to add that all Auth rules i set in AppController:

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',
            )    
        )
    );    
}

First of all this line is definitly wrong:

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

change it to

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

also Cakes Auth by default is looking for field called "username" so you have 2 options instead of User.nickname use

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

(and remember about changing validiation from nickname to username) Or

To configure different field then username for user auth in $components array: Pass settings in $components array

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

I highly recommend you to read about Cake's Auth Component so you will avoid mistakes like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM