-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.py
More file actions
431 lines (344 loc) · 13.5 KB
/
api.py
File metadata and controls
431 lines (344 loc) · 13.5 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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
from __future__ import annotations
from flask import Blueprint, jsonify, request
from CTFd.models import Challenges, Solves, Users, db
from CTFd.utils.decorators import authed_only, ratelimit
from CTFd.utils.user import get_current_user
try:
from CTFd.utils.config import is_teams_mode
except Exception:
is_teams_mode = None
try:
from CTFd.utils.user import get_current_team
except Exception:
get_current_team = None
from .models import Module, ModuleChallenge, ModuleStatus
from .compat import csrf_protect
from .utils import (
module_challenges_query,
module_progress,
user_has_module_access,
grant_access,
modules_enabled,
ordered_modules_query,
)
modules_api_bp = Blueprint("ctfd_modules_api", __name__, url_prefix="/api/v1/modules")
def _modules_disabled_response():
return jsonify({"success": False, "error": "MODULES_DISABLED"}), 404
def _ensure_modules_enabled():
if modules_enabled():
return None
return _modules_disabled_response()
def _forbidden_response():
return jsonify({"success": False, "error": "FORBIDDEN"}), 403
def _module_access_error(module: Module, user: Users | None):
if module.status == ModuleStatus.locked:
return jsonify({"success": False, "error": "MODULE_LOCKED"}), 403
if module.status == ModuleStatus.private and not user_has_module_access(user, module):
return jsonify({"success": False, "error": "MODULE_ACCESS_REQUIRED"}), 403
return None
def _solved_ids_for_user(user: Users | None) -> set[int]:
if not user:
return set()
try:
if is_teams_mode and is_teams_mode() and get_current_team:
team = get_current_team()
if team:
return {
cid
for (cid,) in db.session.query(Solves.challenge_id)
.filter(Solves.team_id == team.id)
.all()
}
except Exception:
pass
return {
cid
for (cid,) in db.session.query(Solves.challenge_id)
.filter(Solves.user_id == user.id)
.all()
}
def _module_to_dict(module: Module, user: Users | None):
has_access = user_has_module_access(user, module) if user else False
progress = module_progress(user, module) if has_access else module_progress(None, module, challenge_ids=[])
return {
"id": module.id,
"name": module.name,
"category": module.category,
"banner_url": module.banner_url,
"order": module.order,
"status": module.status.value if hasattr(module.status, "value") else str(module.status),
"created_at": module.created_at.isoformat() if module.created_at else None,
"updated_at": module.updated_at.isoformat() if module.updated_at else None,
"has_access": has_access,
"progress": progress,
}
@modules_api_bp.route("", methods=["GET"])
@authed_only
def api_modules_list():
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
modules = ordered_modules_query().all()
# Locked modules are not visible via list for anyone.
modules = [m for m in modules if m.status != ModuleStatus.locked]
# Private modules should not appear in the general list unless the user has access.
modules = [
m
for m in modules
if m.status == ModuleStatus.public
or (m.status == ModuleStatus.private and user_has_module_access(user, m))
]
return jsonify({"success": True, "data": [_module_to_dict(m, user) for m in modules]})
@modules_api_bp.route("/<int:module_id>", methods=["GET"])
@authed_only
def api_modules_get(module_id: int):
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
module = Module.query.get_or_404(module_id)
access_error = _module_access_error(module, user)
if access_error:
return access_error
return jsonify({"success": True, "data": _module_to_dict(module, user)})
@modules_api_bp.route("/<int:module_id>/join", methods=["POST"])
@authed_only
@ratelimit(method="POST", limit=10, interval=60)
@csrf_protect
def api_modules_join(module_id: int):
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
module = Module.query.get_or_404(module_id)
if module.status != ModuleStatus.private:
return jsonify({"success": False, "error": "MODULE_NOT_PRIVATE"}), 400
body = request.get_json(silent=True) or {}
code = (body.get("invite_code") or "").strip().upper()
if not code or not module.invite_code or code != module.invite_code:
return jsonify({"success": False, "error": "INVALID_INVITE_CODE"}), 400
grant_access(module, user, granted_by_user=None)
db.session.commit()
return jsonify({"success": True, "data": _module_to_dict(module, user)})
@modules_api_bp.route("/<int:module_id>/challenges", methods=["GET"])
@authed_only
def api_modules_challenges(module_id: int):
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
module = Module.query.get_or_404(module_id)
access_error = _module_access_error(module, user)
if access_error:
return access_error
challenges = module_challenges_query(module, include_hidden=False)
if not challenges:
return jsonify({"success": False, "error": "MODULE_EMPTY"}), 404
solved_ids = _solved_ids_for_user(user)
data = []
for c in challenges:
data.append(
{
"id": c.id,
"name": c.name,
"category": c.category,
"value": c.value,
"state": c.state,
"type": c.type,
"solved": c.id in solved_ids,
}
)
return jsonify({"success": True, "data": data})
@modules_api_bp.route("/assign", methods=["POST"])
@authed_only
@csrf_protect
def api_modules_assign_challenge():
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
if not user or getattr(user, "type", None) != "admin":
return _forbidden_response()
body = request.get_json(silent=True) or {}
challenge_id = body.get("challenge_id")
try:
challenge_id = int(challenge_id)
except Exception:
return jsonify({"success": False, "error": "INVALID_PAYLOAD"}), 400
raw_module_ids = body.get("module_ids")
module_ids: list[int] = []
if isinstance(raw_module_ids, list):
for value in raw_module_ids:
try:
module_ids.append(int(value))
except Exception:
continue
elif body.get("module_id") not in (None, ""):
try:
module_ids = [int(body.get("module_id"))]
except Exception:
return jsonify({"success": False, "error": "INVALID_PAYLOAD"}), 400
module_ids = list(dict.fromkeys([mid for mid in module_ids if mid > 0]))
if not Challenges.query.get(challenge_id):
return jsonify({"success": False, "error": "CHALLENGE_NOT_FOUND"}), 404
if not module_ids and "module_ids" in body:
ModuleChallenge.query.filter_by(challenge_id=challenge_id).delete()
db.session.commit()
return jsonify({"success": True, "data": {"challenge_id": challenge_id, "module_ids": []}})
if not module_ids:
return jsonify({"success": False, "error": "INVALID_PAYLOAD"}), 400
# Validate existence
existing_modules = {
mid
for (mid,) in db.session.query(Module.id).filter(Module.id.in_(module_ids)).all()
}
if len(existing_modules) != len(module_ids):
return jsonify({"success": False, "error": "MODULE_NOT_FOUND"}), 404
if isinstance(raw_module_ids, list):
ModuleChallenge.query.filter_by(challenge_id=challenge_id).delete()
existing_links = {
mid
for (mid,) in db.session.query(ModuleChallenge.module_id)
.filter(ModuleChallenge.challenge_id == challenge_id)
.all()
}
for module_id in module_ids:
if module_id in existing_links:
continue
db.session.add(ModuleChallenge(challenge_id=challenge_id, module_id=module_id))
db.session.commit()
return jsonify({"success": True, "data": {"challenge_id": challenge_id, "module_ids": module_ids}})
@modules_api_bp.route("/unassign", methods=["POST"])
@authed_only
@csrf_protect
def api_modules_unassign_challenge():
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
if not user or getattr(user, "type", None) != "admin":
return _forbidden_response()
body = request.get_json(silent=True) or {}
challenge_id = body.get("challenge_id")
try:
challenge_id = int(challenge_id)
except Exception:
return jsonify({"success": False, "error": "INVALID_PAYLOAD"}), 400
module_id = body.get("module_id")
if module_id in (None, ""):
ModuleChallenge.query.filter_by(challenge_id=challenge_id).delete()
else:
try:
module_id = int(module_id)
except Exception:
return jsonify({"success": False, "error": "INVALID_PAYLOAD"}), 400
ModuleChallenge.query.filter_by(challenge_id=challenge_id, module_id=module_id).delete()
db.session.commit()
return jsonify({"success": True})
@modules_api_bp.route("/challenge/<int:challenge_id>", methods=["GET"])
@authed_only
def api_modules_challenge_mapping(challenge_id: int):
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
if not user or getattr(user, "type", None) != "admin":
return _forbidden_response()
rows = ModuleChallenge.query.filter_by(challenge_id=challenge_id).all()
module_ids = sorted({row.module_id for row in rows})
modules = Module.query.filter(Module.id.in_(module_ids)).order_by(Module.name.asc()).all() if module_ids else []
return jsonify(
{
"success": True,
"data": {
"challenge_id": challenge_id,
"module_ids": module_ids,
"modules": [{"id": module.id, "name": module.name} for module in modules],
"module_id": (module_ids[0] if module_ids else None),
"module_name": (modules[0].name if modules else None),
},
}
)
@modules_api_bp.route("/bulk/assign", methods=["POST"])
@authed_only
@csrf_protect
def api_modules_bulk_assign_challenges():
"""Add or unassign module mapping for multiple challenges.
Payload:
- challenge_ids: list[int]
- module_id: int | null | "" (empty/null -> unassign all mappings)
"""
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
if not user or getattr(user, "type", None) != "admin":
return _forbidden_response()
body = request.get_json(silent=True) or {}
raw_ids = body.get("challenge_ids")
raw_module_id = body.get("module_id")
if not isinstance(raw_ids, list) or not raw_ids:
return jsonify({"success": False, "error": "INVALID_PAYLOAD"}), 400
challenge_ids: list[int] = []
for x in raw_ids:
try:
challenge_ids.append(int(x))
except Exception:
continue
# De-dup while preserving order
challenge_ids = list(dict.fromkeys([cid for cid in challenge_ids if cid > 0]))
if not challenge_ids:
return jsonify({"success": False, "error": "INVALID_PAYLOAD"}), 400
module_id: int | None
if raw_module_id in (None, ""):
module_id = None
else:
try:
module_id = int(raw_module_id)
except Exception:
return jsonify({"success": False, "error": "INVALID_PAYLOAD"}), 400
# Validate module existence if assigning
if module_id is not None and not Module.query.get(module_id):
return jsonify({"success": False, "error": "MODULE_NOT_FOUND"}), 404
# Only operate on existing challenges
existing_ids = {
cid
for (cid,) in db.session.query(Challenges.id)
.filter(Challenges.id.in_(challenge_ids))
.all()
}
if not existing_ids:
return jsonify({"success": False, "error": "NO_CHALLENGES_FOUND"}), 404
from .models import ModuleChallenge
if module_id is None:
ModuleChallenge.query.filter(ModuleChallenge.challenge_id.in_(list(existing_ids))).delete(
synchronize_session=False
)
db.session.commit()
return jsonify({"success": True, "data": {"updated": len(existing_ids), "module_id": None}})
rows = (
db.session.query(ModuleChallenge.challenge_id)
.filter(ModuleChallenge.challenge_id.in_(list(existing_ids)))
.filter(ModuleChallenge.module_id == module_id)
.all()
)
already_linked = {cid for (cid,) in rows}
for cid in existing_ids:
if cid in already_linked:
continue
db.session.add(ModuleChallenge(challenge_id=cid, module_id=module_id))
db.session.commit()
return jsonify({"success": True, "data": {"updated": len(existing_ids), "module_id": module_id}})
@modules_api_bp.route("/<int:module_id>/progress", methods=["GET"])
@authed_only
def api_modules_progress(module_id: int):
disabled = _ensure_modules_enabled()
if disabled:
return disabled
user = get_current_user()
module = Module.query.get_or_404(module_id)
access_error = _module_access_error(module, user)
if access_error:
return access_error
return jsonify({"success": True, "data": module_progress(user, module)})