""" Flask application for DMH Patient Registration Form. Serves the registration UI, legacy .php endpoints (secured with upload_service and server-side CAPTCHA), and /api/v1 REST endpoints. """ import base64 import hashlib import html import io import json import logging import os import random import shutil import string import time import uuid from collections import defaultdict from datetime import date, timedelta from functools import wraps from dotenv import load_dotenv from flask import Flask, jsonify, render_template, request, send_file, session from PIL import Image, ImageDraw, ImageFont from werkzeug.utils import secure_filename import db from crypto_utils import PiiRedactingFilter, validate_production_secrets from upload_service import UploadValidationError, process_staged_upload from validators import validate_core_fields, validate_registration load_dotenv() validate_production_secrets() app = Flask(__name__, static_folder="static", static_url_path="") app.secret_key = os.getenv("FLASK_SECRET_KEY", "dev-secret-change-me") app.config["UPLOAD_FOLDER"] = os.getenv("UPLOAD_FOLDER", "uploads") app.config["MAX_CONTENT_LENGTH"] = 16 * 1024 * 1024 # 16 MB app.logger.addFilter(PiiRedactingFilter()) logging.getLogger("werkzeug").addFilter(PiiRedactingFilter()) # Simple in-memory sliding-window rate limiter _RATE_BUCKETS: dict[str, list[float]] = defaultdict(list) def _is_rate_limited(bucket: str, limit: int, window_sec: int = 60) -> bool: if app.config.get("TESTING") and not app.config.get("ENABLE_RATE_LIMIT_IN_TESTS"): return False now = time.monotonic() key = f"{bucket}:{request.remote_addr or 'local'}" timestamps = [t for t in _RATE_BUCKETS[key] if now - t < window_sec] if len(timestamps) >= limit: _RATE_BUCKETS[key] = timestamps return True timestamps.append(now) _RATE_BUCKETS[key] = timestamps return False def _render_captcha_png_b64(code: str) -> str: width, height = 160, 44 img = Image.new("RGB", (width, height), "#e4e0e0") draw = ImageDraw.Draw(img) for _ in range(4): draw.line( [(random.randint(0, width), random.randint(0, height)), (random.randint(0, width), random.randint(0, height))], fill="#b0a8a8", width=1, ) font = ImageFont.load_default(size=26) x = 18 for ch in code: draw.text((x, random.randint(6, 11)), ch, fill="#111111", font=font) x += 33 buf = io.BytesIO() img.save(buf, format="PNG") return "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii") @app.after_request def apply_security_headers(response): response.headers.setdefault("X-Content-Type-Options", "nosniff") response.headers.setdefault("X-Frame-Options", "DENY") response.headers.setdefault( "Content-Security-Policy", "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' blob: data:;", ) return response @app.route("/healthz", methods=["GET"]) def healthz(): try: conn = db.get_connection() try: with conn.cursor() as cur: cur.execute("SELECT 1") finally: conn.close() return jsonify({"status": "ok"}), 200 except Exception: return jsonify({"status": "degraded"}), 503 # ============================================================ # Legacy HTML & SACK AJAX Endpoints # ============================================================ def _render_state_html(country_id_raw: str, state_id_raw: str, other_state: str, is_permanent: bool) -> str: name = "p_state" if is_permanent else "state" other_name = "other_p_state" if is_permanent else "other_state" onchange_fn = "p_getCity" if is_permanent else "getCity" if country_id_raw in ("", "38"): selected_state = state_id_raw or ("12" if country_id_raw == "" else "") states = db.get_states_by_country(38) options = [''] for st in states: sel = " selected" if str(st["id"]) == str(selected_state) else "" options.append(f'') return ( f'" ) safe_val = html.escape(other_state or "") return f'' def _render_city_html(country_id_raw: str, state_id_raw: str, city_id_raw: str, other_city: str, is_permanent: bool) -> str: name = "p_city" if is_permanent else "city" other_name = "other_p_city" if is_permanent else "other_city" if country_id_raw in ("", "38"): effective_state = state_id_raw selected_city = city_id_raw if country_id_raw == "" and state_id_raw == "": effective_state = "12" if not selected_city: selected_city = "289" cities = db.get_cities_by_state(int(effective_state)) if effective_state.isdigit() else [] options = [''] for ct in cities: sel = " selected" if str(ct["id"]) == str(selected_city) else "" options.append(f'') return f'" safe_val = html.escape(other_city or "") return f'' @app.route("/", methods=["GET"]) @app.route("/index.php", methods=["GET"]) def index(): return render_template("index.html") @app.route("/captcha-image", methods=["GET"]) def legacy_captcha_image(): if _is_rate_limited("captcha", 60): return jsonify({"error": "Too many requests"}), 429 code = "".join(random.choices(string.ascii_letters, k=4)) session["captcha"] = code return jsonify({"imageDataUrl": _render_captcha_png_b64(code)}), 200 @app.route("/getState.php", methods=["GET", "POST"]) def get_state(): return _render_state_html( request.values.get("countryId", "").strip(), request.values.get("stateId", "").strip(), request.values.get("other_state", "").strip(), is_permanent=False, ) @app.route("/getCity.php", methods=["GET", "POST"]) def get_city(): return _render_city_html( request.values.get("countryId", "").strip(), request.values.get("stateId", "").strip(), request.values.get("cityId", "").strip(), request.values.get("other_city", "").strip(), is_permanent=False, ) @app.route("/p_getState.php", methods=["GET", "POST"]) def p_get_state(): return _render_state_html( request.values.get("countryId", "").strip(), request.values.get("stateId", "").strip(), request.values.get("other_state", "").strip(), is_permanent=True, ) @app.route("/p_getCity.php", methods=["GET", "POST"]) def p_get_city(): return _render_city_html( request.values.get("countryId", "").strip(), request.values.get("stateId", "").strip(), request.values.get("cityId", "").strip(), request.values.get("other_city", "").strip(), is_permanent=True, ) @app.route("/getDOB.php", methods=["GET", "POST"]) def get_dob(): age_raw = (request.values.get("age") or "").strip() unit = (request.values.get("ageUnit") or "years").strip().lower() if not age_raw.isdigit() or int(age_raw) <= 0: return "", 400 age = int(age_raw) today = date.today() try: if unit == "years": if age > 120: return "", 400 try: dob = today.replace(year=today.year - age) except ValueError: dob = today.replace(year=today.year - age, day=28) elif unit == "months": if age > 1440: return "", 400 total_months = today.year * 12 + (today.month - 1) - age year, month_zero = divmod(total_months, 12) month = month_zero + 1 days_in_month = [31, 29 if year % 4 == 0 and (year % 100 != 0 or year % 400 == 0) else 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] dob = date(year, month, min(today.day, days_in_month)) elif unit == "weeks": if age > 6260: return "", 400 dob = today - timedelta(weeks=age) elif unit == "days": if age > 43800: return "", 400 dob = today - timedelta(days=age) else: return "", 400 except (OverflowError, ValueError): return "", 400 return dob.strftime("%d/%m/%Y") @app.route("/uploadProxy.php", methods=["POST"]) def upload_proxy(): if _is_rate_limited("upload_proxy", 20): return render_template("error.html", errors=["Too many registration attempts. Please try again shortly."]), 429 cleaned, errors = validate_registration( request.form, request.files, session_captcha=session.get("captcha"), ) if errors: return render_template("error.html", errors=errors), 400 ptn_photo_file = cleaned.pop("ptnPhoto_file") id_file_obj = cleaned.pop("id_file_obj") # Enforce magic-byte, size, dimension, EXIF strip & malware scan on legacy path too try: photo_meta = process_staged_upload( raw_bytes=ptn_photo_file.read(), category="PHOTO", upload_root=app.config["UPLOAD_FOLDER"], session_id="legacy", ) kyc_meta = process_staged_upload( raw_bytes=id_file_obj.read(), category="KYC", upload_root=app.config["UPLOAD_FOLDER"], session_id="legacy", doc_type_id=cleaned["doc_type"], ) except UploadValidationError as exc: return render_template("error.html", errors=[exc.message]), exc.status_code if exc.status_code in (400, 413) else 400 # Consume legacy session captcha after validation session.pop("captcha", None) def _move_to_ref_dir(ref_id: str) -> tuple[str, str]: ref_dir = os.path.join(app.config["UPLOAD_FOLDER"], ref_id) os.makedirs(ref_dir, exist_ok=True) photo_name = f"photo_{os.path.basename(photo_meta['storage_key'])}" kyc_name = f"kyc_{os.path.basename(kyc_meta['storage_key'])}" shutil.move(os.path.join(app.config["UPLOAD_FOLDER"], photo_meta["storage_key"]), os.path.join(ref_dir, photo_name)) shutil.move(os.path.join(app.config["UPLOAD_FOLDER"], kyc_meta["storage_key"]), os.path.join(ref_dir, kyc_name)) return f"{ref_id}/{photo_name}", f"{ref_id}/{kyc_name}" try: ref_id = db.save_registration(cleaned, save_files_cb=_move_to_ref_dir) except Exception: corr = str(uuid.uuid4()) app.logger.exception("Registration save failed correlation_id=%s", corr) for meta in (photo_meta, kyc_meta): p = os.path.join(app.config["UPLOAD_FOLDER"], meta["storage_key"]) if os.path.exists(p): os.remove(p) return render_template("error.html", errors=[f"Unable to save registration at this time (Ref: {corr})."]), 500 return render_template("success.html", reference_form_id=ref_id) # ============================================================ # Modernized /api/v1 REST Endpoints # ============================================================ def _api_error(code: str, message: str, status: int, errors: list[dict] | None = None): body = {"success": False, "code": code, "message": message} if errors is not None: body["errors"] = errors return jsonify(body), status @app.route("/api/v1/registration-sessions", methods=["POST"]) def api_create_session(): if _is_rate_limited("sessions", 60): return _api_error("RATE_LIMITED", "Too many session requests.", 429) data = db.create_registration_session() return jsonify({"success": True, "data": data}), 201 @app.route("/api/v1/captcha", methods=["GET"]) def api_get_captcha(): if _is_rate_limited("captcha", 60): return _api_error("RATE_LIMITED", "Too many CAPTCHA requests.", 429) session_id = request.args.get("sessionId") or request.headers.get("X-Session-Id", "") if not session_id: return _api_error("BAD_REQUEST", "sessionId is required.", 400) code = "".join(random.choices(string.ascii_letters, k=4)) challenge = db.create_captcha_challenge(session_id, code) # Never return plaintext CAPTCHA answer in API response return jsonify({"success": True, "data": {**challenge, "imageDataUrl": _render_captcha_png_b64(code)}}), 200 @app.route("/api/v1/masters/registration-options", methods=["GET"]) def api_master_options(): return jsonify({ "success": True, "data": { "titles": db.get_master_list("titles"), "genders": db.get_master_list("genders"), "relations": db.get_master_list("relations"), "docTypes": db.get_master_list("doc-types"), "countries": db.get_master_list("countries"), "defaults": {"countryId": 38, "stateId": 12, "cityId": 289}, }, }), 200 @app.route("/api/v1/masters/", methods=["GET"]) def api_master_by_type(master_type: str): items = db.get_master_list(master_type) if items is None: return _api_error("NOT_FOUND", "Unknown master type.", 404) return jsonify({"success": True, "data": items}), 200 @app.route("/api/v1/masters/states", methods=["GET"]) def api_master_states(): cid = request.args.get("countryId", "38") if not cid.isdigit(): return _api_error("BAD_REQUEST", "Invalid countryId.", 400) return jsonify({"success": True, "data": db.get_states_by_country(int(cid))}), 200 @app.route("/api/v1/masters/cities", methods=["GET"]) def api_master_cities(): sid = request.args.get("stateId", "") if not sid.isdigit(): return _api_error("BAD_REQUEST", "Invalid stateId.", 400) return jsonify({"success": True, "data": db.get_cities_by_state(int(sid))}), 200 @app.route("/api/v1/uploads", methods=["POST"]) def api_upload_staged(): if _is_rate_limited("uploads", 30): return _api_error("RATE_LIMITED", "Too many upload requests.", 429) session_id = (request.form.get("sessionId") or request.headers.get("X-Session-Id") or "").strip() category = (request.form.get("category") or "").strip() doc_type_raw = (request.form.get("docTypeId") or "").strip() file_obj = request.files.get("file") if not session_id: return _api_error("BAD_REQUEST", "sessionId is required.", 400) if not file_obj: return _api_error("VALIDATION_ERROR", "File is required.", 422) doc_type_id = int(doc_type_raw) if doc_type_raw.isdigit() else None try: meta = process_staged_upload( raw_bytes=file_obj.read(), category=category, upload_root=app.config["UPLOAD_FOLDER"], session_id=session_id, doc_type_id=doc_type_id, ) db.save_staged_upload(meta) except UploadValidationError as exc: return _api_error("UPLOAD_ERROR", exc.message, exc.status_code) return jsonify({ "success": True, "data": {"uploadId": meta["id"], "scanStatus": meta["scan_status"], "mimeType": meta["mime_type"]}, }), 201 @app.route("/api/v1/uploads/", methods=["DELETE"]) def api_delete_staged_upload(upload_id: str): session_id = request.args.get("sessionId") or request.headers.get("X-Session-Id", "") if not session_id: return _api_error("BAD_REQUEST", "sessionId is required.", 400) storage_key = db.delete_staged_upload(upload_id, session_id) if not storage_key: return _api_error("NOT_FOUND", "Upload not found or not owned by session.", 404) full_path = os.path.join(app.config["UPLOAD_FOLDER"], storage_key) if os.path.exists(full_path): os.remove(full_path) return jsonify({"success": True}), 200 @app.route("/api/v1/registrations", methods=["POST"]) def api_create_registration(): if _is_rate_limited("registrations", 20): return _api_error("RATE_LIMITED", "Too many registration requests.", 429) payload = request.get_json(silent=True) if not isinstance(payload, dict): return _api_error("BAD_REQUEST", "JSON payload is required.", 400) session_id = str(payload.get("sessionId") or request.headers.get("X-Session-Id") or "").strip() idem_key = str(request.headers.get("Idempotency-Key") or "").strip() if not session_id or not idem_key: return _api_error("BAD_REQUEST", "sessionId and Idempotency-Key header are required.", 400) fp_payload = {k: v for k, v in payload.items() if k != "captcha"} fingerprint = hashlib.sha256(json.dumps(fp_payload, sort_keys=True).encode("utf-8")).hexdigest() # 1. Replay check BEFORE field validation / CAPTCHA consumption conn = db.get_connection() try: with conn.cursor() as cur: idem = db.check_or_reserve_idempotency(cur, session_id, idem_key, fingerprint) if idem["state"] == "CONFLICT": conn.rollback() return _api_error("IDEMPOTENCY_CONFLICT", "Idempotency-Key reused with different payload.", 409) if idem["state"] == "COMPLETED": conn.rollback() return jsonify(idem["response"]), idem["http_status"] if idem["state"] == "IN_PROGRESS": conn.rollback() return _api_error("CONFLICT", "Registration request already in progress.", 409) # 2. Validate fields BEFORE consuming CAPTCHA so validation errors don't burn CAPTCHA or trap key cleaned, errors = validate_core_fields(payload, skip_captcha=True) if errors: db.release_idempotency_reservation(cur, session_id, idem_key) conn.commit() return _api_error( "VALIDATION_ERROR", "Validation failed.", 422, [{"field": "form", "message": msg} for msg in errors], ) photo_upload_id = str(payload.get("photoUploadId") or "").strip() kyc_upload_id = str(payload.get("kycUploadId") or "").strip() if not photo_upload_id or not kyc_upload_id or photo_upload_id == kyc_upload_id: db.release_idempotency_reservation(cur, session_id, idem_key) conn.commit() return _api_error("VALIDATION_ERROR", "Distinct photoUploadId and kycUploadId are required.", 422) # 3. Verify & consume single-use CAPTCHA captcha = payload.get("captcha") or {} if not db.verify_and_consume_captcha( cur, session_id, str(captcha.get("challengeId") or ""), str(captcha.get("answer") or "") ): db.release_idempotency_reservation(cur, session_id, idem_key) conn.commit() return _api_error("VALIDATION_ERROR", "Invalid or expired CAPTCHA.", 422, [{"field": "captcha", "message": "Invalid or expired CAPTCHA."}]) conn.commit() finally: conn.close() try: status_code, body = db.save_registration_v1( cleaned=cleaned, session_id=session_id, idempotency_key=idem_key, payload_fingerprint=fingerprint, photo_upload_id=photo_upload_id, kyc_upload_id=kyc_upload_id, ) return jsonify(body), status_code except ValueError as exc: conn2 = db.get_connection() try: with conn2.cursor() as cur2: db.release_idempotency_reservation(cur2, session_id, idem_key) conn2.commit() finally: conn2.close() return _api_error("VALIDATION_ERROR", str(exc), 422) @app.route("/api/v1/registrations//status", methods=["GET"]) def api_registration_status(reference: str): session_id = request.headers.get("X-Session-Id") or request.args.get("sessionId") if not session_id: return _api_error("UNAUTHORIZED", "Session or access token required.", 401) row = db.get_registration_status_by_ref(reference) if not row: return _api_error("NOT_FOUND", "Registration not found.", 404) if not row["session_id"] or row["session_id"] != session_id: return _api_error("FORBIDDEN", "Not authorized to access this registration.", 403) return jsonify({ "success": True, "data": { "registrationReference": row["reference_form_id"], "status": row["status"], "hospitalPatientId": row["hospital_patient_id"], "emailStatus": row["email_status"], }, }), 200 # ============================================================ # Staff / Admin Endpoints (SSO Token + DB-Backed RBAC) # ============================================================ def _require_admin_role(*allowed_roles: str): def decorator(fn): @wraps(fn) def wrapper(*args, **kwargs): expected_secret = os.getenv("ADMIN_SSO_SECRET", "dev-admin-sso-token") token = request.headers.get("X-Admin-Token", "") sso_subject = (request.headers.get("X-Admin-Subject") or "").strip() if not token or token != expected_secret or not sso_subject: return _api_error("UNAUTHORIZED", "Valid staff SSO token and subject required.", 401) user = db.get_admin_user(sso_subject) if not user or user["role"] not in allowed_roles: return _api_error("FORBIDDEN", "Insufficient role permissions.", 403) request.admin_user = user return fn(*args, **kwargs) return wrapper return decorator @app.route("/api/v1/admin/registrations", methods=["GET"]) @_require_admin_role("REG_STAFF", "SUPERVISOR", "SYS_ADMIN") def api_admin_list_registrations(): status_filter = request.args.get("status") return jsonify({"success": True, "data": db.list_registrations_admin(status_filter)}), 200 @app.route("/api/v1/admin/registrations//documents/", methods=["GET"]) @_require_admin_role("REG_STAFF", "SUPERVISOR") def api_admin_download_document(reg_id: int, doc_id: str): doc = db.get_registration_document_for_admin(reg_id, doc_id, request.admin_user["sso_subject"]) if not doc: return _api_error("NOT_FOUND", "Document not found.", 404) full_path = os.path.join(app.config["UPLOAD_FOLDER"], doc["storage_key"]) if not os.path.exists(full_path): return _api_error("NOT_FOUND", "Document file missing on disk.", 404) return send_file(full_path, mimetype=doc["mime_type"], as_attachment=True) @app.route("/api/v1/admin/registrations//review", methods=["POST"]) @_require_admin_role("SUPERVISOR") def api_admin_review_registration(reg_id: int): body = request.get_json(silent=True) or {} decision = (body.get("decision") or "").upper() reason = (body.get("reason") or "").strip() uhid = (body.get("hospitalPatientId") or "").strip() or None actor = request.admin_user["sso_subject"] decision_map = { "APPROVE_NEW": "PENDING_HIS_SYNC", "LINK_EXISTING": "LINKED_EXISTING", "REJECT": "REJECTED", } if decision not in decision_map or not reason: return _api_error("VALIDATION_ERROR", "Valid decision and audit reason are required.", 422) if decision == "LINK_EXISTING" and not uhid: return _api_error("VALIDATION_ERROR", "hospitalPatientId is required for LINK_EXISTING.", 422) conn = db.get_connection() try: with conn.cursor() as cur: db.transition_registration_status( cur, reg_id, decision_map[decision], actor, reason=reason, hospital_patient_id=uhid ) if decision == "APPROVE_NEW": cur.execute( """ INSERT INTO outbox_events (id, registration_id, event_type, status, correlation_id) VALUES (%s, %s, 'HIS_CREATE', 'PENDING', %s) """, (str(uuid.uuid4()), reg_id, str(uuid.uuid4())), ) conn.commit() return jsonify({"success": True, "data": {"status": decision_map[decision]}}), 200 except ValueError as exc: conn.rollback() return _api_error("VALIDATION_ERROR", str(exc), 422) finally: conn.close() @app.route("/api/v1/admin/registrations//retry", methods=["POST"]) @_require_admin_role("SUPERVISOR", "SYS_ADMIN") def api_admin_retry_registration(reg_id: int): actor = request.admin_user["sso_subject"] conn = db.get_connection() try: with conn.cursor() as cur: cur.execute("SELECT status FROM patient_registration WHERE id = %s FOR UPDATE", (reg_id,)) row = cur.fetchone() if not row: conn.rollback() return _api_error("NOT_FOUND", "Registration not found.", 404) if row["status"] == "CHECKING_DUPLICATES": event_type = "DUPLICATE_CHECK" next_status = "CHECKING_DUPLICATES" cur.execute( "INSERT INTO audit_logs (registration_id, actor, action, from_status, to_status, reason) VALUES (%s, %s, 'MANUAL_RETRY', %s, %s, %s)", (reg_id, actor, "CHECKING_DUPLICATES", "CHECKING_DUPLICATES", "Manual duplicate check retry"), ) else: next_status = "PENDING_HIS_SYNC" event_type = "HIS_CREATE" db.transition_registration_status( cur, reg_id, next_status, actor, reason="Manual retry requested" ) cur.execute( """ INSERT INTO outbox_events (id, registration_id, event_type, status, correlation_id) VALUES (%s, %s, %s, 'PENDING', %s) """, (str(uuid.uuid4()), reg_id, event_type, str(uuid.uuid4())), ) conn.commit() return jsonify({"success": True, "data": {"status": next_status}}), 200 except ValueError as exc: conn.rollback() return _api_error("VALIDATION_ERROR", str(exc), 422) finally: conn.close() @app.route("/api/v1/admin/audit-logs", methods=["GET"]) @_require_admin_role("SUPERVISOR", "SYS_ADMIN") def api_admin_audit_logs(): reg_id_raw = request.args.get("registrationId", "").strip() if reg_id_raw and not reg_id_raw.isdigit(): return _api_error("BAD_REQUEST", "registrationId must be a positive integer.", 400) reg_id = int(reg_id_raw) if reg_id_raw else None return jsonify({"success": True, "data": db.list_audit_logs_admin(reg_id)}), 200 if __name__ == "__main__": debug_flag = os.getenv("FLASK_DEBUG", "false").strip().lower() in ("1", "true", "yes") app.run(debug=debug_flag, host="127.0.0.1", port=5000)