Skip to main content

enable 2fa 2 step login authentication in cakephp 3


How to use 2fa google authentication  in cakephp 3 and above

What is google authentication or 2 step verification

google authentication or 2 step verification provide security to user account and enable 2 step security on thier account.user need to always insert a unique code generated by their phone app to login in thier account. this will prevent others to access their account even they have users login details.

this tutorial will allow user to enable 2 factor google verfication into their accounts .and after this code user needs to follow these steps
* click on enable 2fa link
* download authi or google authenticator app
* after click on enable 2fa link user able to view a page with a qr code and a key. user need to read qr code or enter key manually into their phone app .
* and get a code from their phone and insert this code into the code field on same page.and if code is right then user 2fa google authentication or 2 step verificaiton will enabled for thier account.

How to use 2fa google authentication in cakephp 3


Step 1
Download this php class from here

now extract it and open pphgangsta folder and copy GoogleAuthenticator.php file


Step 2
to enable google authentication in cakehpp we need to create a pluginNow open your cakeproject
open plugins folder and create a new folder (GoogleAuthenticate)into it.
paste your GoogleAuthenticator.php into this folder.

Step 3

config/bootstrap.php

paste this code into bootstrap.php

require_once dirname(dirname(__FILE__)).'/plugins/GoogleAuthenticate/GoogleAuthenticator.php';

 $gauth = new PHPGangsta_GoogleAuthenticator();


this code will make this class available globally.

Step 4
Now open vendor folder from your root directory and create a new folder with GoogleAuthenticator name. and paste same file GoogleAuthenticator.php into it. and now open this file and add this namespace over class

namespace GoogleAuthenticator;


Step 5

Now open your usersController
and paste this after namespace.
use GoogleAuthenticator\GoogleAuthenticator;

Step 6
add two fileds in your user table in db  2fa_key and  2fa_status
Create a new function into it

public function authi()
{

require_once(ROOT .DS. "vendor" . DS  . "GoogleAuthenticator" . DS . "GoogleAuthenticator.php");

$ga = new GoogleAuthenticator();

    $users = TableRegistry::get('Users');
  
    $user_cur_id =  $this->Auth->user('id');
    $getcomp_user = $users->get($user_cur_id);
     $userstatus =  $getcomp_user['2fa_status'];
     $userkey =  $getcomp_user['2fa_key'];
    if($userstatus=="active" && $userkey!="") {
        $this->redirect(array("controller" => "Users","action" => "index"));
    }
    if($this->request->is('post'))
    {

        $checkconfirm = $this->request->data['checkconfirm'];
        if($checkconfirm ==0)
        {
            $this->Flash->error(__('Please back up your 16-digit key before proceeding.'),array('class' => 'alert alert-danger'));
            $this->redirect(array("controller" => "Users","action" => "authi"));
        }
        $secret = $this->request->data['secretcode'];
        $oneCode = $this->request->data['code'];
      
        $checkResult = $ga->verifyCode($secret, $oneCode, 2);    // 2 = 2*30sec clock tolerance
if ($checkResult) {
  

        $savedata['2fa_key'] =  $this->request->data['secretcode'];
        $savedata['2fa_status'] = "active";

        $curuser = $this->Users->get($user_cur_id);       
        $userupdate = $this->Users->patchEntity($curuser,$savedata);
        if ($this->Users->save($userupdate)) {

            $this->Flash->success(__('Two-Factor Authentication (2FA) Is Enabled.'),array('class' => 'alert alert-danger'));
            $this->redirect(array("controller" => "Users","action" => "index"));
          
            }else {
                $this->Flash->error(__('Please try again.'),array('class' => 'alert alert-danger'));

            }
 
        }else {
            $this->Flash->error(__('Wrong code entered.Please try again.'),array('class' => 'alert alert-danger'));

        }

    }
  }



  Step 7
  Now open template/users
  and create a new file with authi.ctp name and paste this code into it.

  <?php $ga = new PHPGangsta_GoogleAuthenticator();

$secret = $ga->createSecret();

$qrCodeUrl = $ga->getQRCodeGoogleUrl('dc-ex.com', $secret);
?>
<div class="col-sm-12 col-md-12 nopadding">
        <div class="col-sm-2 col-md-2 paddingone"></div>
    <div class="col-sm-8 col-md-8 paddingone">
        <div class="users form">


        <?= $this->Form->create() ?>
           
             <div class="col-md-12 minheight nopadding">
       
            <div class="content-wrap ">
            <div class="content-box-large">
            <div class="col-md-12">
                <?= $this->Flash->render('auth') ?>
                <?= $this->Flash->render() ?>
            </div>              
                           
            <div class="col-md-12">
                <div class="col-sm-6">
                     <legend>Two Factor Authentication</legend>

                     <div class="form-group">
                            <?= $this->Form->input('code', array('type' => 'text','class' => 'form-control','label' => 'Code','required'=>true)); ?>
                      
                         <?= $this->Form->input('secretcode', array('type' => 'hidden','class' => 'form-control','value' => $secret)); ?>


                        </div>
                           

                     <div class="col-sm-12 paddingleftnone">
                            <div class="col-sm-1 paddingleftnone paddingrightnone">
                                <?= $this->Form->input('checkconfirm', ['type' => 'checkbox','class' => 'form-control','value'=>'1','required'=>true,'label'=>'']); ?>
                            </div>
                            <div class="col-sm-11 aligncenter">I have backed up my 16-digit key.</a>  </div>   
                     </div> 
               
                  <?= $this->Form->button('Enable 2FA', array('div' => false,'class' => 'btn btn-primary signup', 'title' => 'Enable 2FA')); ?>



                </div>
                <div class="col-sm-1"></div>
                <div class="col-sm-5">
                    <div class="col-sm-12">
                            <label><?php echo "Secret Key is: ".$secret."\n\n"; ?></label>
                        </div>
                        <div class="col-sm-12">
                            <img src="<?php  echo $qrCodeUrl; ?>" name="qr" />
                        </div>

                </div> 
            </div>
                 <div class="clearboth"></div>            
 
                               
            </div>
                  </div>
                   
                    </div>
  <?= $this->Form->end() ?>
                 </div>
     </div>
</div>





Now You can call authi controller by linking it with anchor link like
<?php echo $this->Html->link('Active 2FA', ['controller'=>'Users', 'action'=>'authi','_full'=>true],['escape' => false]);
 ?>

 Now user able to enable google authenticator 2fa security in account and you can check it on login that if user enable the 2fa security then you apply 2 step authentication.
 to how to enable 2fa security or 2 step authentication in user login in cakephp 3.x then you need to click here for 2 part of  How to use 2fa google authentication in cakephp 3 or how to enable 2 step login authentication in cakephp 3

 Part 2 How to enable 2fa 2 step google authentication in cakephp 3.x

Comments

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