"""Flask application factory and DB setup.""" from __future__ import annotations import hmac import os import secrets from pathlib import Path from flask import Flask, abort, g, redirect, render_template, request, session, url_for from physcom.db.schema import init_db from physcom.db.repository import Repository from physcom.units import format_quantity DEFAULT_DB = Path("data/physcom.db") # Everything a read-only visitor may not reach. Writes (any non-GET) are # locked separately, except the purely exploratory results.explore. ADMIN_GET_ENDPOINTS = {"pipeline.pipeline_form", "entities.entity_new", "domains.domain_new"} PUBLIC_POST_ENDPOINTS = {"results.explore", "login"} def db_path() -> Path: return Path(os.environ.get("PHYSCOM_DB", str(DEFAULT_DB))) def _secret_key() -> str: """FLASK_SECRET_KEY, else a key persisted next to the DB so admin sessions survive restarts.""" key = os.environ.get("FLASK_SECRET_KEY") if key: return key path = db_path().parent / ".secret_key" try: return path.read_text().strip() except FileNotFoundError: key = secrets.token_hex(32) path.parent.mkdir(parents=True, exist_ok=True) path.write_text(key) return key def is_admin() -> bool: from flask import current_app return session.get("admin", False) def get_repo() -> Repository: """Return a Repository scoped to the current request.""" if "repo" not in g: conn = init_db(db_path()) g.repo = Repository(conn) return g.repo def close_db(exc: BaseException | None = None) -> None: repo: Repository | None = g.pop("repo", None) if repo is not None: repo.conn.close() def create_app() -> Flask: """Read-only to visitors; writes need a login with PHYSCOM_ADMIN_TOKEN (no token set = no one can write).""" app = Flask(__name__) app.secret_key = _secret_key() admin_token = os.environ.get("PHYSCOM_ADMIN_TOKEN", "") app.config.update( SESSION_COOKIE_SAMESITE="Lax", SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SECURE=os.environ.get("PHYSCOM_SECURE_COOKIES") == "1", ) app.jinja_env.globals["is_admin"] = is_admin @app.before_request def require_admin(): if is_admin() or request.endpoint in (None, "static"): return None blueprint = request.endpoint.split(".")[0] if request.method in ("GET", "HEAD"): if blueprint == "admin" or request.endpoint in ADMIN_GET_ENDPOINTS: return redirect(url_for("login", next=request.path)) return None if request.endpoint not in PUBLIC_POST_ENDPOINTS: abort(403) return None @app.route("/login", methods=["GET", "POST"]) def login(): error = None if request.method == "POST": given = request.form.get("token", "") if admin_token and hmac.compare_digest(given, admin_token): session.clear() session["admin"] = True session.permanent = True target = request.args.get("next", "") # Only same-site relative paths, never "//evil.com". if not target.startswith("/") or target.startswith("//"): target = url_for("index") return redirect(target) error = "Wrong token." if admin_token else "Admin login is disabled (PHYSCOM_ADMIN_TOKEN not set)." return render_template("login.html", error=error), (401 if error else 200) @app.route("/logout", methods=["POST"]) def logout(): session.clear() return redirect(url_for("index")) app.jinja_env.filters["qty"] = format_quantity app.teardown_appcontext(close_db) # Register blueprints from physcom_web.routes.entities import bp as entities_bp from physcom_web.routes.domains import bp as domains_bp from physcom_web.routes.pipeline import bp as pipeline_bp from physcom_web.routes.results import bp as results_bp from physcom_web.routes.admin import bp as admin_bp app.register_blueprint(entities_bp) app.register_blueprint(domains_bp) app.register_blueprint(pipeline_bp) app.register_blueprint(results_bp) app.register_blueprint(admin_bp) @app.route("/") def index(): repo = get_repo() entities = repo.list_entities() dims = {e.dimension for e in entities} domains = repo.list_domains() status_counts = repo.count_combinations_by_status() stats = { "entities": len(entities), "dimensions": len(dims), "domains": len(domains), "combinations": sum(status_counts.values()), } top_concepts = [] for d in domains: top = repo.get_top_results(d.name, limit=1) if top and top[0]["composite_score"]: top_concepts.append((d, top[0])) return render_template("home.html", stats=stats, top_concepts=top_concepts) return app def run() -> None: """Entry point for `physcom-web` script. Same access rules as production, so localhost shows the public view; without PHYSCOM_ADMIN_TOKEN a one-off token is generated and printed for /login.""" if not os.environ.get("PHYSCOM_ADMIN_TOKEN"): os.environ["PHYSCOM_ADMIN_TOKEN"] = secrets.token_urlsafe(16) print(f" * Admin login token (this run only): {os.environ['PHYSCOM_ADMIN_TOKEN']}") app = create_app() app.run( host=os.environ.get("HOST", "127.0.0.1"), debug=os.environ.get("FLASK_DEBUG") == "1", port=int(os.environ.get("PORT", "5000")), )