from google.oauth2 import id_token from google.auth.transport import requests import pickle import os.path from googleapiclient.discovery import build from http.server import HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler import socketserver import logging import json # some_file.py import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '../calenderwatch_server/') 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') if checkClientId(self.data_string): getApiAuth(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}") return True except ValueError: # ID token is invalid print('invalid token') return False def getApiAuth(token): 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) # creds = pickle.load(idinfo) service = build('calendar', 'v3', credentials=idinfo) if __name__ == '__main__': from sys import argv if len(argv) == 2: run(port=int(argv[1])) else: run()