Ethical Hacking Institute Course in Pune-India
Extreme Hacking | Sadik Shaikh | Cyber Suraksha Abhiyan
In this article I am going to show you how to use “login with google” in your website.
Implementing Google Login system in your website is very easy, the Google API Client Library enables us to work with many Google services like Google+, Drive, or YouTube etc. We can also use the library to fetch user details required for registration and login. Today let’s learn how we can use Google API Client Library to make user login and registration system for the website.
Create Database Table
Run SQL query below to create a new MySQL table called “google_users” using phpMyAdmin. As you can see we have 5 columns in the table, all are strings (varchar) except for primary field google_id, that’s because Google user IDs are unique numbers and very long ones (21 characters), so we use decimal for that field.
CREATE TABLE IF NOT EXISTS `google_users` ( `google_id` decimal(21,0) NOT NULL, `google_name` varchar(60) NOT NULL, `google_email` varchar(60) NOT NULL, `google_link` varchar(60) NOT NULL, `google_picture_link` varchar(200) NOT NULL, PRIMARY KEY (`google_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Login and Process Page
Before you begin, you need client id, secret key from Google API, go to Google API console, create an OAuth client for Web Application, next you will be presented with your Client ID and Secret, which will be required in code below.
The process is pretty straight forward, when user clicks Google login link, user is redirected to Google Authentication page, once user grants the basic permission to your application, user is redirected back to your website with Authentication code. The code is than used to obtain Access Token, using Access Token the application can access current user data from Google, which could be used to register and login the user.
########## Google Settings.Client ID, Client Secret from https://console.developers.google.com #############
$client_id = ‘xxxxxxxxxxxxxxxxxx’;
$client_secret = ‘xxxxxxxxxxxxxxxxxxxxxxxxxxxxx’;
$redirect_uri = ‘http://path-to-script/google-login-api/’;
########## MySql details #############
$db_username = “xxxxxxxxx”; //Database Username
$db_password = “xxxxxxxxx”; //Database Password
$host_name = “localhost”; //Mysql Hostname
$db_name = ‘xxxxxxxxx’; //Database Name
###################################################################
$client = new Google_Client();
$client->setClientId($client_id);
$client->setClientSecret($client_secret);
$client->setRedirectUri($redirect_uri);
$client->addScope(“email”);
$client->addScope(“profile”);
$service = new Google_Service_Oauth2($client);
//If $_GET[‘code’] is empty, redirect user to google authentication page for code.
//Code is required to aquire Access Token from google
//Once we have access token, assign token to session variable
//and we can redirect user back to page and login.
if (isset($_GET[‘code’])) {
$client->authenticate($_GET[‘code’]);
$_SESSION[‘access_token’] = $client->getAccessToken();
header(‘Location: ‘ . filter_var($redirect_uri, FILTER_SANITIZE_URL));
exit;
}
//if we have access_token continue, or else get login URL for user
if (isset($_SESSION[‘access_token’]) && $_SESSION[‘access_token’]) {
$client->setAccessToken($_SESSION[‘access_token’]);
} else {
$authUrl = $client->createAuthUrl();
}
/Display user info or display login url as per the info we have.
echo ‘<div style=”margin:20px”>’;
if (isset($authUrl)){
//show login url
echo ‘<div align=”center”>’;
echo ‘<h3>Login with Google — Demo</h3>’;
echo ‘<div>Please click login button to connect to Google.</div>’;
echo ‘<a class=”login” href=”‘ . $authUrl . ‘”><img src=”images/google-login-button.png” /></a>’;
echo ‘</div>’;
} else {
$user = $service->userinfo->get(); //get user info
// connect to database
$mysqli = new mysqli($host_name, $db_username, $db_password, $db_name);
if ($mysqli->connect_error) {
die(‘Error : (‘. $mysqli->connect_errno .‘) ‘. $mysqli->connect_error);
}
//check if user exist in database using COUNT
$result = $mysqli->query(“SELECT COUNT(google_id) as usercount FROM google_users WHERE google_id=$user->id“);
$user_count = $result->fetch_object()->usercount; //will return 0 if user doesn’t exist
//show user picture
echo ‘<img src=”‘.$user->picture.‘” style=”float: right;margin-top: 33px;” />’;
if($user_count) //if user already exist change greeting text to “Welcome Back”
{
echo ‘Welcome back ‘.$user->name.‘! [<a href=”‘.$redirect_uri.‘?logout=1″>Log Out</a>]’;
}
else //else greeting text “Thanks for registering”
{
echo ‘Hi ‘.$user->name.‘, Thanks for Registering! [<a href=”‘.$redirect_uri.‘?logout=1″>Log Out</a>]’;
$statement = $mysqli->prepare(“INSERT INTO google_users (google_id, google_name, google_email, google_link, google_picture_link) VALUES (?,?,?,?,?)”);
$statement->bind_param(‘issss’, $user->id, $user->name, $user->email, $user->link, $user->picture);
$statement->execute();
echo $mysqli->error;
}
//print user details
echo ‘<pre>’;
print_r($user);
echo ‘</pre>’;
}
echo ‘</div>’;
www.extremehacking.org
Cyber Suraksha Abhiyan, CEHv9, CHFI, ECSAv9, CAST, ENSA, CCNA, CCNA SECURITY, MCITP,RHCE,CHECKPOINT, ASA FIREWALL, VMWARE, CLOUD, ANDROID, IPHONE, NETWORKING HARDWARE,TRAINING INSTITUTE IN PUNE, Certified Ethical Hacking, Center For Advanced Security Training in India, ceh v9 course in Pune-India, ceh certification in pune-India, ceh v9 training in Pune-India, Ethical Hacking Course in Pune-India