61 lines
1.9 KiB
Python
61 lines
1.9 KiB
Python
from __future__ import annotations
|
|
import json
|
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
from urllib.parse import urlparse, parse_qs
|
|
from .oauth import start, callback
|
|
|
|
HOST = '127.0.0.1'
|
|
PORT = 8787
|
|
|
|
|
|
def _json(handler: BaseHTTPRequestHandler, code: int, payload: dict):
|
|
raw = json.dumps(payload).encode()
|
|
handler.send_response(code)
|
|
handler.send_header('Content-Type', 'application/json')
|
|
handler.send_header('Content-Length', str(len(raw)))
|
|
handler.end_headers()
|
|
handler.wfile.write(raw)
|
|
|
|
|
|
class H(BaseHTTPRequestHandler):
|
|
def do_GET(self):
|
|
try:
|
|
u = urlparse(self.path)
|
|
q = parse_qs(u.query)
|
|
|
|
if u.path == '/health':
|
|
return _json(self, 200, {'ok': True, 'service': 'prime-oauth'})
|
|
|
|
if u.path.startswith('/auth/') and u.path.endswith('/start'):
|
|
provider = u.path.split('/')[2]
|
|
redirect_uri = q.get('redirect_uri', [''])[0]
|
|
if not redirect_uri:
|
|
return _json(self, 400, {'error': 'redirect_uri required'})
|
|
out = start(provider, redirect_uri)
|
|
return _json(self, 200, out)
|
|
|
|
if u.path.startswith('/auth/') and u.path.endswith('/callback'):
|
|
provider = u.path.split('/')[2]
|
|
state = q.get('state', [''])[0]
|
|
code = q.get('code', [''])[0]
|
|
if not state or not code:
|
|
return _json(self, 400, {'error': 'state and code required'})
|
|
out = callback(provider, state, code)
|
|
return _json(self, 200, out)
|
|
|
|
return _json(self, 404, {'error': 'not_found'})
|
|
except Exception as e:
|
|
return _json(self, 500, {'error': str(e)})
|
|
|
|
def log_message(self, fmt, *args):
|
|
return
|
|
|
|
|
|
def main():
|
|
s = HTTPServer((HOST, PORT), H)
|
|
s.serve_forever()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|