Ashish-K commited on
Commit
4ecdf5f
·
verified ·
1 Parent(s): c5d86d7

Serve the app only under a secret link

Browse files
Files changed (2) hide show
  1. app.py +48 -18
  2. static/index.html +0 -0
app.py CHANGED
@@ -24,8 +24,8 @@ import uuid
24
  from datetime import datetime, timezone
25
  from pathlib import Path
26
 
27
- from fastapi import FastAPI, Header, HTTPException, Query
28
- from fastapi.responses import FileResponse, JSONResponse, Response
29
  from pydantic import BaseModel, Field
30
 
31
  HERE = Path(__file__).parent
@@ -34,7 +34,17 @@ HF_TOKEN = os.environ.get("HF_TOKEN")
34
  RESULTS_REPO = os.environ.get("RESULTS_REPO", "")
35
  LOCAL = HERE / "localdata"
36
 
37
- app = FastAPI(title="StepWise Self-Checks", docs_url=None, redoc_url=None)
 
 
 
 
 
 
 
 
 
 
38
 
39
 
40
  # ---------------------------------------------------------------- storage
@@ -209,19 +219,19 @@ class AttemptIn(BaseModel):
209
  answers: dict[str, AnswerIn]
210
 
211
 
212
- @app.get("/")
213
  def index() -> FileResponse:
214
  return FileResponse(HERE / "static" / "index.html", headers={"Cache-Control": "no-cache"})
215
 
216
 
217
- @app.get("/api/state")
218
  def state() -> JSONResponse:
219
  students = [{"id": k, **v} for k, v in STORE.students.items()]
220
  return JSONResponse({"sets": list(SETS.values()), "students": students, "attempts": STORE.attempts,
221
  "feedback": list(STORE.feedback.values())})
222
 
223
 
224
- @app.post("/api/students")
225
  def add_student(body: StudentIn) -> dict:
226
  name = re.sub(r"\s+", " ", body.name).strip()
227
  if not name:
@@ -229,7 +239,7 @@ def add_student(body: StudentIn) -> dict:
229
  return STORE.add_student(name)
230
 
231
 
232
- @app.post("/api/attempts")
233
  def add_attempt(body: AttemptIn) -> dict:
234
  if body.studentId not in STORE.students:
235
  raise HTTPException(404, "That student is not on the list any more.")
@@ -291,12 +301,12 @@ def _tutor_call(fn, *a):
291
  raise HTTPException(502, "The tutor hit a problem. Try again in a moment.") from e
292
 
293
 
294
- @app.get("/api/tutor/status")
295
  def tutor_status() -> dict:
296
  return {"enabled": TUTOR_ON, "chapters": [c for c in CHAPTERS if c in SETS]}
297
 
298
 
299
- @app.get("/api/mastery/{student_id}")
300
  def mastery(student_id: str) -> dict:
301
  m = STORE.mastery.get(student_id, {})
302
  out = {}
@@ -306,7 +316,7 @@ def mastery(student_id: str) -> dict:
306
  return out
307
 
308
 
309
- @app.post("/api/tutor/start")
310
  def tutor_start(body: TutorStart) -> dict:
311
  if not TUTOR_ON:
312
  raise HTTPException(503, "The tutor isn't switched on yet.")
@@ -315,7 +325,7 @@ def tutor_start(body: TutorStart) -> dict:
315
  return _tutor_call(TUTOR.start, body.studentId, body.setId, body.mode)
316
 
317
 
318
- @app.post("/api/tutor/message")
319
  def tutor_message(body: TutorMsg) -> dict:
320
  if body.sessionId not in STORE.chats:
321
  raise HTTPException(404, "That chat has ended. Start a new one.")
@@ -342,7 +352,7 @@ class FeedbackStatus(BaseModel):
342
  note: str = Field(default="", max_length=1000)
343
 
344
 
345
- @app.post("/api/feedback")
346
  def add_feedback(body: FeedbackIn) -> dict:
347
  if body.by != "parent" and body.by not in STORE.students:
348
  raise HTTPException(404, "Pick your name first.")
