Google Two Factor Authentication Using PHP, Ajax, MySQL

Google Two Factor Authentication Using PHP, Ajax, MySQL

Two-Factor Verification Using Google Authenticator

Here is an additional element that can be added to login framework for an additional layer of security. It is 2 figure verification utilizing Google Authenticator App for Android/iPhone. Your record could be in danger of having your watchword stolen. 2 stage check can shield from abuse of your record on the off chance that somebody have your secret key, since signing into your record dependably require a security code(this confirmation code is interestingly intended for your record, in the event that you decide on confirmation code, a one of a kind code is sent to your portable for each 30-60 seconds) in the second step after you enter your watchword.

Live Demo   Download Source Code

Users Table

CREATE TABLE IF NOT EXISTS `tbl_users` (
  `user_id` int(11) NOT NULL primary key AUTO_INCREMENT,
  `email` varchar(120) DEFAULT NULL,
  `password` varchar(200) DEFAULT NULL,
  `profile_name` varchar(100) DEFAULT NULL,
  `profile_image` varchar(200) DEFAULT NULL,
  `google_auth_code` varchar(16) DEFAULT NULL,
  `created_at` varchar(15) DEFAULT NULL,
  `updated_at` varchar(15) DEFAULT NULL
)

connection.php

<?php
session_start();
$conn = mysql_connect("localhost","","") or die(mysql_error());
$DB = mysql_select_db("test",$conn) or die(mysql_error());
date_default_timezone_set('Asia/Kolkata');
?>

index.php

<!DOCTYPE html>
<html>
<head>
    <title>2-Step Verification using Google Authenticator</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

    <link rel="stylesheet" type="text/css" href="css/app_style.css" charset="utf-8" />
</head>
<body>
<div class="container">
    <h1>2-Step Verification using Google Authenticator</h1>
	
	<div class="row">
		<div class="col-md-offset-1 col-md-4">
			<h3>Registration</h3>
			<form name="signup-form" id="signup-form">
			<input type="hidden" id="process_name" name="process_name" value="user_registor" />
			  <div class="errorMsg errorMsgReg"></div>
			  <div class="form-group">
				<label for="email">Full Name:</label>
				<input type="text" name="reg_name" class="form-control" id="reg_name" required />
			  </div>
			  <div class="form-group">
				<label for="email">Email:</label>
				<input type="email" name="reg_email" class="form-control" id="reg_email" required />
			  </div>
			  <div class="form-group">
				<label for="password">Password:</label>
				<input type="password" name="reg_password" class="form-control" id="reg_password" required />
			  </div>
			  
			  <button type="button" class="btn btn-primary btn-reg-submit">Submit</button>
			</form>

		</div>

		<div class="col-md-offset-1 col-md-4">
			<h3>Login</h3>
			<form name="login-form" id="login-form">
			<input type="hidden" id="process_name" name="process_name" value="user_login" />
			  <div class="errorMsg errorMsgReg"></div>
			  <div class="form-group">
				<label for="login_email">Email:</label>
				<input type="email" name="login_email" class="form-control" id="login_email" required />
			  </div>
			  <div class="form-group">
				<label for="login_password">Password:</label>
				<input type="password" name="login_password" class="form-control" id="login_password" required />
			  </div>
			  
			  <button type="button" class="btn btn-success btn-login-submit">Login</button>
			</form>
			
		</div>
	</div>
</div>

<script src="js/jquery.validate.min.js"></script>

<script>
	$(document).ready(function(){
		/* submit form details */
		$(document).on('click', '.btn-reg-submit', function(ev){
			if($("#signup-form").valid() == true){
				var data = $("#signup-form").serialize();
				$.post('check_user.php', data, function(data,status){
					console.log("submitnig result ====> Data: " + data + "\nStatus: " + status);
					if( data == "done"){
						window.location = 'user_confirm.php';
					}
					else{
						alert("not done");
					}
					
				});
			}
		});
		/* ebd submit form details */
		
		/* submit form details */
		$(document).on('click', '.btn-login-submit', function(ev){
			if($("#login-form").valid() == true){
				var data = $("#login-form").serialize();
				$.post('check_user.php', data, function(data,status){
					console.log("submitnig result ====> Data: " + data + "\nStatus: " + status);
					if( data == "done"){
						window.location = 'user_confirm.php';
					}
					else{
						alert("not done");
					}
					
				});
			}
		});
		/* ebd submit form details */
	});
</script>

</body>
</html>

check_user.php

<?php
include("connection.php");

require_once 'googleLib/GoogleAuthenticator.php';
$gauth = new GoogleAuthenticator();
$secret_key = $gauth->createSecret();

$process_name = $_POST['process_name'];



if($process_name == "user_registor"){
	$reg_name		= $_POST['reg_name'];
	$reg_email		= $_POST['reg_email'];
	$reg_password	= md5($_POST['reg_password']);
    
	$chk_user = mysql_query("select * from tbl_users where email='$reg_email'") or die(mysql_error());
	if(mysql_num_rows($chk_user) == 0){
    	$query = "insert into tbl_users(profile_name, email, password, google_auth_code) values('$reg_name', '$reg_email', '$reg_password', '$secret_key' )";
		$result = mysql_query($query) or die(mysql_error());
		$_SESSION['user_id'] = mysql_insert_id();
		echo "done";
    }
    else{
		echo "This Email already exits in system.";
    }
}

if($process_name == "user_login"){
	$login_email		= $_POST['login_email'];
	$login_password		= md5($_POST['login_password']);
    
	$user_result = mysql_query("select * from tbl_users where email='$login_email' and password='$login_password'") or die(mysql_error());
	if(mysql_num_rows($user_result) == 1){
    	$user_row = mysql_fetch_array($user_result);
		$_SESSION['user_id'] = $user_row['user_id'];
		echo "done";
    }
    else{
		echo "Check your user login details.";
    }
}

if($process_name == "verify_code"){
	$scan_code = $_POST['scan_code'];
	$user_id = $_SESSION['user_id'];
	
	$user_result = mysql_query("select * from tbl_users where user_id='$user_id'") or die(mysql_error());
	$user_row = mysql_fetch_array($user_result);
	$secret_key	= $user_row['google_auth_code'];
	
	$checkResult = $gauth->verifyCode($secret_key, $scan_code, 2);    // 2 = 2*30sec clock tolerance

	if ($checkResult){
		$_SESSION['googleVerifyCode'] = $scan_code;
		echo "done";
	} 
	else{
		echo 'Note : Code not matched.';
	}
}
?>

user_confirm.php

<?php
include('connection.php');
require_once 'googleLib/GoogleAuthenticator.php';
$gauth = new GoogleAuthenticator();

if(empty($_SESSION['user_id']))
{
	echo "<script> window.location = 'index.php'; </script>";
}

$user_id = $_SESSION['user_id'];
$user_result = mysql_query("select * from tbl_users where user_id='$user_id'") or die(mysql_error());
$user_row = mysql_fetch_array($user_result);

$secret_key	= $user_row['google_auth_code'];
$email		= $user_row['email'];

$google_QR_Code = $gauth->getQRCodeGoogleUrl($email, $secret_key,'Lisenme');
?>
<!DOCTYPE html>
<html>
	<head>
		<title>2-Step Verification using Google Authenticator</title>
		<link rel="stylesheet" type="text/css" href="css/app_style.css" charset="utf-8" />
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	</head>
	<body>
		<div id="container">
			<h1>2-Step Verification using Google Authenticator</h1>
			<div id='device'>

			<p>Scan with Google Authenticator application on your smart phone.</p>
			<div id="img"><img src='<?php echo $google_QR_Code; ?>' /></div>

			<form id="LI-form">
			<input type="hidden" id="process_name" name="process_name" value="verify_code" />
				<div class="form-group">
					<label for="email">Place your code here:</label>
					<input type="text" name="scan_code" class="form-control" id="scan_code" required />
				  </div>
				  
				<input type="button" class="btn btn-success btn-submit" value="Verify Code"/>
			</form>
			</div>
			<div style="text-align:center">
				<h6>Download Google Authenticator <br/> application using this link(s),</h6>
			<a href="https://itunes.apple.com/us/app/google-authenticator/id388497605?mt=8" target="_blank"><img class='app' src="images/iphone.png" /></a>

			<a href="https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2&hl=en" target="_blank"><img class="app" src="images/android.png" /></a>
			</div>
		</div>
		
	<script src="js/jquery.validate.min.js"></script>

	<script>
		$(document).ready(function(){
			/* submit form details */
			$(document).on('click', '.btn-submit', function(ev){
				if($("#LI-form").valid() == true){
					var data = $("#LI-form").serialize();
					$.post('check_user.php', data, function(data,status){
						console.log("submitnig result ====> Data: " + data + "\nStatus: " + status);
						if( data == "done"){
							window.location = 'my_page.php';
						}
						else{
							alert("not done");
						}
						
					});
				}
			});
			/* ebd submit form details */
		});
	</script>
	</body>
</html>

my_page.php

<?php
include("connection.php");
if(empty($_SESSION['user_id']))
{
	echo "<script> window.location = 'index.php'; </script>";
}

$user_id = $_SESSION['user_id'];
$user_result = mysql_query("select * from tbl_users where user_id='$user_id'") or die(mysql_error());
$user_row = mysql_fetch_array($user_result);
?>
<!DOCTYPE html>
<html>
	<head>
		<title>2-Step Verification using Google Authenticator</title>
		
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
		<link rel="stylesheet" type="text/css" href="css/app_style.css" charset="utf-8" />
	</head>
	<body>
		<div id="container">
			<h1>Hi <?php echo ucfirst($user_row['profile_name']); ?>,</h1>
			
			<table class="user-table">
				<tr><td colspan="3" align="center" class="title">User Profile Details:</td></tr>
				<tr><th>Profile Name</th><td><?php echo $user_row['profile_name']; ?></td></tr>
				<tr><th>Email</th><td><?php echo $user_row['email']; ?></td></tr>
				<tr><th>Secret Key</th><td><?php echo $user_row['google_auth_code']; ?></td></tr>
				<tr><td colspan="3" align="center"><a href="logout.php" class="btn btn-xs btn-danger" >Logout</a></td></tr>
			</table>
			<h4></h4>
		</div>
	</body>
</html>

 

 

You May Also Like

About the Author: Ranjith Kumar A

0 0 votes
Article Rating
Subscribe
Notify of
guest
4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Akshit
Akshit
3 years ago

It getting too much errors on check_user.php new php get rid of mysql and all new browser doesn’t support mysql now.

Sunday
Sunday
3 years ago

Hello Admin,

pls the confirmation page keep return not done even those the right code is input

Thanks

shahzaib rehman
shahzaib rehman
1 year ago

i cant register why

4
0
Would love your thoughts, please comment.x
()
x