-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_email_webhook_old_musha.py
More file actions
163 lines (138 loc) · 5.55 KB
/
get_email_webhook_old_musha.py
File metadata and controls
163 lines (138 loc) · 5.55 KB
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
import os
import json
import hmac
import hashlib
import requests
from msal import ConfidentialClientApplication
from datetime import datetime
# --- Determine mode ---
TEST_MODE = os.getenv("TEST_MODE", "true").lower() == "true"
# Only import Flask if not in TEST_MODE
if not TEST_MODE:
from flask import Flask, request
app = Flask(__name__)
# --- Microsoft Graph Email Sending Function ---
def send_email_via_graph(subject, body):
TENANT_ID = os.getenv("TENANT_ID")
CLIENT_ID = os.getenv("CLIENT_ID")
CLIENT_SECRET = os.getenv("CLIENT_SECRET")
FROM_EMAIL = os.getenv("FROM_EMAIL")
TO_EMAIL = os.getenv("TO_EMAIL")
if not all([TENANT_ID, CLIENT_ID, CLIENT_SECRET, FROM_EMAIL, TO_EMAIL]):
print("❌ Missing required environment variables")
return
try:
app_msal = ConfidentialClientApplication(
CLIENT_ID,
authority=f"https://login.microsoftonline.com/{TENANT_ID}",
client_credential=CLIENT_SECRET
)
token = app_msal.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
access_token = token.get("access_token")
if not access_token:
print(f"❌ Failed to get access token: {token}")
return
email_msg = {
"message": {
"subject": subject,
"body": {"contentType": "Text", "content": body},
"toRecipients": [{"emailAddress": {"address": TO_EMAIL}}]
}
}
response = requests.post(
f"https://graph.microsoft.com/v1.0/users/{FROM_EMAIL}/sendMail",
headers={"Authorization": f"Bearer {access_token}", "Content-Type": "application/json"},
json=email_msg
)
if response.status_code == 202:
print(f"✅ Email sent to {TO_EMAIL}")
else:
print(f"❌ Failed to send email: {response.status_code} {response.text}")
except Exception as e:
print(f"❌ Exception occurred while sending email: {e}")
# --- Format GitHub timestamp ---
def format_timestamp(ts):
"""Convert GitHub timestamp to 'YYYY-MM-DD HH:MM:SS' format."""
if not ts:
return None
try:
dt = datetime.strptime(ts, "%Y-%m-%dT%H:%M:%SZ")
return dt.strftime("%Y-%m-%d %H:%M:%S")
except Exception:
return ts # fallback
# --- Verify GitHub webhook signature ---
def verify_github_signature(payload_body, signature, secret):
if not secret:
print("⚠️ No webhook secret set, skipping verification")
return True
if not signature:
print("❌ No signature provided in headers")
return False
mac = hmac.new(secret.encode(), msg=payload_body, digestmod=hashlib.sha256)
expected_signature = "sha256=" + mac.hexdigest()
return hmac.compare_digest(expected_signature, signature)
# --- GitHub Webhook + Health Handlers ---
if not TEST_MODE:
@app.route("/webhook", methods=["POST"])
def github_webhook():
payload_body = request.data
signature = request.headers.get("X-Hub-Signature-256")
secret = os.getenv("GITHUB_WEBHOOK_SECRET")
# Debug logging
print("📥 Incoming GitHub webhook")
print(f"📥 Payload size: {len(payload_body)} bytes")
print(f"📥 GitHub Event: {request.headers.get('X-GitHub-Event')}")
print(f"📥 Signature header: {signature}")
print(f"📥 Secret length: {len(secret) if secret else 'None'}")
if not verify_github_signature(payload_body, signature, secret):
print("❌ Invalid signature! Webhook rejected.")
return "❌ Invalid signature", 401
try:
data = request.json or {}
except Exception as e:
print(f"❌ Failed to parse JSON payload: {e}")
return "❌ Bad payload", 400
event = request.headers.get("X-GitHub-Event", "")
if event == "repository" and data.get("action") in ["created", "deleted"]:
repo = data.get("repository", {})
action = data["action"]
repo_name = repo.get("name")
full_name = repo.get("full_name")
org = repo.get("owner", {}).get("login")
owner_id = repo.get("owner", {}).get("id")
default_branch = repo.get("default_branch")
created_at = format_timestamp(repo.get("created_at"))
updated_at = format_timestamp(repo.get("updated_at"))
html_url = repo.get("html_url")
subject = f"[GitHub Alert] Repository {action}: {full_name}"
body = f"""
A repository was {action} in your GitHub organization.
Repository: {repo_name}
Full name: {full_name}
Organization: {org}
Owner ID: {owner_id}
Default branch: {default_branch}
Created at: {created_at}
Last updated: {updated_at}
URL: {html_url}
"""
print(f"📩 Sending email alert: {subject}")
send_email_via_graph(subject, body.strip())
else:
print(f"ℹ️ Ignored event: {event}, action: {data.get('action')}")
return "OK", 200
# Health check endpoint
@app.route("/health", methods=["GET"])
def health_check():
return {"status": "running"}, 200
# --- Main Entry Point ---
if __name__ == "__main__":
if TEST_MODE:
print("🔹 TEST_MODE: sending test email")
send_email_via_graph(
"[Test] Graph Email",
"The information of Quantori's GitHub repositories has been updated"
)
else:
print("✅ Flask is up and listening on /webhook and /health")
app.run(host="0.0.0.0", port=int(os.getenv("PORT", 8000)))