38 lines
1.2 KiB
Python
38 lines
1.2 KiB
Python
#!/root/kpr-links/.venv/bin/python
|
|
|
|
import hashlib, hmac, os, subprocess, sys
|
|
from dotenv import load_dotenv
|
|
from flask import Flask, request, abort
|
|
|
|
app = Flask(__name__)
|
|
|
|
REPO_DIR = os.getenv("REPO_DIR", "/root/kpr-links")
|
|
SERVICE_NAME = os.getenv("SERVICE_NAME", "kpr-links")
|
|
SECRET = os.getenv("GITEA_SECRET", "")
|
|
|
|
def signature_ok(body: bytes, header: str | None) -> bool:
|
|
if not SECRET:
|
|
return True
|
|
if not header or not header.startswith("sha256="):
|
|
return False
|
|
theirs = header.split("=", 1)[1]
|
|
ours = hmac.new(SECRET.encode(), body, hashlib.sha256).hexdigest()
|
|
return hmac.compare_digest(ours, theirs)
|
|
|
|
@app.post("/webhook")
|
|
def handle():
|
|
if not signature_ok(request.data, request.headers.get("X-Gitea-Signature")):
|
|
abort(403)
|
|
if request.headers.get("X-Gitea-Event") != "push":
|
|
return "ignored", 200
|
|
try:
|
|
subprocess.check_call(["git", "-C", REPO_DIR, "fetch", "--all"])
|
|
subprocess.check_call(["git", "-C", REPO_DIR, "reset", "--hard", "origin/main"])
|
|
subprocess.check_call(["systemctl", "restart", SERVICE_NAME])
|
|
except subprocess.CalledProcessError as e:
|
|
abort(500, str(e))
|
|
return "ok", 200
|
|
|
|
if __name__ == "__main__":
|
|
app.run("0.0.0.0", 9000)
|