084fe2e8d3
Cookie session with /auth/login, /auth/logout and /auth/me. Four accounts come from WEBAPI_USUARIOS (admin plus one per domain) and a second before_request answers 403 when an account asks for another domain. The data suites run with WEBAPI_AUTH_REQUIRED=0; test_auth.py turns the lock back on and covers both hooks. The Dockerfile normalises the entrypoint so a Windows checkout still starts the container.
138 lines
6.1 KiB
Python
138 lines
6.1 KiB
Python
import datetime as _dt
|
|
import logging
|
|
import os
|
|
import secrets
|
|
from decimal import Decimal
|
|
|
|
from flask import Flask, jsonify
|
|
from flask.json.provider import DefaultJSONProvider
|
|
|
|
from webapi.blueprints.auth import auth_bp, exigir_dominio, exigir_sesion
|
|
from webapi.blueprints.cacu import cacu_bp
|
|
from webapi.blueprints.data import data_bp
|
|
from webapi.blueprints.governance import governance_bp
|
|
from webapi.blueprints.imports import imports_bp
|
|
from webapi.blueprints.reports import reports_bp
|
|
from webapi.cama_analysis.routes import analysis_blueprint as cama_analysis_blueprint
|
|
from webapi.cama_follow_up.routes import follow_up_blueprint as cama_follow_up_blueprint
|
|
from webapi.follow_up.routes import follow_up_blueprint
|
|
|
|
|
|
class IsoJSONProvider(DefaultJSONProvider):
|
|
"""ISO-8601 dates (Flask's default is RFC 822); files are never sent
|
|
inline in JSON, only their size."""
|
|
|
|
@staticmethod
|
|
def default(o):
|
|
if isinstance(o, (_dt.datetime, _dt.date, _dt.time)):
|
|
return o.isoformat()
|
|
if isinstance(o, Decimal):
|
|
return float(o)
|
|
if isinstance(o, (bytes, bytearray)):
|
|
return f"<{len(o)} bytes>"
|
|
return DefaultJSONProvider.default(o)
|
|
|
|
|
|
def create_app() -> Flask:
|
|
app = Flask(__name__)
|
|
app.json = IsoJSONProvider(app)
|
|
from webapi.cama_runtime import configure_cama_cohort
|
|
|
|
configure_cama_cohort(app)
|
|
# File sources travel inside the request; cap them per request.
|
|
app.config["MAX_CONTENT_LENGTH"] = int(os.environ.get("WEBAPI_MAX_UPLOAD_MB", "200")) * 1024 * 1024
|
|
|
|
# Session cookie: the login lives in it, so it needs a stable key. Without
|
|
# WEBAPI_SECRET_KEY each process would sign with its own random key and a
|
|
# login would break on the next gunicorn worker (the Dockerfile sets one);
|
|
# in that case the session dies when the process restarts.
|
|
clave = os.environ.get("WEBAPI_SECRET_KEY")
|
|
if not clave:
|
|
clave = secrets.token_hex(32)
|
|
logging.getLogger(__name__).warning(
|
|
"WEBAPI_SECRET_KEY sin definir: la sesión no sobrevive a un reinicio "
|
|
"ni es válida entre varios workers de gunicorn"
|
|
)
|
|
app.secret_key = clave
|
|
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
|
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
|
# Eight hours: a working day, no re-login in the middle of a session.
|
|
app.config["PERMANENT_SESSION_LIFETIME"] = _dt.timedelta(hours=8)
|
|
|
|
# The web client goes through a proxy; browser clients on other origins
|
|
# are allowed with WEBAPI_CORS_ORIGINS (comma-separated). Credentials so
|
|
# that a cross-origin client can also carry the session cookie.
|
|
cors_origins = os.environ.get("WEBAPI_CORS_ORIGINS")
|
|
if cors_origins:
|
|
from flask_cors import CORS
|
|
|
|
CORS(app, origins=[origin.strip() for origin in cors_origins.split(",")], supports_credentials=True)
|
|
|
|
# One hook for the whole application: every route answers 401 without a
|
|
# session, except the login routes and `health`/`api` (see blueprints.auth).
|
|
app.before_request(exigir_sesion)
|
|
# And 403 when the account asks for a domain that is not its own.
|
|
app.before_request(exigir_dominio)
|
|
|
|
@app.get("/health")
|
|
def health():
|
|
return {"status": "ok"}
|
|
|
|
@app.get("/api")
|
|
def api_index():
|
|
"""Every route with its methods and summary, for programmatic clients."""
|
|
routes = []
|
|
for rule in sorted(app.url_map.iter_rules(), key=lambda r: r.rule):
|
|
if rule.endpoint == "static":
|
|
continue
|
|
doc = (app.view_functions[rule.endpoint].__doc__ or "").strip()
|
|
routes.append(
|
|
{
|
|
"path": rule.rule,
|
|
"methods": sorted(rule.methods - {"HEAD", "OPTIONS"}),
|
|
"summary": " ".join(doc.split("\n\n")[0].split()),
|
|
}
|
|
)
|
|
return jsonify({"routes": routes})
|
|
|
|
@app.errorhandler(413)
|
|
def too_large(_exc):
|
|
limit_mb = app.config["MAX_CONTENT_LENGTH"] // (1024 * 1024)
|
|
return jsonify({"error": f"la solicitud excede {limit_mb} MB"}), 413
|
|
|
|
app.register_blueprint(auth_bp, url_prefix="/auth")
|
|
app.register_blueprint(cacu_bp, url_prefix="/cacu")
|
|
app.register_blueprint(imports_bp, url_prefix="/imports")
|
|
app.register_blueprint(data_bp, url_prefix="/data")
|
|
app.register_blueprint(governance_bp, url_prefix="/governance")
|
|
app.register_blueprint(reports_bp, url_prefix="/reportes")
|
|
# The measures, answered on request from dbt's semantic definitions: the deployment ships their manifest.
|
|
if os.environ.get("DBT_MANIFEST"):
|
|
from importlib import import_module
|
|
from pathlib import Path
|
|
|
|
from webapi.fhir import fhir_blueprint
|
|
from webapi.kpis import kpis_blueprint
|
|
|
|
for domain in ("cacu", "cama", "tea"):
|
|
repositories, manifest = import_module(f"persistance.{domain}"), Path(os.environ["DBT_MANIFEST"])
|
|
app.register_blueprint(kpis_blueprint(domain, repositories, manifest), url_prefix=f"/{domain}")
|
|
# The same measures in FHIR R4, with TEA's patient summary (simulated data, marked in every response).
|
|
app.register_blueprint(fhir_blueprint(domain, repositories, manifest, with_patients=True),
|
|
url_prefix=f"/{domain}/fhir")
|
|
# Patient-level follow-up list and individual risk, marked `simulado` in every response. Who may see them is
|
|
# an access rule still to be defined, not an environment variable.
|
|
from persistance import cacu as cacu_repositories
|
|
from persistance.db import get_cacu_session, get_cama_session
|
|
|
|
from webapi.patient_risk import patient_risk_blueprint
|
|
from webapi.risk_batches import risk_batches_blueprint
|
|
|
|
app.register_blueprint(follow_up_blueprint(get_cacu_session), url_prefix="/cacu")
|
|
app.register_blueprint(cama_follow_up_blueprint(get_cama_session), url_prefix="/cama")
|
|
app.register_blueprint(cama_analysis_blueprint(get_cama_session), url_prefix="/cama/analisis")
|
|
app.register_blueprint(patient_risk_blueprint(cacu_repositories), url_prefix="/cacu")
|
|
app.register_blueprint(risk_batches_blueprint(cacu_repositories), url_prefix="/cacu")
|
|
|
|
return app
|