I got Google SignIn to work properly, but do not know how to only allow users already in my database. I'm trying to allow only users whose Google email is in the Mail
column in the MyTable
table. If user is not in the table, redirect to unauthorized.html
. Right now, if I do not check against the database, login is working OK.
I think I have two concept problems:
1) don't know if the redirect is in data-redirecturi="http://MyPage.php"
or in window.location.replace("http://MyPage.php");
2) I don't know how to redirect to, say, unauthorized.html
if user's email is not in database.
The html:
<div class="WelcomeContainer">
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark" data-redirecturi="http://MyPage.php"></div>
</div>
<script>
function onSignIn(googleUser) {
var id_token = googleUser.getAuthResponse().id_token;
var xhr = new XMLHttpRequest();
xhr.open('POST', 'signin.php');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
window.location.replace("http://MyPage.php");
};
xhr.send('idtoken=' + id_token);
}
</script>
The signin.php:
<?php
session_start();
require_once 'vendor/autoload.php';
$CLIENT_ID = "xxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
$id_token = $_POST['idtoken'];
$client = new Google_Client(['client_id' => $CLIENT_ID]);
$payload = $client->verifyIdToken($id_token);
if ($payload) {
$link = new mysqli('localhost', 'my_user', 'my_password', 'my_db');
$Test=false;
$result = $link->query("SELECT Mail FROM MyTable");
while ($row = $result->fetch_assoc()) {
if ($row['Mail']==$payload['email']) {
$Test=true;
}
}
if ($Test==true) {
//code here for success?
}
else {
//code here for failure?
}
} else {
die();
}
?>