-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1196 lines (1018 loc) · 36.3 KB
/
app.py
File metadata and controls
1196 lines (1018 loc) · 36.3 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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## app.py
from __future__ import annotations
import json
import re
import secrets
from typing import Any
from dotenv import load_dotenv
# .env 파일 로드 (환경 변수)
load_dotenv()
from pathlib import PurePosixPath
from flask import Flask, jsonify, redirect, render_template, request, send_from_directory, session, url_for, make_response, abort
from flask_cors import CORS, cross_origin
from flask_smorest import Api
from flask_socketio import SocketIO
from werkzeug.middleware.proxy_fix import ProxyFix
import requests
from auth import blueprint as auth_bp
from auth.sessions import load_remembered_user
from class_routes import blueprint as class_bp
from exports_routes import blueprint as export_bp
from chat_routes import blueprint as chat_bp
from vote_routes import blueprint as vote_bp
from arcade_routes import blueprint as arcade_bp, init_arcade_socketio
from shop_routes import blueprint as shop_bp
from event_routes import blueprint as event_bp
from public_api import public_api_bp, broadcast_public_status_update
from developer_routes import blueprint as developer_bp
from oauth import blueprint as oauth_bp
from account import blueprint as account_bp
from mcp_routes import blueprint as mcp_bp
from config import config
from extensions import db
from models import ClassConfig, ClassPin, ClassState
from config_loader import load_class_config
from utils import (
after_request,
before_request,
burst_guard_allow,
burst_guard_key,
clear_teacher_session,
is_teacher_session_active,
mark_teacher_session,
metrics,
pin_guard_key,
pin_guard_register_failure,
pin_guard_reset,
pin_guard_status,
setup_logging,
verify_csrf,
)
from content_filter import contains_slang
from ws import namespaces
import gspread
class _NoopSocketIO:
def __init__(self, app: Flask):
self.app = app
self.app.extensions["socketio"] = self
def on_namespace(self, _namespace) -> None:
return None
def emit(self, *_args, **_kwargs) -> None:
return None
def run(self, *_args, **_kwargs) -> None:
raise RuntimeError("Socket.IO backend is unavailable")
app = Flask(__name__)
app.config.from_object(config)
# Reverse proxy(TLS terminator) headers trust: X-Forwarded-Proto/Host
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1)
setup_logging(config.LOG_LEVEL)
app.register_blueprint(auth_bp)
app.register_blueprint(class_bp)
app.register_blueprint(export_bp)
app.register_blueprint(chat_bp)
app.register_blueprint(vote_bp)
app.register_blueprint(arcade_bp)
app.register_blueprint(shop_bp)
app.register_blueprint(event_bp)
app.register_blueprint(public_api_bp)
app.register_blueprint(developer_bp)
app.register_blueprint(oauth_bp)
app.register_blueprint(account_bp)
app.register_blueprint(mcp_bp)
app.add_url_rule("/metrics", "metrics", metrics)
db.init_app(app)
socketio_async_mode = "threading"
try:
socketio = SocketIO(
app,
cors_allowed_origins=config.FRONTEND_ORIGIN,
async_mode=socketio_async_mode
)
except ValueError as exc: # pragma: no cover - depends on optional socket backends
app.logger.warning("Socket.IO disabled: %s", exc)
socketio = _NoopSocketIO(app)
CORS(
app,
resources={
r"/public/*": {"origins": "*", "supports_credentials": False},
r"/*": {"origins": [config.FRONTEND_ORIGIN], "supports_credentials": True},
},
)
for ns in namespaces:
socketio.on_namespace(ns)
init_arcade_socketio(socketio)
app.before_request(before_request)
app.after_request(after_request)
app.before_request(verify_csrf)
@app.before_request
def _apply_ddos_guard():
path = request.path or ""
rule_map = {
"/api/version": config.DDOS_GUARD_API_VERSION_MAX_REQUESTS,
"/healthz": config.DDOS_GUARD_HEALTHZ_MAX_REQUESTS,
"/metrics": config.DDOS_GUARD_METRICS_MAX_REQUESTS,
"/api/qrng": config.DDOS_GUARD_QRNG_MAX_REQUESTS,
}
max_requests = rule_map.get(path)
if max_requests is None:
return None
allowed, retry_after = burst_guard_allow(
burst_guard_key(f"http:{path}"),
max_requests=max_requests,
window_seconds=config.DDOS_GUARD_WINDOW_SECONDS,
)
if allowed:
return None
response = jsonify(
{
"error": {
"code": "429",
"message": "too many requests",
}
}
)
response.status_code = 429
response.headers["Retry-After"] = str(retry_after)
return response
def _set_no_store(response):
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
def _set_short_revalidate_cache(response):
response.headers["Cache-Control"] = "public, max-age=300, must-revalidate"
response.headers.pop("Pragma", None)
response.headers.pop("Expires", None)
@app.after_request
def _apply_cache_policy(response):
path = (request.path or "").lower()
mimetype = (response.mimetype or "").lower()
host = (request.host or "").split(":", 1)[0].lower()
def _maybe_set_hsts():
if request.is_secure and host in _HTTPS_ENFORCED_HOSTS:
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
is_api_or_auth = path.startswith("/api/") or path.startswith("/auth/") or path == "/me"
is_html = path == "/" or path.endswith(".html") or mimetype == "text/html"
is_service_worker = path == "/service-worker.js"
is_pwa_script = path == "/js/pwa.js"
is_manifest = path == "/manifest.webmanifest"
if is_api_or_auth or is_html or is_service_worker or is_pwa_script or is_manifest:
_set_no_store(response)
_maybe_set_hsts()
return response
if path.endswith((
".js",
".css",
".json",
".map",
".txt",
".xml",
".webmanifest",
".png",
".jpg",
".jpeg",
".gif",
".svg",
".webp",
".ico",
".woff",
".woff2",
".ttf",
".otf",
)):
_set_short_revalidate_cache(response)
_maybe_set_hsts()
return response
_SENSITIVE_PREFIXES = {
".env",
"dimicheck-471412-85491c7985df.json",
"instance",
".git",
".venv",
"app.db",
}
_HTTPS_ENFORCED_HOSTS = {
"dimicheck.com",
"www.dimicheck.com",
"chec.kro.kr",
"www.chec.kro.kr",
}
@app.before_request
def _block_sensitive_files():
path = (request.path or "").lstrip("/")
lowered = path.lower()
for prefix in _SENSITIVE_PREFIXES:
prefix_lower = prefix.lower().rstrip("/")
if lowered == prefix_lower or lowered.startswith(f"{prefix_lower}/") or f"/{prefix_lower}" in f"/{lowered}":
abort(404)
@app.before_request
def _force_https_for_public_hosts():
host = (request.host or "").split(":", 1)[0].lower()
if host not in _HTTPS_ENFORCED_HOSTS:
return None
if request.is_secure:
return None
https_url = request.url.replace("http://", "https://", 1)
return redirect(https_url, code=301)
@app.context_processor
def inject_asset_version():
"""Inject asset version for cache busting"""
return {
'asset_version': config.ASSET_VERSION,
'app_version': config.APP_VERSION,
}
@app.before_request
def _inject_remembered_session():
load_remembered_user()
@app.before_request
def _refresh_user_session() -> None:
if session.get("user"):
session.permanent = True
@app.errorhandler(400)
@app.errorhandler(401)
@app.errorhandler(403)
@app.errorhandler(404)
@app.errorhandler(409)
def handle_error(err):
code = getattr(err, "code", 500)
message = getattr(err, "description", str(err))
# JSON 요청 (예: fetch, axios) → JSON 반환
if request.accept_mimetypes.best == "application/json" or request.is_json:
return jsonify({"error": {"code": str(code), "message": message}}), code
# 일반 브라우저 접근 → HTML 페이지
return send_from_directory(".", "404.html"), code
@app.get("/healthz")
@cross_origin(origins=["https://checstat.netlify.app"])
def health() -> Any:
return {"status": "ok"}
def _resolve_student_chat_page() -> str:
user = session.get("user") or {}
if str(user.get("type", "")).lower() != "student":
return "chat.html"
grade, section, _ = _derive_student_session()
if grade is None or section is None:
return "chat.html"
try:
class_config = load_class_config().get((grade, section)) or {}
except Exception as exc: # pylint: disable=broad-except
app.logger.warning("Failed to load class config for chat gate: %s", exc)
return "chat.html"
return "chat.html" if bool(class_config.get("chat_enabled")) else "notice.html"
@app.get("/chat.html")
def chat_page():
return send_from_directory(".", _resolve_student_chat_page())
@app.get("/user")
def user_page_alias():
return redirect("/user.html")
@app.get("/user.html")
def user_page():
user = session.get("user") or {}
if str(user.get("type", "")).lower() == "teacher":
return redirect(url_for("teacher_dashboard"))
return send_from_directory(".", "user.html")
@app.get("/me")
def me() -> Any:
user = session.get("user")
teacher_session_active = is_teacher_session_active()
if not user and not teacher_session_active:
return jsonify({"error": {"code": "unauthorized", "message": "login required"}}), 401
token = session.get("csrf_token")
if not token:
import secrets
token = secrets.token_hex(16)
session["csrf_token"] = token
if not user and teacher_session_active:
return jsonify({"type": "teacher", "csrf_token": token})
user_data = {k: v for k, v in user.items() if k in {"id", "email", "name", "type", "grade", "class", "number"}}
user_data["csrf_token"] = token
return jsonify(user_data)
# Swagger UI
api_spec = {
"title": "Presence API",
"version": "1.0",
"openapi_version": "3.0.2",
"components": {"securitySchemes": {}},
"name": "dimicheck-openapi"
}
api = Api(app, spec_kwargs=api_spec)
CLASS_CONFIGS = load_class_config()
QRNG_ENDPOINT = "https://qrng.anu.edu.au/API/jsonI.php"
QRNG_ALLOWED_TYPES = {"uint8", "uint16", "hex16"}
QRNG_MAX_LENGTH = 1024
DEFAULT_CHAT_CHANNEL = "home"
# 단축 상태 코드 → 내부 상태 키 매핑
STATUS_ALIASES = {
"class": "section",
"classroom": "section",
"room": "section",
"section": "section",
"교실": "section",
"toilet": "toilet",
"화장실": "toilet",
"bathroom": "toilet",
"hallway": "hallway",
"복도": "hallway",
"club": "club",
"동아리": "club",
"afterschool": "afterschool",
"after-school": "afterschool",
"방과후": "afterschool",
"project": "project",
"프로젝트": "project",
"early": "early",
"조기입실": "early",
"etc": "etc",
"기타": "etc",
"absence": "absence",
"absent": "absence",
"결석": "absence",
"조퇴": "absence",
}
STATUS_LABELS = {
"section": "교실",
"toilet": "화장실",
"hallway": "복도",
"club": "동아리",
"afterschool": "방과후",
"project": "프로젝트",
"early": "조기입실",
"etc": "기타",
"absence": "결석(조퇴)",
}
PRESERVE_STATE_FIELDS = [
"reaction",
"reactionPostedAt",
"reactionExpiresAt",
"thought",
"thoughtPostedAt",
"thoughtExpiresAt",
]
def _fallback_qrng(length: int, qtype: str) -> dict[str, Any]:
if qtype == "uint16":
data = [secrets.randbits(16) for _ in range(length)]
elif qtype == "hex16":
data = [f"{secrets.randbits(16):04x}" for _ in range(length)]
else: # default uint8
data = list(secrets.token_bytes(length))
return {"success": True, "data": data, "source": "fallback"}
def _coerce_int(value: Any) -> int | None:
try:
return int(value)
except (TypeError, ValueError):
return None
def _split_student_identifier(value: Any) -> tuple[int | None, int | None, int | None]:
if value is None:
return None, None, None
digits = "".join(ch for ch in str(value) if ch.isdigit())
if not digits:
return None, None, None
if len(digits) >= 3:
grade = _coerce_int(digits[0])
seat = _coerce_int(digits[-2:])
section_digits = digits[1:-2]
section = _coerce_int(section_digits) if section_digits else None
return grade, section, seat
return None, None, _coerce_int(digits)
def _derive_student_session() -> tuple[int | None, int | None, int | None]:
user = session.get("user") or {}
if str(user.get("type", "")).lower() != "student":
return None, None, None
grade = _coerce_int(user.get("grade") or user.get("grade_no") or user.get("gradeNo"))
section = _coerce_int(
user.get("class")
or user.get("class_no")
or user.get("classNo")
or user.get("section")
or user.get("section_no")
or user.get("sectionNo")
)
identifier = (
user.get("number")
or user.get("student_number")
or user.get("studentNumber")
or user.get("student_no")
or user.get("studentNo")
)
derived_grade, derived_section, seat = _split_student_identifier(identifier)
if grade is None:
grade = derived_grade
if section is None:
section = derived_section
if seat is None:
_, _, seat = _split_student_identifier(user.get("seat_number") or user.get("seatNumber") or user.get("number_only"))
return grade, section, seat
def _normalize_status_param(raw_status: str | None) -> str | None:
if not raw_status:
return None
cleaned = str(raw_status).strip().strip('"\'').lower()
canonical = STATUS_ALIASES.get(cleaned, cleaned)
if canonical in STATUS_LABELS:
return canonical
return None
def _normalize_channels(channels_raw) -> list[str]:
channels = channels_raw if isinstance(channels_raw, list) else []
normalized: list[str] = []
seen = set()
for ch in channels:
if not isinstance(ch, str):
continue
name = ch.strip()
if not name:
continue
key = name.casefold()
if key in seen:
continue
seen.add(key)
normalized.append(name[:30])
if DEFAULT_CHAT_CHANNEL.casefold() not in seen:
normalized.insert(0, DEFAULT_CHAT_CHANNEL)
return normalized
def _normalize_channel_memberships(raw_memberships, channels: list[str], grade: int | None = None, section: int | None = None) -> dict[str, list[dict]]:
memberships = raw_memberships if isinstance(raw_memberships, dict) else {}
result: dict[str, list[dict]] = {}
for ch in channels:
entries = []
seen = set()
raw_entries = memberships.get(ch) if isinstance(memberships.get(ch), list) else []
for entry in raw_entries:
if not isinstance(entry, dict):
continue
g = _coerce_int(entry.get("grade"))
s = _coerce_int(entry.get("section"))
if g is None or s is None:
continue
key = f"{g}-{s}"
if key in seen:
continue
seen.add(key)
entries.append({"grade": g, "section": s})
if grade is not None and section is not None:
key = f"{grade}-{section}"
if key not in seen:
entries.append({"grade": grade, "section": section})
result[ch] = entries
return result
def _load_magnet_payload(state: ClassState | None) -> dict[str, dict[str, object]]:
if not state or not state.data:
return {"magnets": {}, "channels": [DEFAULT_CHAT_CHANNEL], "channelMemberships": {DEFAULT_CHAT_CHANNEL: []}}
try:
raw = json.loads(state.data)
except json.JSONDecodeError:
return {"magnets": {}, "channels": [DEFAULT_CHAT_CHANNEL], "channelMemberships": {DEFAULT_CHAT_CHANNEL: []}}
if not isinstance(raw, dict):
return {"magnets": {}, "channels": [DEFAULT_CHAT_CHANNEL], "channelMemberships": {DEFAULT_CHAT_CHANNEL: []}}
magnets = raw.get("magnets")
if not isinstance(magnets, dict):
magnets = {}
channels = _normalize_channels(raw.get("channels"))
memberships = _normalize_channel_memberships(
raw.get("channelMemberships"),
channels,
getattr(state, "grade", None),
getattr(state, "section", None),
)
return {"magnets": magnets, "channels": channels, "channelMemberships": memberships}
def _persist_magnet_state(state: ClassState | None, grade: int, section: int, payload: dict[str, object]) -> ClassState:
if not state:
state = ClassState(grade=grade, section=section, data="")
db.session.add(state)
state.data = json.dumps(payload, ensure_ascii=False)
db.session.commit()
return state
def _upsert_student_status(
magnets: dict[str, dict[str, object]],
student_number: int,
status_code: str,
reason: str | None,
) -> dict[str, dict[str, object]]:
normalized_reason = reason.strip() if reason else None
payload: dict[str, object] = {"attachedTo": status_code}
if status_code == "etc" and normalized_reason:
payload["reason"] = normalized_reason
elif status_code != "etc":
payload.pop("reason", None)
key = str(student_number)
existing = magnets.get(key, {}) if isinstance(magnets, dict) else {}
for field in PRESERVE_STATE_FIELDS:
if field in existing and field not in payload:
payload[field] = existing[field]
magnets[key] = payload
return magnets
@app.get("/api/qrng")
@cross_origin(origins=[config.FRONTEND_ORIGIN, "https://churchofquantum.netlify.app"])
def qrng_proxy():
length = request.args.get("length", default=128, type=int)
qtype = request.args.get("type", default="uint8")
if not length or length < 1 or length > QRNG_MAX_LENGTH:
return (
jsonify(
{
"success": False,
"error": "invalid_length",
"message": f"length must be between 1 and {QRNG_MAX_LENGTH}",
}
),
400,
)
if qtype not in QRNG_ALLOWED_TYPES:
qtype = "uint8"
try:
upstream = requests.get(
QRNG_ENDPOINT,
params={"length": length, "type": qtype},
timeout=5,
)
upstream.raise_for_status()
data = upstream.json()
if data.get("success"):
return jsonify(data)
app.logger.warning("QRNG upstream responded without success flag: %s", data)
except requests.RequestException as exc:
app.logger.warning("QRNG upstream error: %s", exc)
except ValueError:
app.logger.warning("QRNG upstream returned invalid JSON")
fallback = _fallback_qrng(length, qtype)
return jsonify(fallback), 200
@app.route("/board", methods=["GET", "POST"])
def board():
CLASS_CONFIGS = load_class_config()
grade = request.args.get("grade", type=int)
section = request.args.get("section", type=int)
class_config = CLASS_CONFIGS.get((grade, section))
if not class_config:
return send_from_directory(".", "404.html")
guard_key = pin_guard_key(f"board:{grade}:{section}")
if request.method == "POST":
allowed, _, locked_for = pin_guard_status(guard_key, max_attempts=5, window_seconds=300, lock_seconds=900)
if not allowed:
return make_response("Too many attempts. 잠시 후 다시 시도해주세요.", 429)
pin = request.form.get("pin")
if str(class_config["pin"]) == pin:
session[f"board_verified_{grade}_{section}"] = True
session.permanent = True
pin_guard_reset(guard_key)
return render_template("index.html", arcade_debug_allow_any_time=config.ARCADE_DEBUG_ALLOW_ANY_TIME)
attempts_left, lock_remaining = pin_guard_register_failure(
guard_key, max_attempts=5, window_seconds=300, lock_seconds=900
)
status_code = 429 if lock_remaining else 401
return make_response("잘못된 PIN 입니다.", status_code)
if session.get(f"board_verified_{grade}_{section}"):
return render_template("index.html", arcade_debug_allow_any_time=config.ARCADE_DEBUG_ALLOW_ANY_TIME)
return send_from_directory(".", "enter_pin.html")
def _parse_short_board_code(code: str) -> tuple[int | None, int | None]:
if not re.fullmatch(r"\d{2}", str(code or "")):
return None, None
grade = int(code[0])
section = int(code[1])
if grade not in {1, 2, 3} or section not in {1, 2, 3, 4, 5, 6}:
return None, None
return grade, section
@app.before_request
def _redirect_short_board_code():
path = (request.path or "").strip("/")
if "/" in path:
return None
grade, section = _parse_short_board_code(path)
if grade is None or section is None:
return None
if not load_class_config().get((grade, section)):
abort(404)
return redirect(url_for("board", grade=grade, section=section))
def _validate_teacher_pin(pin: str) -> bool:
allowed = config.TEACHER_PINS
if not allowed:
return False
return pin in allowed
def _teacher_session_valid() -> bool:
if is_teacher_session_active():
return True
clear_teacher_session()
return False
@app.route("/teacher", methods=["GET", "POST"])
def teacher_dashboard():
if _teacher_session_valid():
return render_template("teacher.html", csrf_token=session.get("csrf_token"))
error = None
guard_key = pin_guard_key("teacher")
if request.method == "POST":
allowed, attempts_left, locked_for = pin_guard_status(guard_key, max_attempts=5, window_seconds=300, lock_seconds=900)
if not allowed:
error = f"시도가 잠겼어요. {locked_for}초 후 다시 시도하세요."
return render_template(
"teacher_pin.html",
error=error,
has_pin=bool(config.TEACHER_PINS),
)
pin = (request.form.get("pin") or "").strip()
remember = request.form.get("remember") == "on"
if not config.TEACHER_PINS:
error = "교사용 PIN이 설정되지 않았습니다. 관리자에게 문의하세요."
elif _validate_teacher_pin(pin):
duration = (
config.TEACHER_SESSION_REMEMBER_SECONDS
if remember
else config.TEACHER_SESSION_DURATION_SECONDS
)
mark_teacher_session(duration_seconds=duration, remember=remember)
pin_guard_reset(guard_key)
return redirect(url_for("teacher_dashboard"))
else:
attempts_left, lock_remaining = pin_guard_register_failure(
guard_key, max_attempts=5, window_seconds=300, lock_seconds=900
)
if lock_remaining:
error = f"PIN이 여러 번 틀렸어요. {lock_remaining}초 후 다시 시도하세요."
elif attempts_left > 0:
error = f"PIN이 올바르지 않습니다. 다시 시도해주세요. (남은 시도 {attempts_left}회)"
else:
error = "PIN이 올바르지 않습니다. 잠시 후 다시 시도해주세요."
return render_template(
"teacher_pin.html",
error=error,
has_pin=bool(config.TEACHER_PINS),
)
@app.get("/teacher/notices")
def teacher_notices_page():
if not _teacher_session_valid():
return redirect(url_for("teacher_dashboard"))
return render_template("teacher_notices.html", csrf_token=session.get("csrf_token"))
@app.get("/teacher/wallpapers")
def teacher_wallpapers_page():
if not _teacher_session_valid():
return redirect(url_for("teacher_dashboard"))
return render_template("teacher_wallpapers.html", csrf_token=session.get("csrf_token"))
@app.get("/teacher/events")
def teacher_events_page():
if not _teacher_session_valid():
return redirect(url_for("teacher_dashboard"))
return render_template("teacher_events.html", csrf_token=session.get("csrf_token"))
@app.get("/teacher.html")
def teacher_legacy_redirect():
return redirect(url_for("teacher_dashboard"))
@app.route("/", methods=["GET", "POST"])
def index(): # type: ignore[override]
user = session.get("user")
if user:
user_type = str(user.get("type", "")).lower()
if user_type == "teacher":
return redirect(url_for("teacher_dashboard"))
if user_type == "student":
return redirect("/user.html")
return send_from_directory(".", "login.html")
@app.get("/privacy")
def privacy():
return send_from_directory(".", "privacy.html")
@app.get("/set")
def quick_apply_status_get():
raw_status = request.args.get("status")
reason_input = request.args.get("reason") or ""
reason = str(reason_input).strip() or None
status_code = _normalize_status_param(raw_status)
allowed_codes = sorted(STATUS_LABELS.keys())
user = session.get("user") or {}
status_label = STATUS_LABELS.get(status_code, status_code) if status_code else None
if reason and contains_slang(reason):
return (
render_template(
"set_status.html",
success=False,
status_code=status_code or raw_status,
status_label=status_label,
allowed_codes=allowed_codes,
labels=STATUS_LABELS,
error="invalid_reason",
pending_status=None,
pending_reason=None,
pending_apply=False,
requires_login=False,
csrf_token=session.get("csrf_token"),
),
400,
)
if status_code:
if not user:
return render_template(
"set_status.html",
success=False,
pending_status=status_code,
pending_reason=reason if status_code == "etc" else None,
pending_apply=False,
requires_login=True,
status_code=status_code,
status_label=status_label,
allowed_codes=allowed_codes,
labels=STATUS_LABELS,
csrf_token=None,
error=None,
)
if str(user.get("type", "")).lower() != "student":
return (
render_template(
"set_status.html",
success=False,
status_code=status_code,
status_label=status_label,
allowed_codes=allowed_codes,
labels=STATUS_LABELS,
error="unsupported_user",
pending_status=None,
pending_reason=None,
pending_apply=False,
requires_login=False,
csrf_token=session.get("csrf_token"),
),
403,
)
grade, section, seat = _derive_student_session()
if grade is None or section is None or seat is None:
return (
render_template(
"set_status.html",
success=False,
status_code=status_code,
status_label=status_label,
allowed_codes=allowed_codes,
labels=STATUS_LABELS,
error="missing_profile",
pending_status=None,
pending_reason=None,
pending_apply=False,
requires_login=False,
csrf_token=session.get("csrf_token"),
),
400,
)
if not session.get("csrf_token"):
session["csrf_token"] = secrets.token_hex(16)
return render_template(
"set_status.html",
success=False,
pending_status=status_code,
pending_reason=reason if status_code == "etc" else None,
pending_apply=True,
requires_login=False,
status_code=status_code,
status_label=status_label,
allowed_codes=allowed_codes,
labels=STATUS_LABELS,
csrf_token=session.get("csrf_token"),
error=None,
)
return (
render_template(
"set_status.html",
success=False,
status_code=None,
status_label=None,
allowed_codes=allowed_codes,
labels=STATUS_LABELS,
error="method_not_allowed",
pending_status=None,
pending_reason=None,
pending_apply=False,
requires_login=False,
csrf_token=session.get("csrf_token"),
),
405,
)
@app.post("/set")
def quick_apply_status():
payload = request.get_json(silent=True) if request.is_json else None
raw_status = (
(payload.get("status") if isinstance(payload, dict) else None)
or request.form.get("status")
or request.args.get("status")
)
reason_input = (
(payload.get("reason") if isinstance(payload, dict) else None)
or request.form.get("reason")
or request.args.get("reason")
or ""
)
reason = str(reason_input).strip() or None
status_code = _normalize_status_param(raw_status)
allowed_codes = sorted(STATUS_LABELS.keys())
if not status_code:
return (
render_template(
"set_status.html",
success=False,
status_code=raw_status,
status_label=None,
allowed_codes=allowed_codes,
labels=STATUS_LABELS,
error="invalid_status",
pending_status=None,
pending_reason=None,
pending_apply=False,
requires_login=False,
csrf_token=session.get("csrf_token"),
),
400,
)
if reason and contains_slang(reason):
return (
render_template(
"set_status.html",
success=False,
status_code=status_code,
status_label=STATUS_LABELS.get(status_code, status_code),
allowed_codes=allowed_codes,
labels=STATUS_LABELS,
error="invalid_reason",
pending_status=None,
pending_reason=None,
pending_apply=False,
requires_login=False,
csrf_token=session.get("csrf_token"),
),
400,
)
user = session.get("user")
if not user:
return redirect(
url_for(
"auth.login",
next=url_for(
"quick_apply_status_get",
status=status_code,
reason=reason or "",
),
)
)
if str(user.get("type", "")).lower() != "student":