@@ -358,12 +368,12 @@ def add_feedback(body: FeedbackIn) -> dict:
358
  return item
359
 
360
 
361
- @app.get("/api/feedback")
362
  def list_feedback() -> list:
363
  return sorted(STORE.feedback.values(), key=lambda x: x["created"], reverse=True)
364
 
365
 
366
- @app.post("/api/feedback/{fid}/status")
367
  def set_feedback_status(fid: str, body: FeedbackStatus) -> dict:
368
  item = STORE.feedback.get(fid)
369
  if not item:
@@ -374,7 +384,7 @@ def set_feedback_status(fid: str, body: FeedbackStatus) -> dict:
374
 
375
 
376
  # ---------------------------------------------------------------- parent
377
- @app.get("/api/parent/chats")
378
  def parent_chats() -> list:
379
  names = {k: v["name"] for k, v in STORE.students.items()}
380
  out = []
@@ -388,7 +398,7 @@ def parent_chats() -> list:
388
  return sorted(out, key=lambda x: x["updated"], reverse=True)
389
 
390
 
391
- @app.get("/api/parent/chats/{sid}")
392
  def parent_chat(sid: str) -> dict:
393
  s = STORE.chats.get(sid)
394
  if not s:
@@ -396,7 +406,7 @@ def parent_chat(sid: str) -> dict:
396
  return {k: s[k] for k in ("id", "studentId", "setId", "mode", "started", "updated", "transcript", "attempts", "flags", "usage")}
397
 
398
 
399
- @app.get("/api/export/{kind}.csv")
400
  def export(kind: str) -> Response:
401
  buf = io.StringIO()
402
  w = csv.writer(buf)
@@ -457,5 +467,25 @@ def export(kind: str) -> Response:
457
 
458
  @app.get("/healthz")
459
  def health() -> dict:
 
 
 
 
 
