Hussien Haider commited on
Commit
0b3bc37
·
1 Parent(s): dfd40ba
app/api/__init__.py CHANGED
@@ -14,6 +14,7 @@ from . import certificates
14
  from . import onevone
15
  from . import mentor
16
  from . import chatbot
 
17
 
18
  __all__ = [
19
  "auth",
@@ -25,4 +26,5 @@ __all__ = [
25
  "onevone",
26
  "mentor",
27
  "chatbot",
 
28
  ]
 
14
  from . import onevone
15
  from . import mentor
16
  from . import chatbot
17
+ from . import daily_challenge
18
 
19
  __all__ = [
20
  "auth",
 
26
  "onevone",
27
  "mentor",
28
  "chatbot",
29
+ "daily_challenge",
30
  ]
app/api/daily_challenge.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """``/api/daily-challenge`` — Daily random challenge with 2× XP.
2
+
3
+ Every 24 hours a random challenge is picked from the pool. Students
4
+ who complete it get double XP (base + bonus via ``/claim``).
5
+ """
6
+
7
+ import random
8
+ from datetime import datetime, date, timedelta, timezone
9
+ from typing import Optional
10
+
11
+ import httpx
12
+ from fastapi import APIRouter, Depends, HTTPException, Request
13
+ from pydantic import BaseModel
14
+
15
+ from app.core.auth import get_current_user
16
+ from app.core.config import SUPABASE_URL, SUPABASE_ANON_KEY, SUPABASE_EDGE_URL
17
+ from app.services.supabase_service import supabase_headers
18
+
19
+
20
+ router = APIRouter()
21
+
22
+
23
+ # Per-type tables we can pick a daily challenge from.
24
+ _TABLES: list[tuple[str, str, str]] = [
25
+ ("encryption_challenges", "crypto", "red"),
26
+ ("code_fixing_challenges", "code-fixing", "blue"),
27
+ ("log_analysis_challenges", "log-analysis", "blue"),
28
+ ("vulnerability_hunter_challenges", "vulnerability-hunter", "blue"),
29
+ ("web_exploitation_challenges", "web-exploitation", "red"),
30
+ ]
31
+
32
+
33
+ class DailyChallengeResponse(BaseModel):
34
+ challengeId: str
35
+ challengeType: str
36
+ teamRole: str
37
+ title: str
38
+ difficulty: str
39
+ xpReward: int
40
+ xpMultiplier: int = 2
41
+ timeRemaining: int # seconds until midnight
42
+
43
+
44
+ class ClaimRequest(BaseModel):
45
+ challengeId: str
46
+ xpAmount: int = 0
47
+
48
+
49
+ class ClaimResponse(BaseModel):
50
+ bonus: int
51
+
52
+
53
+ # --------------------------------------------------------------------------- #
54
+ # GET /api/daily-challenge #
55
+ # --------------------------------------------------------------------------- #
56
+
57
+ @router.get("/api/daily-challenge")
58
+ async def get_daily_challenge(user: dict = Depends(get_current_user)):
59
+ today = date.today()
60
+
61
+ dc = await _fetch_today_daily_challenge(today)
62
+ if dc:
63
+ challenge_info = await _fetch_challenge_info(
64
+ dc["challenge_id"], dc["challenge_type"], dc["team_role"]
65
+ )
66
+ if challenge_info:
67
+ remaining = _seconds_until_midnight()
68
+ return DailyChallengeResponse(
69
+ challengeId=dc["challenge_id"],
70
+ challengeType=dc["challenge_type"],
71
+ teamRole=dc["team_role"],
72
+ title=challenge_info["title"],
73
+ difficulty=challenge_info["difficulty"],
74
+ xpReward=int(dc.get("xp_reward", challenge_info["xp_reward"])),
75
+ timeRemaining=remaining,
76
+ )
77
+
78
+ # No daily challenge for today yet — pick one.
79
+ dc = await _pick_daily_challenge(today)
80
+ if not dc:
81
+ raise HTTPException(status_code=404, detail="لا توجد تحديات متاحة للتحدي اليومي")
82
+
83
+ challenge_info = await _fetch_challenge_info(
84
+ dc["challenge_id"], dc["challenge_type"], dc["team_role"]
85
+ )
86
+ if not challenge_info:
87
+ raise HTTPException(status_code=404, detail="التحدي غير متاح حالياً")
88
+
89
+ remaining = _seconds_until_midnight()
90
+ return DailyChallengeResponse(
91
+ challengeId=dc["challenge_id"],
92
+ challengeType=dc["challenge_type"],
93
+ teamRole=dc["team_role"],
94
+ title=challenge_info["title"],
95
+ difficulty=challenge_info["difficulty"],
96
+ xpReward=int(dc.get("xp_reward", challenge_info["xp_reward"])),
97
+ timeRemaining=remaining,
98
+ )
99
+
100
+
101
+ # --------------------------------------------------------------------------- #
102
+ # POST /api/daily-challenge/claim #
103
+ # --------------------------------------------------------------------------- #
104
+
105
+ @router.post("/api/daily-challenge/claim")
106
+ async def claim_daily_challenge(
107
+ req: ClaimRequest,
108
+ request: Request,
109
+ user: dict = Depends(get_current_user),
110
+ ):
111
+ today = date.today()
112
+ dc = await _fetch_today_daily_challenge(today)
113
+ if not dc or dc["challenge_id"] != req.challengeId:
114
+ return ClaimResponse(bonus=0)
115
+
116
+ bonus = req.xpAmount or int(dc.get("xp_reward", 150))
117
+ if bonus <= 0:
118
+ return ClaimResponse(bonus=0)
119
+
120
+ async with httpx.AsyncClient(timeout=30) as client:
121
+ resp = await client.post(
122
+ f"{SUPABASE_EDGE_URL}/apex-xp",
123
+ json={"action": "add_xp", "user_id": user["user_id"], "xp_amount": bonus},
124
+ )
125
+ if resp.status_code != 200:
126
+ raise HTTPException(status_code=502, detail="فشل إضافة نقاط XP")
127
+
128
+ return ClaimResponse(bonus=bonus)
129
+
130
+
131
+ # --------------------------------------------------------------------------- #
132
+ # Internal helpers #
133
+ # --------------------------------------------------------------------------- #
134
+
135
+ async def _fetch_today_daily_challenge(today: date) -> Optional[dict]:
136
+ if not SUPABASE_URL or not SUPABASE_ANON_KEY:
137
+ return None
138
+ url = (
139
+ f"{SUPABASE_URL}/rest/v1/daily_challenges"
140
+ f"?active_date=eq.{today.isoformat()}&limit=1"
141
+ f"&order=created_at.desc"
142
+ )
143
+ try:
144
+ async with httpx.AsyncClient(timeout=10) as client:
145
+ r = await client.get(url, headers=supabase_headers())
146
+ if r.status_code == 200:
147
+ rows = r.json()
148
+ if rows:
149
+ return rows[0]
150
+ except Exception as e:
151
+ print(f"[daily_challenge] fetch error: {e}")
152
+ return None
153
+
154
+
155
+ async def _pick_daily_challenge(today: date) -> Optional[dict]:
156
+ if not SUPABASE_URL or not SUPABASE_ANON_KEY:
157
+ return None
158
+
159
+ candidates = []
160
+ for table, ctype, team in _TABLES:
161
+ try:
162
+ async with httpx.AsyncClient(timeout=10) as client:
163
+ r = await client.get(
164
+ f"{SUPABASE_URL}/rest/v1/{table}"
165
+ f"?select=id,title,difficulty,xp_reward"
166
+ f"&order=created_at.desc&limit=50",
167
+ headers=supabase_headers(),
168
+ )
169
+ if r.status_code == 200:
170
+ rows = r.json()
171
+ for row in rows:
172
+ candidates.append((row, ctype, team))
173
+ except Exception as e:
174
+ print(f"[daily_challenge] {table}: {e}")
175
+ continue
176
+
177
+ if not candidates:
178
+ return None
179
+
180
+ row, ctype, team = random.choice(candidates)
181
+ xp_reward = int(row.get("xp_reward") or 150)
182
+
183
+ payload = {
184
+ "challenge_id": row["id"],
185
+ "challenge_type": ctype,
186
+ "team_role": team,
187
+ "xp_reward": xp_reward,
188
+ "active_date": today.isoformat(),
189
+ }
190
+
191
+ url = f"{SUPABASE_URL}/rest/v1/daily_challenges"
192
+ headers = supabase_headers(content_type=True)
193
+ headers["Prefer"] = "return=representation,resolution=ignore-duplicates"
194
+ try:
195
+ async with httpx.AsyncClient(timeout=10) as client:
196
+ r = await client.post(url, json=payload, headers=headers)
197
+ if r.status_code in (200, 201):
198
+ rows = r.json()
199
+ if rows:
200
+ return rows[0]
201
+ else:
202
+ print(f"[daily_challenge] insert failed: {r.status_code} {r.text[:200]}")
203
+ except Exception as e:
204
+ print(f"[daily_challenge] insert exception: {e}")
205
+
206
+ return payload # best-effort return
207
+
208
+
209
+ async def _fetch_challenge_info(
210
+ challenge_id: str, challenge_type: str, team_role: str
211
+ ) -> Optional[dict]:
212
+ table = {
213
+ "crypto": "encryption_challenges",
214
+ "code-fixing": "code_fixing_challenges",
215
+ "log-analysis": "log_analysis_challenges",
216
+ "vulnerability-hunter": "vulnerability_hunter_challenges",
217
+ "web-exploitation": "web_exploitation_challenges",
218
+ }.get(challenge_type)
219
+
220
+ if not table or not SUPABASE_URL or not SUPABASE_ANON_KEY:
221
+ return None
222
+
223
+ url = f"{SUPABASE_URL}/rest/v1/{table}?id=eq.{challenge_id}&limit=1"
224
+ try:
225
+ async with httpx.AsyncClient(timeout=10) as client:
226
+ r = await client.get(url, headers=supabase_headers())
227
+ if r.status_code == 200:
228
+ rows = r.json()
229
+ if rows:
230
+ return rows[0]
231
+ except Exception as e:
232
+ print(f"[daily_challenge] fetch_challenge_info: {e}")
233
+ return None
234
+
235
+
236
+ def _seconds_until_midnight() -> int:
237
+ now = datetime.now(timezone.utc)
238
+ midnight = datetime(now.year, now.month, now.day, tzinfo=timezone.utc).replace(
239
+ hour=0, minute=0, second=0
240
+ ) + timedelta(days=1)
241
+ return int((midnight - now).total_seconds())
app/main.py CHANGED
@@ -89,6 +89,7 @@ from app.api import ( # noqa: E402 (import after middleware so order is right)
89
  profile as _profile,
90
  mentor as _mentor,
91
  chatbot as _chatbot,
 
92
  )
93
 
94
 
@@ -103,6 +104,7 @@ def _include_all_routers(app: FastAPI) -> None:
103
  app.include_router(_profile.router)
104
  app.include_router(_mentor.router)
105
  app.include_router(_chatbot.router)
 
106
 
107
 
108
  _include_all_routers(app)
 
89
  profile as _profile,
90
  mentor as _mentor,
91
  chatbot as _chatbot,
92
+ daily_challenge as _daily_challenge,
93
  )
