1

I'm using CakePHP 2.7.8 to build an admin panel. My project contains multiple admins instead of users. That's why I have an admins table in the database and not an users table.

I'm using BlowfishHasher for hashing passwords, and it's working fine. Passwords are hashed before saving to database.

But login() returns:

Invalid username or password, try again

Table admins:

CREATE TABLE `admins` (
  `id` char(36) NOT NULL,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  `gender` varchar(45) DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `modified` datetime DEFAULT NULL,
  PRIMARY KEY (`id`))

Admins model : Admin.php

<?php
App::uses('AppModel', 'Model');
App::uses('BlowfishPasswordHasher','Controller/Component/Auth');
/**
 * Admin Model
 *
 */
class Admin extends AppModel {

/**
 * Display field
 *
 * @var string
 */

    public $displayField = 'first_name';


        public function beforeSave($options = array()) {
            if(isset($this->data[$this->alias]['password'])){
                $passwordHasher = new BlowfishPasswordHasher();
                $this->data[$this->alias]['password'] = $passwordHasher->hash(
                    $this->data[$this->alias]['password']
                        );
            }
            return true;
        }
}

Admins Controller : AdminsController.php

<?php
App::uses('AppController', 'Controller');
/**
 * Admins Controller
 *
 * @property Admin $Admin
 * @property PaginatorComponent $Paginator
 * @property FlashComponent $Flash
 * @property SessionComponent $Session
 */
class AdminsController extends AppController {

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

/**
 * index method
 *
 * @return void
 */
    public function index() {
        $this->Admin->recursive = 0;
        $this->set('admins', $this->Paginator->paginate());
    }
/**
 * login function
 */
        public function login(){
            if($this->request->is('post')) {
                if($this->Auth->login()) {
                    return $this->redirect($this->Auth->redirectUrl());
                }
                $this->Flash->error(__('Invalid username or password, try again'));
            }
        }

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

App Controller : AppController.php

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

/**
 * @package     app.Controller
 * @link        http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
 */
class AppController extends Controller {

    public $components = array(
        'Flash',
        'Auth' => array(
            'loginRedirect'=>array(
                'controller'=>'admins',
                'action'=>'index'
            ),
            'logoutRedirect'=>array(
                'controller'=>'admins',
                'action'=>'login'
            ),
            'authenticate'=>array(
                'Form'=>array(
                    'passwordHasher'=>'Blowfish'
                )
            )
        )
    );

    function beforeFilter() {
        $this->Auth->authenticate = array(
            AuthComponent::ALL => array(
                'userModel' => 'Admin'
            )
        );
        $this->Auth->allow('login','add','index');
    }
}

Login view : login.ctp

<div class="users form">
    <?php echo $this->Flash->render('auth'); ?>
    <?php echo $this->Form->create('admin'); ?>
        <fieldset>
        <legend>
            <?php echo __('Please enter your username and password'); ?>
        </legend>
        <?php 
            echo $this->Form->input('username'); 
            echo $this->Form->input('password');
        ?>
    </fieldset>
    <?php echo $this->Form->end(__('Login')); ?>
</div>
Inigo Flores
  • 4,461
  • 1
  • 15
  • 36

2 Answers2

0

From the problem you've posted, I think there's a chance that your password isn't hashing properly when you're logging in.

Try a bit of debugging in your login action:

    public function login(){

        if($this->request->is('post')) {

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

            $passwordHasher = new BlowfishPasswordHasher();

            $this->request->data['Admin']['password'] = $passwordHasher->hash(
                   $this->request->data['Admin']['password']
            );

            pr($this->request->data);

            exit;

            // Take a look at this $this->request->data["Admin"]["password"] field and compare it with the password you have in the database. Do they match?

            if($this->Auth->login()) {
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Invalid username or password, try again'));
        }
    }

Peace! xD

Indrasis Datta
  • 8,692
  • 2
  • 14
  • 32
  • Debugging gives different hash every time login is requested with same username and password. This is what I get on debug `Notice (8): Undefined index: Admin [APP/Controller/AdminsController.php, line 135] Array ( [admin] => Array ( [username] => qwerty [password] => qwerty ) [Admin] => Array ( [password] => $2a$10$Xx9VTgAhUnYApkLNXeQ2sOEJDuvGqYB4ZWz9MfD6p9w3YxGKaIFdC ) )` and the password in the database is `$2a$10$x4S46.KX9Okq7Kzedf0J3e3xuX41UTkRMzr7qhhSGR/kDdKOzC.Zi` –  Jan 22 '16 at 13:09
-1

Try changing your password field from VARCHAR(255) to BINARY(60).

Remember to clear your models cache after doing so.

See the following question for further details:


Edit

Also the AuthComponent configuration defined in the $components array is being overwritten in beforeFilter().

Try replacing the following code:

$this->Auth->authenticate = array(
    AuthComponent::ALL => array(
        'userModel' => 'Admin'
    )
);

with:

$this->Auth->authenticate[AuthComponent::ALL] = array(
    'userModel' => 'Admin'
);

Edit 2

In your view, you have to replace

<?php echo $this->Form->create('admin'); ?>

with

<?php echo $this->Form->create('Admin'); ?>

Case is important.

Community
  • 1
  • 1
Inigo Flores
  • 4,461
  • 1
  • 15
  • 36
  • no effect again. On debug using code by @object-manipulator , Password is hashing differently each time login is called with same username password. –  Jan 22 '16 at 13:20
  • This is expected behaviour. Blowfish uses a random salt every time. Have you implemented both the above modifications? Have you cleared the cache? – Inigo Flores Jan 22 '16 at 13:23
  • I do have implemented both modifications but still there is no effect. –  Jan 22 '16 at 13:49
  • I think there is a problem with your login form. Please post the `login.ctp` view. – Inigo Flores Jan 22 '16 at 13:53
  • See my last edit. Please note that it's not one solution or the other. Everything mentioned in my answer must be taken care of. – Inigo Flores Jan 22 '16 at 14:13
  • Thank you so much. Finally it worked. Your 'Edit 1' and 'Edit 2' both worked and finally its working. –  Jan 22 '16 at 15:33
  • sorry for the downvote you have received by someone. I have upvoted your answer but since I'm new here and my reputation is under 15, it will be automatically upvoted from my side once I achieve 15 reputation. –  Jan 22 '16 at 15:44
  • hey! although login is working by visiting `/admins/login` manually but on accessing unauthorized module before login is now redirecting to `/users/login` which does not exist instead of redirecting to `/admins/login` also after login `loginRedirect` is not working and it redirects to last page requested before login() –  Jan 22 '16 at 16:28
  • 1
    You need to add option `'loginAction'` to the `$components['Auth']` array. See [Configuring Authentication handlers](http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html#configuring-authentication-handlers). Regarding `'loginRedirect'`, it's a feature. See [Identifying users and logging them in](http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html) – Inigo Flores Jan 22 '16 at 18:05