Php 如果在Google OAuth之后未授权,则重定向到特定页面

Php 如果在Google OAuth之后未授权,则重定向到特定页面,php,google-oauth,Php,Google Oauth,我让谷歌登录正常工作,但不知道如何只允许我的数据库中已有的用户。我试图只允许那些谷歌电子邮件位于MyTable表的Mail列中的用户使用。如果用户不在表中,请重定向到unauthorized.html。现在,如果我不检查数据库,登录工作正常 我想我有两个概念问题: 1) 不知道重定向是否在数据重定向URI=”中http://MyPage.php“或在窗口中。位置。替换(”http://MyPage.php"); 2) 如果用户的电子邮件不在数据库中,我不知道如何重定向到,比如,unauthori

我让谷歌登录正常工作,但不知道如何只允许我的数据库中已有的用户。我试图只允许那些谷歌电子邮件位于
MyTable
表的
Mail
列中的用户使用。如果用户不在表中,请重定向到
unauthorized.html
。现在,如果我不检查数据库,登录工作正常

我想我有两个概念问题:

1) 不知道重定向是否在
数据重定向URI=”中http://MyPage.php“
或在
窗口中。位置。替换(”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>

函数onSignIn(谷歌用户){
var id_token=googleUser.getAuthResponse().id_token;
var xhr=new XMLHttpRequest();
open('POST','sign.php');
setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onload=函数(){
window.location.replace(“http://MyPage.php");
};
send('idtoken='+id_token);
}
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();
}
?>

以下代码似乎有效

在html中,我替换以下内容:

xhr.onload = function() {
    window.location.replace("http://MyPage.php");
};
为此:

xhr.onload = function() {
    if (xhr.readyState == 4 && xhr.status==200) {
        window.location.replace(xhr.responseText);
    }
};
在signin.php中

if ($Test==true) {
  echo "http://www.example.com/TheGoodPage.html";
}
else {
  echo "http://www.example.com/TheUnAuthorizedPage.html";
}    

很抱歉,我错过了XHR部分,所以我删除了我的答案。您将需要返回一个错误
未经授权
,并让您的代码在客户端运行以处理该错误。请看一看,然后回答:谢谢!你的指导方针帮助我解决了这个问题(尽管我不知道这个解决方案是否优雅)。我将在几分钟内发布代码。我看到的唯一直接问题是返回url<代码>http://TheUnAuthorizedPage.html
不起作用。使用完整的URL。另外,如果您计划支持HTTPS,那么现在就在code.Edited中处理它。再次感谢!