94
 
95
 
 
104
  app.include_router(_profile.router)
105
  app.include_router(_mentor.router)
106
  app.include_router(_chatbot.router)
107
+ app.include_router(_daily_challenge.router)
108
 
109
 
110
  _include_all_routers(app)
db/schema/015_daily_challenges.sql ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BEGIN;
2
+
3
+ CREATE TABLE IF NOT EXISTS public.daily_challenges (
4
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
5
+ challenge_id text NOT NULL,
6
+ challenge_type text NOT NULL,
7
+ team_role text NOT NULL DEFAULT 'blue',
8
+ xp_reward integer NOT NULL DEFAULT 150,
9
+ active_date date NOT NULL DEFAULT CURRENT_DATE,
10
+ created_at timestamptz NOT NULL DEFAULT now(),
11
+ UNIQUE(active_date)
12
+ );
13
+
14
+ ALTER TABLE public.daily_challenges ENABLE ROW LEVEL SECURITY;
15
+
16
+ DROP POLICY IF EXISTS "Open read daily_challenges" ON public.daily_challenges;
17
+ CREATE POLICY "Open read daily_challenges" ON public.daily_challenges
18
+ FOR SELECT USING (true);
19
+
20
+ DROP POLICY IF EXISTS "Service role insert daily_challenges" ON public.daily_challenges;
21
+ CREATE POLICY "Service role insert daily_challenges" ON public.daily_challenges
22
+ FOR INSERT WITH CHECK (true);
23
+
24
+ DROP POLICY IF EXISTS "Service role update daily_challenges" ON public.daily_challenges;
25
+ CREATE POLICY "Service role update daily_challenges" ON public.daily_challenges
26
+ FOR UPDATE USING (true);
27
+
28
+ COMMIT;