forked from hasura/graphql-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebhook.py
55 lines (50 loc) · 1.9 KB
/
webhook.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
"""
Webhook for GraphQL engine
For successful authentication
1) Add header X-Hasura-Auth-From: webhook to the list of headers
2) Base64 encode the required headers (including X-Hasura-Auth-From)
3) Pass it as the bearer token with the Authorization header
"""
import base64
import json
import ssl
import http.server
import traceback
import sys
class Handler(http.server.BaseHTTPRequestHandler):
def handle_headers(self, headers):
if 'Authorization' in headers:
auth = headers['Authorization']
h = dict()
if auth.startswith("Bearer "):
try:
h = json.loads(base64.b64decode(auth[7:]).decode("utf-8"))
if h.get('X-Hasura-Auth-Mode') == 'webhook':
print (h)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps(h).encode('utf-8'))
else:
print ('forbidden')
self.send_response(401)
self.end_headers()
self.wfile.write(b'{}')
except Exception as e:
print ('forbidden')
self.send_response(401)
self.end_headers()
print("type error: " + str(e))
print(traceback.format_exc())
else:
self.send_response(401)
self.end_headers()
print ('forbidden')
def do_GET(self):
self.handle_headers(self.headers)
def do_POST(self):
content_len = self.headers.get('Content-Length')
req_body = self.rfile.read(int(content_len)).decode("utf-8")
req_json = json.loads(req_body)
self.handle_headers(req_json.get('headers', {}))