460
  return {"ok": True, "sets": len(SETS), "students": len(STORE.students), "attempts": len(STORE.attempts),
461
- "chats": len(STORE.chats), "feedback": len(STORE.feedback), "tutor": TUTOR_ON, "storage": "hf-dataset" if STORE.api else "local"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  from datetime import datetime, timezone
25
  from pathlib import Path
26
 
27
+ from fastapi import APIRouter, Depends, FastAPI, Header, HTTPException, Query
28
+ from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, RedirectResponse, Response
29
  from pydantic import BaseModel, Field
30
 
31
  HERE = Path(__file__).parent
 
34
  RESULTS_REPO = os.environ.get("RESULTS_REPO", "")
35
  LOCAL = HERE / "localdata"
36
 
37
+ app = FastAPI(title="StepWise Self-Checks", docs_url=None, redoc_url=None, openapi_url=None)
38
+ ACCESS_KEY = os.environ.get("ACCESS_KEY", "")
39
+
40
+
41
+ def check_key(key: str) -> None:
42
+ """Everything lives under /s/<ACCESS_KEY>/; any other key looks like a missing page."""
43
+ if not ACCESS_KEY or not secrets.compare_digest(key, ACCESS_KEY):
44
+ raise HTTPException(404, "Not found")
45
+
46
+
47
+ router = APIRouter(prefix="/s/{key}", dependencies=[Depends(check_key)])
48
 
49
 
50
  # ---------------------------------------------------------------- storage
 
219
  answers: dict[str, AnswerIn]
220
 
221
 
222
+ @router.get("/")
223
  def index() -> FileResponse:
224
  return FileResponse(HERE / "static" / "index.html", headers={"Cache-Control": "no-cache"})
225
 
226
 
227
+ @router.get("/api/state")
228
  def state() -> JSONResponse:
229
  students = [{"id": k, **v} for k, v in STORE.students.items()]
230
  return JSONResponse({"sets": list(SETS.values()), "students": students, "attempts": STORE.attempts,
231
  "feedback": list(STORE.feedback.values())})
232
 
233
 
234
+ @router.post("/api/students")
235
  def add_student(body: StudentIn) -> dict:
236
  name = re.sub(r"\s+", " ", body.name).strip()
237
  if not name:
 
239
  return STORE.add_student(name)
240
 
241
 
242
+ @router.post("/api/attempts")
243
  def add_attempt(body: AttemptIn) -> dict:
244
  if body.studentId not in STORE.students:
245
  raise HTTPException(404, "That student is not on the list any more.")
 
301
  raise HTTPException(502, "The tutor hit a problem. Try again in a moment.") from e
302
 
303
 
304
+ @router.get("/api/tutor/status")
305
  def tutor_status() -> dict:
306
  return {"enabled": TUTOR_ON, "chapters": [c for c in CHAPTERS if c in SETS]}
307
 
308
 
309
+ @router.get("/api/mastery/{student_id}")
310
  def mastery(student_id: str) -> dict:
311
  m = STORE.mastery.get(student_id, {})
312
  out = {}
 
316
  return out
317
 
318
 
319
+ @router.post("/api/tutor/start")
320
  def tutor_start(body: TutorStart) -> dict:
321
  if not TUTOR_ON:
322
  raise HTTPException(503, "The tutor isn't switched on yet.")
 
325
  return _tutor_call(TUTOR.start, body.studentId, body.setId, body.mode)
326
 
327
 
328
+ @router.post("/api/tutor/message")
329
  def tutor_message(body: TutorMsg) -> dict:
330
  if body.sessionId not in STORE.chats:
331
  raise HTTPException(404, "That chat has ended. Start a new one.")
 
352
  note: str = Field(default="", max_length=1000)
353
 
354
 
355
+ @router.post("/api/feedback")
356
  def add_feedback(body: FeedbackIn) -> dict:
357
  if body.by != "parent" and body.by not in STORE.students:
358
  raise HTTPException(404, "Pick your name first.")
 
368
  return item
369
 
370
 
371
+ @router.get("/api/feedback")
372
  def list_feedback() -> list:
373
  return sorted(STORE.feedback.values(), key=lambda x: x["created"], reverse=True)
374
 
375
 
376
+ @router.post("/api/feedback/{fid}/status")
377
  def set_feedback_status(fid: str, body: FeedbackStatus) -> dict:
378
  item = STORE.feedback.get(fid)
379
  if not item:
 
384
 
385
 
386
  # ---------------------------------------------------------------- parent
387
+ @router.get("/api/parent/chats")
388
  def parent_chats() -> list:
389
  names = {k: v["name"] for k, v in STORE.students.items()}
390
  out = []
 
398
  return sorted(out, key=lambda x: x["updated"], reverse=True)
399
 
400
 
401
+ @router.get("/api/parent/chats/{sid}")
402
  def parent_chat(sid: str) -> dict:
403
  s = STORE.chats.get(sid)
404
  if not s:
 
406
  return {k: s[k] for k in ("id", "studentId", "setId", "mode", "started", "updated", "transcript", "attempts", "flags", "usage")}
407
 
408
 
409
+ @router.get("/api/export/{kind}.csv")
410
  def export(kind: str) -> Response:
411
  buf = io.StringIO()
412
  w = csv.writer(buf)
 
467
 
468
  @app.get("/healthz")
469
  def health() -> dict:
470
+ return {"ok": True}
471
+
472
+
473
+ @router.get("/status")
474
+ def status() -> dict:
475
  return {"ok": True, "sets": len(SETS), "students": len(STORE.students), "attempts": len(STORE.attempts),
476
+ "chats": len(STORE.chats), "feedback": len(STORE.feedback), "tutor": TUTOR_ON,
477
+ "storage": "hf-dataset" if STORE.api else "local"}
478
+
479
+
480
+ @app.get("/s/{key}", include_in_schema=False)
481
+ def add_slash(key: str) -> RedirectResponse:
482
+ check_key(key)
483
+ return RedirectResponse(f"/s/{key}/", status_code=307)
484
+
485
+
486
+ @app.get("/", include_in_schema=False)
487
+ def root() -> HTMLResponse:
488
+ return HTMLResponse("<!doctype html><title>Not found</title><p>Not found.</p>", status_code=404)
489
+
490
+
491
+ app.include_router(router)
static/index.html CHANGED
The diff for this file is too large to render. See raw diff