Domify commited on
Commit
02c5ecf
·
verified ·
1 Parent(s): 37e67bf

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +138 -2
main.py CHANGED
@@ -8,8 +8,14 @@ import aiohttp
8
  import time
9
  import hmac
10
  import hashlib
 
 
 
 
 
11
 
12
  app = FastAPI()
 
13
 
14
  # ============================================
15
  # CORS - allow your frontend domains
@@ -119,7 +125,7 @@ async def get_user(request: Request, email: str = None, user_id: str = None):
119
  return {
120
  "userId": "admin",
121
  "name": "Administrator",
122
- "email": "admin@domify.com",
123
  "tier": "Master",
124
  "expiry": (datetime.now() + timedelta(days=365)).isoformat(),
125
  "certPaid": True,
@@ -256,4 +262,134 @@ async def keep_alive_self():
256
  async def startup_event():
257
  print("🚀 Domify Academy Backend Starting...")
258
  asyncio.create_task(keep_alive_self())
259
- print("✅ Keep-alive task started (pings every 5 minutes)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  import time
9
  import hmac
10
  import hashlib
11
+ import sqlite3
12
+ import requests
13
+ from datetime import datetime
14
+ from fastapi import FastAPI, Request
15
+ from fastapi.middleware.cors import CORSMiddleware
16
 
17
  app = FastAPI()
18
+ app.add_middleware(CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])
19
 
20
  # ============================================
21
  # CORS - allow your frontend domains
 
125
  return {
126
  "userId": "admin",
127
  "name": "Administrator",
128
+ "email": "domifyacademy@gmail.com",
129
  "tier": "Master",
130
  "expiry": (datetime.now() + timedelta(days=365)).isoformat(),
131
  "certPaid": True,
 
262
  async def startup_event():
263
  print("🚀 Domify Academy Backend Starting...")
264
  asyncio.create_task(keep_alive_self())
265
+ print("✅ Keep-alive task started (pings every 5 minutes)")
266
+
267
+
268
+
269
+
270
+ # Google Apps Script Webhook URL (deploy this first)
271
+ APPS_SCRIPT_URL = "https://script.google.com/macros/s/AKfycbwRuM5jLusScp0gzZqOmjO3_V_PXvn72vG4GSZ9P5jNb9kwav6_GVf5g0zWI7CwrXGb/exec"
272
+ # ============================================
273
+ # STORE CERTIFICATE CODE (First call from certificate page)
274
+ # ============================================
275
+ @app.post("/store-certificate-code")
276
+ async def store_certificate_code(request: Request):
277
+ try:
278
+ data = await request.json()
279
+ verification_code = data.get('verification_code')
280
+ user_name = data.get('user_name')
281
+ user_email = data.get('user_email')
282
+ user_id = data.get('user_id')
283
+ tier = data.get('tier')
284
+ date = data.get('date')
285
+
286
+ # Save to SQLite (without Drive URL yet)
287
+ conn = sqlite3.connect('domify_users.db')
288
+ c = conn.cursor()
289
+ c.execute("""
290
+ CREATE TABLE IF NOT EXISTS certificates (
291
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
292
+ verification_code TEXT UNIQUE,
293
+ user_name TEXT,
294
+ user_email TEXT,
295
+ user_id TEXT,
296
+ tier TEXT,
297
+ date TEXT,
298
+ drive_url TEXT
299
+ )
300
+ """)
301
+ c.execute("""
302
+ INSERT OR REPLACE INTO certificates (verification_code, user_name, user_email, user_id, tier, date, drive_url)
303
+ VALUES (?, ?, ?, ?, ?, ?, ?)
304
+ """, (verification_code, user_name, user_email, user_id, tier, date, None))
305
+ conn.commit()
306
+ conn.close()
307
+
308
+ # Send to Google Sheet (via Apps Script)
309
+ try:
310
+ requests.post(APPS_SCRIPT_URL, json={
311
+ "verification_code": verification_code,
312
+ "user_name": user_name,
313
+ "user_email": user_email,
314
+ "user_id": user_id,
315
+ "tier": tier,
316
+ "date": date,
317
+ "drive_url": ""
318
+ }, timeout=10)
319
+ print(f"✅ Sent to Google Sheet: {verification_code}")
320
+ except Exception as e:
321
+ print(f"Sheet error: {e}")
322
+
323
+ return {"success": True, "message": "Certificate code stored"}
324
+
325
+ except Exception as e:
326
+ return {"success": False, "error": str(e)}
327
+
328
+ # ============================================
329
+ # UPDATE DRIVE URL (Called after PDF uploaded to Drive)
330
+ # ============================================
331
+ @app.post("/update-drive-url")
332
+ async def update_drive_url(request: Request):
333
+ try:
334
+ data = await request.json()
335
+ verification_code = data.get('verification_code')
336
+ drive_url = data.get('drive_url')
337
+
338
+ # Update SQLite
339
+ conn = sqlite3.connect('domify_users.db')
340
+ c = conn.cursor()
341
+ c.execute("UPDATE certificates SET drive_url = ? WHERE verification_code = ?", (drive_url, verification_code))
342
+ conn.commit()
343
+ conn.close()
344
+
345
+ # Also update Google Sheet (optional, send a second webhook)
346
+ try:
347
+ # First get the existing row data to update
348
+ conn = sqlite3.connect('domify_users.db')
349
+ c = conn.cursor()
350
+ c.execute("SELECT user_name, user_email, user_id, tier, date FROM certificates WHERE verification_code = ?", (verification_code,))
351
+ row = c.fetchone()
352
+ conn.close()
353
+
354
+ if row:
355
+ requests.post(APPS_SCRIPT_URL, json={
356
+ "verification_code": verification_code,
357
+ "user_name": row[0],
358
+ "user_email": row[1],
359
+ "user_id": row[2],
360
+ "tier": row[3],
361
+ "date": row[4],
362
+ "drive_url": drive_url
363
+ }, timeout=10)
364
+ except Exception as e:
365
+ print(f"Sheet update error: {e}")
366
+
367
+ return {"success": True, "message": "Drive URL updated"}
368
+
369
+ except Exception as e:
370
+ return {"success": False, "error": str(e)}
371
+
372
+ # ============================================
373
+ # VERIFY CERTIFICATE (Returns Drive URL so image can be displayed)
374
+ # ============================================
375
+ @app.get("/verify-certificate")
376
+ async def verify_certificate(code: str, name: str):
377
+ conn = sqlite3.connect('domify_users.db')
378
+ c = conn.cursor()
379
+ c.execute("""
380
+ SELECT user_name, tier, date, drive_url FROM certificates
381
+ WHERE verification_code = ? AND user_name = ?
382
+ """, (code.upper(), name))
383
+ row = c.fetchone()
384
+ conn.close()
385
+
386
+ if row:
387
+ return {
388
+ "valid": True,
389
+ "name": row[0],
390
+ "tier": row[1],
391
+ "date": row[2],
392
+ "imageUrl": row[3] # This is the Drive URL to display
393
+ }
394
+ else:
395
+ return {"valid": False, "error": "No matching certificate found"}