Skip to main content

login and registration with Cakephp 3 tutorial

Create login and registration with Cakephp 3


first you need to install cakephp 3 on your localhost or sever .for installation guide read this post Install Cakephp 3+ without composer on localhost





Step 1

  open your appController.php (Location :- C://xampp/htdocs/yourproject/src/Controller)
  and paste this code into initialize function.

public function initialize()
    {

        $this->set('pageMainHeading', 'Admin');
        $this->set('title_for_layout','Admin');
        $this->viewBuilder()->layout('default');
        $this->loadComponent('Flash');

        $this->loadComponent('Auth', [
            'loginRedirect' => [
                'controller' => 'AdminUsers',
                'action' => 'index'
            ],
            'logoutRedirect' => [
                'controller' => 'Pages',
                'action' => 'display',
                'home'
            ],
            'loginAction' => [
            'controller' => 'AdminUsers',
            'action' => 'login',
           
        ],
        ]);
    
    }


Step 2
now we create our login controller .create a new file  AdminUsersController.php
and create login registration fuinction into it ...or paste this code.

<?php
/**
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link      http://cakephp.org CakePHP(tm) Project
 * @since     0.2.9
 * @license   http://www.opensource.org/licenses/mit-license.php MIT License
 */
namespace App\Controller;
use App\Controller\AppController;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\Error\Debugger;
use Cake\Event\Event;
use Cake\ORM\Query;
use Cake\ORM\Table;
use App\Model\Entity\Role;
use Cake\ORM\TableRegistry;
//use Cake\Auth\DefaultPasswordHasher;
/**
 * Static content controller
 *
 * This controller will render views from Template/Pages/
 *
 * @link http://book.cakephp.org/3.0/en/controllers/pages-controller.html
 */
class AdminUsersController extends AppController
{

public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->Auth->allow('add', 'logout');
    }

     public function index()
     {
       
     if (isset($this->request->data['submitthis']) && $this->request->data['searchTerm']!="") {
     $usertable = TableRegistry::get('AdminUsers');

     $query = $usertable->find('all')
                ->where(['username LIKE' => "%".$this->request->data['searchTerm']."%"])
                ->orWhere(['email LIKE' => "%".$this->request->data['searchTerm']."%"])
                ->autoFields(true)
                ->select(['Roles.rolename'])
                  ->join([
                            'Groups' => [
                                'table' => 'roles',
                                'type' => 'LEFT',
                    'alias' => 'Roles',
                                'conditions' => 'Roles.id = AdminUsers.role'
                            ]
                        ])
                  ->toArray();
        $this->set('searchtxt', $this->request->data['searchTerm']);

    }else {
       $query = $this->AdminUsers->find('all')  
       ->autoFields(true)
       ->select(['Roles.rolename'])
      ->join([
                'Groups' => [
                    'table' => 'roles',
                    'type' => 'LEFT',
        'alias' => 'Roles',
                    'conditions' => 'Roles.id = AdminUsers.role'
                ]
            ])
      ->toArray();
       }

       $this->set('aRows',$query);

    }

    public function view($id)
    {
       // $user = $this->Users->get($id);
        //$this->set(compact('user'));
    }

    public function edit($id = 0)
    {
        if($id == 0)
        {
            return $this->redirect(array('action' => 'index'));
        } else {

            $usertable = TableRegistry::get('AdminUsers');
            $userdata = $usertable->get($id);
            $role =array("1"=>'admin',"2"=>'Super Admin');

            $user = $this->AdminUsers->get($id);
            if ($this->request->is(['post', 'put'])) {
              $this->AdminUsers->patchEntity($user, $this->request->data);
              if ($this->AdminUsers->save($user)) {
                $this->Flash->success(__('Your account has been edited'));
                return $this->redirect(['controller' => 'AdminUsers', 'action' => 'edit']);
              }
              $this->Flash->error(__('Your account could not be edited. Please fix errors below.'));
            }
            $this->set('roles', $role);
            $this->set(compact('user'));
            $aRow = $this->request->data = $user;
            $this->set('aRow', $aRow);
        }

    }


    public function add()
    {

        $aRow= array();
        $role =array("1"=>'admin',"2"=>'Super Admin');
        $user = $this->AdminUsers->newEntity();
        if ($this->request->is('post')) {
          
            $user = $this->AdminUsers->patchEntity($user, $this->request->data);
            if ($this->AdminUsers->save($user)) {
                $this->Flash->success(__('The user has been saved.'));
                return $this->redirect(['action' => 'add']);
            }
            $this->Flash->error(__('Unable to add the user.'));
        }
        $this->set('user', $user);
        $this->set('roles', $role);
        $this->set('aRow', $aRow);
    }
   
    public function delete($id = 0) {
        if($id == 0)
        {
            return $this->redirect(array('action' => 'index'));
        }
        $entity = $this->AdminUsers->get($id);
        if ($this->AdminUsers->delete($entity))
        {
            $this->Flash->error(__('Admin deleted successfully.'),'default',array('class' => 'alert alert-success'));
            $this->redirect(array('action' => 'index'));
        }
    }

    public function login()
    {
        if ($this->Auth->user()) {

            $this->redirect(array("controller" => "AdminUsers","action" => "add"));

        }

         $this->viewBuilder()->layout('login');
        if ($this->request->is('post')) {
            $user = $this->Auth->identify();
            if ($user) {
                $this->Auth->setUser($user);
                return $this->redirect($this->Auth->redirectUrl());
            }
            $this->Flash->error(__('Invalid username or password, try again'),array('class' => 'alert alert-danger'));
         }
    }

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


    public function changepassword($id = 0) {
        if($id == 0)
        {
            return $this->redirect(array('action' => 'index'));
        }
     
        $usertable = TableRegistry::get('AdminUsers');
        $userdata = $usertable->get($id);
        $user = $this->AdminUsers->get($id);
        //$aUser = $this->User->find('first', array('conditions' => $aCon));
         if ($this->request->is('post')) {
           
            $aVals = $this->AdminUsers->patchEntity($user, $this->request->data);

             $user = $this->AdminUsers->patchEntity($user, [
                    'password' => $this->request->data['new_password'],
                    ]
            );

            if($aVals['new_password'] == $aVals['confirm_password'])
            {              
                $password = $aVals['new_password'];
               if ($usertable->save($user)) {
                 $this->Flash->success(__('Password change successfully'),'default',array('class' => 'alert alert-success'));
                return $this->redirect(array('action' => 'changepassword'));
                }
            }
            else
            {
                 $this->Flash->error(__('Both password must be same.'),'default',array('class' => 'alert alert-danger'));
                return $this->redirect(array('action' => 'changepassword'));
            }          
        }
       
        $this->set('pageMainHeading', 'Change Password');
        $this->set('title_for_layout','Change Password');
       
    }
   
   
   
    public function status($id = 0,$active,$action) {
        if($id == 0)
        {
            return $this->redirect(array('action' => $action));
        }  
        $users = TableRegistry::get('AdminUsers');
        $query = $users->query(); 
        $query->update()
        ->set(['status' => $active])
        ->where(['id' => $id])
        ->execute();
       
        if($active)
        {   
        $msg = 'Admin successfully activated';
        } else {
        $msg = 'Admin successfully deactivated';
        }
        $this->Flash->success(__($msg),'default',array('class' => 'alert alert-success'));
        return $this->redirect(array('action' => $action));
    }

 


}


