Created
May 26, 2019 10:15
-
-
Save fanzeyi/f332b699897a4c364cc7af8479e999f8 to your computer and use it in GitHub Desktop.
GitHub stdlib Python webhook for auto pulling (Python 3)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import json | |
import hmac | |
import hashlib | |
import subprocess | |
from http.server import HTTPServer, BaseHTTPRequestHandler | |
def sign_request(body): | |
key = b"" | |
return hmac.new(key, body, hashlib.sha1).hexdigest() | |
class GitUpdateHook(BaseHTTPRequestHandler): | |
def do_POST(self): | |
if self.path != "/update/hook": | |
self.send_error(404) | |
self.end_headers() | |
self.wfile.write(b"not found") | |
return | |
content_len = int(self.headers.get("Content-Length")) | |
body = self.rfile.read(content_len) | |
sign = sign_request(body) | |
try: | |
_ = json.loads(body) | |
except Exception: | |
self.send_error(400) | |
self.end_headers() | |
self.wfile.write(b"malformed json") | |
return | |
auth = self.headers.get("X-Hub-Signature") | |
if not auth or not auth.endswith(sign): | |
print(auth, sign) | |
self.send_error(403) | |
self.end_headers() | |
self.wfile.write(b"pass isnt right") | |
return | |
subprocess.run(["git", "pull"], cwd="/book") | |
self.send_response(200, message="Success") | |
self.end_headers() | |
self.wfile.write(b"success") | |
return | |
def run(server_class=HTTPServer, handler_class=GitUpdateHook): | |
server_address = ("", 8000) | |
httpd = server_class(server_address, handler_class) | |
httpd.serve_forever() | |
if __name__ == "__main__": | |
exit(run()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment