-
Notifications
You must be signed in to change notification settings - Fork 0
/
webhook_handler.py
46 lines (32 loc) · 1.19 KB
/
webhook_handler.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
import subprocess
from flask import Flask, request, abort
import hmac
import hashlib
import os
app = Flask(__name__)
WEBHOOK_SECRET = os.environ.get('GH_WEBHOOK_SECRET')
def is_valid_signature(payload_body, signature):
expected_signature = hmac.new(
key=WEBHOOK_SECRET.encode(),
msg=payload_body,
digestmod=hashlib.sha256
).hexdigest()
return hmac.compare_digest(f'sha256={expected_signature}', signature)
@app.route('/webhook', methods=['POST'])
def webhook():
signature = request.headers.get('X-Hub-Signature-256')
if not signature:
abort(400, 'X-Hub-Signature-256 header is missing')
if not is_valid_signature(request.data, signature):
abort(401, 'Invalid signature')
if request.json['ref'] == 'refs/heads/main':
subprocess.run(['git', 'pull', 'origin', 'main'], check=True)
subprocess.run(['docker-compose', 'stop'], check=True)
subprocess.run(['docker-compose', 'up', '--build', '-d'], check=True)
return 'OK', 200
return 'Not main branch', 200
@app.route('/health', methods=['GET'])
def health():
return {'status': 'OK'}, 200
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5005)