【发布时间】:2019-06-09 23:47:20
【问题描述】:
我让 Google 登录正常工作,但不知道如何只允许我的数据库中已有的用户。我试图只允许其 Google 电子邮件位于 MyTable 表的 Mail 列中的用户。如果用户不在表中,则重定向到unauthorized.html。现在,如果我不检查数据库,登录工作正常。
我认为我有两个概念问题:
1) 不知道重定向是在data-redirecturi="http://MyPage.php" 还是window.location.replace("http://MyPage.php");
2) 如果用户的电子邮件不在数据库中,我不知道如何重定向到 unauthorized.html。
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>
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();
}
?>
【问题讨论】:
-
对不起,我错过了 XHR 部分,所以我删除了我的答案。您将需要返回错误
unauthorized并让您的代码在客户端运行以处理错误。 -
看看这个 SO 答案:stackoverflow.com/a/8866912/8016720
-
谢谢!您的指导方针帮助我解决了这个问题(尽管我不知道解决方案是否优雅)。我将在几分钟内发布代码。
标签: php google-oauth