- basic login button on website frontend
- index.html hosting using python
- posting google oauth token from javascript on client side
- passing token id to python hoster
- verifying token, and returning a string to client
This commit is contained in:
Raphael Maenle 2020-03-26 09:43:10 +00:00
parent a80fc3fa72
commit b676ee1a71
4 changed files with 140 additions and 0 deletions

1
client_secret.json Normal file
View File

@ -0,0 +1 @@
{"web":{"client_id":"377787187748-shuvi4iq5bi4gdet6q3ioataimobs4lh.apps.googleusercontent.com","project_id":"calendarwatch-1584185874753","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"Hu_YWmKsVKUcLwyeINYzdKfZ","redirect_uris":["http://localhost:1234"],"javascript_origins":["http://raphael.maenle.net","https://raphael.maenle.net"]}}

51
index.html Normal file
View File

@ -0,0 +1,51 @@
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<html lang="en" itemscope itemtype="http://schema.org/Article">
<head>
<!-- BEGIN Pre-requisites -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js">
</script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer>
</script>
<!-- END Pre-requisites -->
<meta name="google-signin-scope" content="profile email">
<meta name="google-signin-client_id"
content="377787187748-shuvi4iq5bi4gdet6q3ioataimobs4lh.apps.googleusercontent.com">
<script src="https://apis.google.com/js/platform.js" async defer></script>
</head>
<body>
<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>
<script>
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
// Send the code to the server
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://192.168.68.103.xip.io:1234/website.py');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function() {
console.log('Signed in as: ' + xhr.responseText);
};
xhr.send(id_token);
}
</script>
</body>
</html>

8
index.js Normal file
View File

@ -0,0 +1,8 @@
const express = require('express')
const path = require('path')
const PORT = process.env.PORT || 1234
express()
.use(express.static(path.join(__dirname,'public')))
.get('/', (req, res) => res.render('index'))
.listen(PORT, () => console.log(`Listening on ${ PORT }`))

80
website.py Normal file
View File

@ -0,0 +1,80 @@
from google.oauth2 import id_token
from google.auth.transport import requests
from http.server import HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler
import socketserver
import logging
import json
Handler = SimpleHTTPRequestHandler
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_headers()
f = open("index.html", "r")
self.wfile.write(f.read().encode('utf-8'))
def do_HEAD(self):
self._set_headers()
def do_POST(self):
self._set_headers()
print("in post method")
self.data_string = self.rfile.read(int(self.headers['Content-Length']))
print('checking client id')
checkClientId(self.data_string)
self.send_response(200)
self.end_headers()
self.wfile.write("Hello".encode('utf-8'))
return
def run(server_class=HTTPServer, handler_class=S, port=1234):
logging.basicConfig(level=logging.INFO)
server_address = ('', port)
with socketserver.TCPServer(("", port), handler_class) as httpd:
print("serving at port", port)
httpd.serve_forever()
# (Receive token by HTTPS POST)
def checkClientId(token):
try:
with open('client_secret.json', 'r') as json_file:
clientSecret = json.load(json_file)
CLIENT_ID = clientSecret["web"]["client_id"]
# Specify the CLIENT_ID of the app that accesses the backend:
idinfo = id_token.verify_oauth2_token(token, requests.Request(), CLIENT_ID)
# Or, if multiple clients access the backend server:
# idinfo = id_token.verify_oauth2_token(token, requests.Request())
# if idinfo['aud'] not in [CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]:
# raise ValueError('Could not verify audience.')
if idinfo['iss'] not in ['accounts.google.com', 'https://accounts.google.com']:
raise ValueError('Wrong issuer.')
# If auth request is from a G Suite domain:
# if idinfo['hd'] != GSUITE_DOMAIN_NAME:
# raise ValueError('Wrong hosted domain.')
# ID token is valid. Get the user's Google Account ID from the decoded token.
userid = idinfo['sub']
print(f"valid user id: {userid}")
except ValueError:
# ID token is invalid
print('invalid token')
pass
if __name__ == '__main__':
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()