forked from leg100/pubsub-webhook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
49 lines (35 loc) · 1.52 KB
/
main.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
from google.cloud import pubsub
from square.utilities.webhooks_helper import is_valid_webhook_event_signature
import os
def whitelist_req(req, ranges):
from ipaddress import ip_address, ip_network
for r in ranges.split(','):
if ip_address(req.remote_addr) in ip_network(r):
return True
return False
def pubsub_webhook(req):
print("Request received")
if req.method != 'POST':
return ('Method not allowed', 405)
if 'IP_WHITELIST' in os.environ:
if not whitelist_req(req, os.environ['IP_WHITELIST']):
return ('Forbidden', 403)
signature = req.headers.get("x-square-hmacsha256-signature", None)
body = req.data
# Only process data with a valid signature
is_from_square = is_valid_webhook_event_signature(body,
signature,
os.environ['SIGNATURE_KEY'],
os.environ['NOTIFICATION_URL'])
if is_from_square:
# Signature is valid. Return 200 OK.
print("Request body: {}".format(body))
client = pubsub.PublisherClient()
topic_project = os.environ.get('TOPIC_PROJECT', os.environ['GCP_PROJECT'])
topic_name = os.environ['TOPIC_NAME']
topic = f'projects/{topic_project}/topics/{topic_name}'
client.publish(topic, req.get_data())
return 'OK'
else:
# Signature is invalid. Return 403 Forbidden.
self.send_response(403)