Step 2--
Now we create a model for our controller
create a new file AdminUsersTable.php (Location :- C://xampp/htdocs/yourproject/src/Model/Table)

<?php
// Path File: \App\src\Model\Table\UsuariosTable.php
namespace App\Model\Table;



use App\Model\Entity\AdminUser;
use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Event\Event;

/**
 * AdminUser Model
 *
 * @property \Cake\ORM\Association\BelongsTo $Perfiles
 */
class AdminUsersTable extends Table
{

    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config)
    {
        parent::initialize($config);
        $this->primaryKey('id');

   }  


    public function validationDefault(Validator $validator)
    {
        return $validator;
           
           
    }

    /**
     * Returns a rules checker object that will be used for validating
     * application integrity.
     *
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
 
   public function buildRules(RulesChecker $rules)
    {
        $rules->add($rules->isUnique(['email']));
        $rules->add($rules->isUnique(['username']));
        //$rules->add($rules->existsIn(['perfiles_id'], 'Perfiles'));
        return $rules;
    }

    }

}



Step 3
to convert password into hash we create an entity AdminUser.php (Location :- C://xampp/htdocs/yourproject/src/Model/Entity/AdminUser.php)

<?php
// src/Model/Entity/User.php
namespace App\Model\Entity;

use Cake\Auth\DefaultPasswordHasher;
use Cake\ORM\Entity;

class AdminUser extends Entity
{

    // Make all fields mass assignable except for primary key field "id".
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];

    // ...

    protected function _setPassword($password)
    {
        return (new DefaultPasswordHasher)->hash($password);
    }



    // ...
}

?>




Step 4 Now create views for our controller
Navigate to c://xampp/htdocs/yourproject/src/template/
create a new folder with AdminUsers name

then create these files into it









 login.ctp

<div class="wrapper">
        <div class="container">
            <div class="row">
                <div class="module module-login span4 offset4">
                   
                   
                    <?= $this->Form->create() ?>
                        <div class="module-head">
                            <h3>Sign In</h3>
                           
                        </div>
                        <div class="module-body">

                            <?= $this->Flash->render('auth') ?>
                             <?= $this->Flash->render() ?>
                            <div class="control-group">
                                <div class="controls row-fluid">
                                    <?php echo $this->Form->input('username', array('type' => 'text','class' => 'form-control fullwidth span12 placeholder-no-fix','required' => true,'label' => 'Email','placeholder' => 'Email'));
?>
                                </div>
                            </div>
                            <div class="control-group">
                                <div class="controls row-fluid">
                                    <?php
echo $this->Form->input('password', array('type' => 'password','class' => 'form-control fullwidth span12 placeholder-no-fix','required' => true,'label' => 'Password','placeholder' => 'Password'));
 ?>
                                </div>
                            </div>
                        </div>
                        <div class="module-foot">
                            <div class="control-group">
                                <div class="controls clearfix">
                                    <button type="submit" class="btn btn-success green pull-right">Login</button>
                                   
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div><!--/.wrapper-->



add.ctp
<!-- src/Template/Users/add.ctp -->

<div class="users form">
<?= $this->Form->create($user) ?>
<?php
if($aRow){   
    echo $this->Form->input('id', array('type' => 'hidden','value' => $aRow['id']));
}

?>
    <fieldset>
        <legend><?= __('Add User') ?></legend>
        <?= $this->Form->input('username', array('type' => 'text','class' => 'form-control','required' => true,'label' => 'Username')); ?>
        <?= $this->Form->input('email', array('type' => 'text','class' => 'form-control','required' => true,'label' => 'Email')); ?>
        <?= $this->Form->input('password', array('type' => 'text','class' => 'form-control','required' => true,'label' => 'Password')); ?>
        <?php echo $this->Form->input('role', array('class' => 'form-control','required' => true,'empty' => 'Select Role', 'options' => $roles, 'label' => 'Select Role' ,
 'selected' => $aRow ? $aRow['Exchange']['api'] : '' )); ?>
     
    
   </fieldset>
<?= $this->Form->submit('Submit', array('div' => false,'class' => 'btn btn-success', 'title' => 'Add User')); ?>
   
<?= $this->Form->end() ?>
</div>




Now Create index.php
<div class="portlet-title">

</div>

<div class="clearfix">&nbsp;</div>
    <div class="col-md-12 col-sm-12">
    <div class="col-md-6 col-sm-6">
         </div>
             <div class="col-md-6 col-sm-6"><div id="sample_4_filter" class="dataTables_filter">
                 <?= $this->Form->create('Model') ?>
                
                 <div class="floatright">
                     <button type="submit" name="submitthis" class="btn btn-default bgclrblue"><i class="fa fa-search"></i></button>
                 </div>
                 <div class="floatright">
                 <input type="text" class="form-control fullwidth input-sm input-small input-inline" name="searchTerm" placeholder="Search" value="<?php echo isset($searchtxt)?$searchtxt:""; ?>">
                </div>
             </div></div></div>
   
<div class="clearfix">&nbsp;</div>
<?php if($aRows) {  ?>
<table class="table table-striped table-bordered table-hover table-checkable order-column" id="sample_4">
<thead>
<tr>
<th>Sr</th>
<th> Username </th>
<th> Email </th>
<th> Role </th>
<th> Status </th>
<th>Action</th>
</tr>
</thead>
<tbody>

<?php foreach($aRows as $aKey => $aRow){ ?>
<tr class="odd gradeX">
<td><?php echo $aKey+1; ?> </td>
<td><?php echo $aRow['username']; ?></td>
<td><?php echo $aRow['email']; ?></td>
<td>
<?php echo $aRow['Roles']['rolename']; ?>
</td>

<td><?php echo $aRow['status']==1 ? 'Active' : 'Inactive'; ?></td>
<td>
 <?php
 if($aRow['status']==1) {
  echo $this->Html->link('<i class="fa fa-times-circle clrred"></i>',['controller'=>'AdminUsers', 'action'=>'status','_full'=>true,$aRow['id'],0,'index'],['escape' => false]);
  } else {
  echo $this->Html->link('<i class="fa fa-check-circle clrgreen"></i>',['controller'=>'AdminUsers', 'action'=>'status','_full'=>true,$aRow['id'],1,'index'],['escape' => false]);
  }
 ?>
  <?php echo $this->Html->link('<i class="fa fa-edit clrblue"></i>',['controller'=>'AdminUsers', 'action'=>'edit','_full'=>true,$aRow['id']],['escape' => false]);
 ?>

  <a title="delete" href="<?php echo $this->Url->build(array('controller' => 'AdminUsers', 'action' => 'delete', $aRow['id'])); ?>"  onclick="return confirm('Are you sure to delete this item ??');"><i class="fa fa-trash clrred"></i></a>

<?php echo $this->Html->link('<i class="fa fa-key clrgreen"></i>',['controller'=>'AdminUsers', 'action'=>'changepassword','_full'=>true,$aRow['id']],['escape' => false]);
 ?>
</td>
</tr>
<?php } ?>

</tbody>
</table>

<?php } else { ?>

Nothing Found !!!

<?php } ?>



Now go to your browser and navigate to http://localhost/yourproject/admin-users/login


Create login registration with cakephp 3 tutorial

Comments

Post a Comment

Popular posts from this blog

Run and compile sass scss file to css using node

  Today we learn how to use scss and generate css using node  or Run and compile sass scss file to css using node   So please follow simple  steps :-   Today we will create a project that can read scss file and generates css with it  Note: Make sure you have installed node in your system. If you want to help to install node js based on your system then check our other tutorial or check node js official website. Now create a blank folder and open  terminal(linux) or cmd(windows) and navigate to your current project folder by using cd command Now run below command npm init after enter it will ask you some package info that you can fill according to you or just keep enter until it finished. The above command will generate package.json file Now  we will install npm module that will convert our scss to css Run below command: npm install node-sass So we have installed node-sass package . Now open package.json file in your editor and add below code into it into

How to retrieve Facebook Likes, share , comment Counts

function facebook_count($url){     // Query in FQL     $fql  = "SELECT share_count, like_count, comment_count ";     $fql .= " FROM link_stat WHERE url = '$url'";     $fqlURL = "https://api.facebook.com/method/fql.query?format=json&query=" . urlencode($fql);     // Facebook Response is in JSON     $response = file_get_contents($fqlURL);     return json_decode($response); } $fb = facebook_count('https://www.facebook.com/BahutHoGyiPadhai'); // facebook share count echo $fb[0]->share_count;  echo "like"; // facebook like count echo $fb[0]->like_count ; echo "comment"; // facebook comment count echo $fb[0]->comment_count;  ?>

jQuery Datatable add date range filter

jQuery Datatable add date range filter Datatable is most useful jQuery plugin that helps to make our html tables more powerful and give powers to user to filter , search, sort, pagination etc, But Data table provides a common filter only and yes we can customize and add filter for each column, but still sometimes we need an advance filter like show results only between a date range, So today we will learn how to create a minimum and maximum date range fields and show date picker on it, and user can fill dates by selecting dates and data table will auto filter records based on it. Keep follow below steps :- I am using Bootstrap if you want to use any other framework then you can use. Create a new index.php file  and paste below code in it, i have used all required CDN like bootstrap, datatable, datepicker etc. <!DOCTYPE html> <html> <head>     <title>Datatable Date Range Filter Example</title>     <link rel="stylesheet" href="https://maxcd