Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Password Hasing in Cakephp 3.0.

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.81k
    Comment on it


    Hello Reader's ,
    Hope your are doing good today.

    Today we will learn about password hashing in CakePHP 3.0.
    Before going to start you should know about Password Hashing.

    Now days password are one of the most important security feature for all application which are using user based authentication.It is important for both you and all your users to have secure, unguessable passwords.

    What is password hashing?

    Password hashing algorithms are one way functions.that will take a string or data and turn ino a fixed-length "encrypted" string that cannot be reversed.

    Let's start password Hashing in cakephp 3.

    First you need to create Users table in your Database.

    CREATE TABLE users (
        id INT UNSIGNED NOT NULL AUTO_INCREMENT ,
        username VARCHAR(250) NOT NULL,
        password VARCHAR(255) NOT NULL,
        role VARCHAR(20) NOT NULL,
        created DATETIME DEFAULT NULL,
        modified DATETIME DEFAULT NULL,
    PRIMARY KEY(id)
    );

    Next Create User model in your project dir.

    Location : "// src/Model/Table/UsersTable.php"

    <?php
    namespace App\Model\Table;
    
    use Cake\ORM\Table;
    use Cake\Validation\Validator;
    
    class UsersTable extends Table
    {
    
        public function validationDefault(Validator $validator)
        {
            return $validator
                ->notEmpty('username', 'A username is required')
                ->notEmpty('password', 'A password is required')
                ->notEmpty('role', 'A role is required')
                ->add('role', 'inList', [
                    'rule' => ['inList', ['admin', 'user']],
                    'message' => 'Please enter a valid role'
                ]);
        }
    
    }

    In above code we are validating data before submit.

    In next step create our UsersController . In controller we are adding and showing user details.
    Location: // src/Controller/UsersController.php

    <?php
    namespace App\Controller;
    
    use App\Controller\AppController;
    use Cake\Event\Event;
    
    class UsersController extends AppController
    {
    
        public function beforeFilter(Event $event)
        {
            parent::beforeFilter($event);
            $this->Auth->allow('add','index');
        }
    
         public function index()
         {
            $this->set('users', $this->Users->find('all'));
        }
    
        public function add()
        {
            $user = $this->Users->newEntity();
            if ($this->request->is('post')) {
                $user = $this->Users->patchEntity($user, $this->request->data);
                if ($this->Users->save($user)) {
                    $this->Flash->success(__('The user has been saved.'));
                    return $this->redirect(['action' => 'index']);
                }
                $this->Flash->error(__('Unable to add the user.'));
            }
            $this->set('user', $user);
        }
    
    }

    Now create the view for our user.For the purpose of this tutorial, we will show just the index.ctp and add.ctp.

    index.ctp

    Location " src/Template/Users/index.ctp"

    <table border="1" align="center" bgcolor="#F8F8FF">
    	<tr >
    		<th colspan="4"><h1>User Info</h1>
    			<p><?= $this->Html->link("Add New User", ['action' => 'add']) ?></p></br>
    	</th>
        </tr>
    	
    	<tr>
            <th>Id</th>
            <th>User Name</th>
            <th>Password</th>
            <th>Created</th>
        </tr>
    
        <!-- Here is where we iterate through our $users query object, printing out User info -->
    
        <?php foreach ($users as $user): ?>
        <tr>
            <td><?= $user->id ?></td>
            <td>
                <?= $user->username ?>
            </td>
    	<td>
                <?= $user->password ?>
            </td>
            <td>
                <?= $user->created->format(DATE_RFC850) ?>
            </td>
        </tr>
        <?php endforeach; ?>
    </table>
    

    add.ctp
    Location " src/Template/Users/add.ctp"

    <div class="users form">
    <?= $this->Form->create($user) ?>
        <fieldset>
            <legend><?= __('Add User') ?></legend>
            <?= $this->Form->input('username') ?>
            <?= $this->Form->input('password') ?>
            <?= $this->Form->input('role', [
                'options' => ['admin' => 'Admin', 'author' => 'Author']
            ]) ?>
       </fieldset>
    <?= $this->Form->button(__('Submit')); ?>
    <?= $this->Form->end() ?>
    </div>

    Password hashing is not done yet, we need an Entity class for our User in order to handle its own specific logic. Create the "src/Model/Entity/User.php" entity file and add the following:

    namespace App\Model\Entity;
    
    use Cake\Auth\DefaultPasswordHasher;
    use Cake\ORM\Entity;
    
    class User extends Entity
    {
    
        protected function _setPassword($password)
        {
            return (new DefaultPasswordHasher)->hash($password);
        }
    

    Now every time the password property is assigned to the user it will be hashed using the DefaultPasswordHasher class.

     

    I hope this will help you.Please feel free to give us your feedback in comments.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: