From 306e21fe44b21d17931fb7fb07d4baca77c65108 Mon Sep 17 00:00:00 2001 From: Joao Carreira Date: Tue, 6 Oct 2026 13:05:09 +0100 Subject: [PATCH] feat: allow reverse proxies --- .env.example | 7 ++- Dockerfile | 4 +- Makefile | 2 +- README.md | 2 + app/config.py | 20 +++++++++ app/main.py | 5 ++- app/templates/admin_assign.html | 12 ++--- app/templates/admin_schedule.html | 28 ++++++------ app/templates/admin_schedules.html | 4 +- app/templates/admin_user_delete.html | 6 +-- app/templates/admin_users.html | 6 +-- app/templates/base.html | 16 +++---- app/templates/dashboard.html | 10 ++--- app/templates/login.html | 2 +- app/templates/schedule.html | 4 +- app/templates/schedules.html | 4 +- app/templates/swap_new.html | 8 ++-- app/templates/swaps.html | 11 ++--- app/web.py | 2 +- docker-compose.dev.yml | 2 +- docs/DOMAIN.md | 1 + tests/test_admin_schedule_assignments.py | 4 +- tests/test_public_schedules.py | 57 ++++++++++++++++++++++++ 23 files changed, 153 insertions(+), 64 deletions(-) diff --git a/.env.example b/.env.example index 16daa4e..2e458ea 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,11 @@ APP_NAME=Contínuos CRR SECRET_KEY=replace-with-a-long-random-value DATABASE_URL=sqlite:///./data/bar_rota.db BASE_URL=http://localhost:8000 + +# Behind a reverse proxy: the public address of the app, used in notification e-mails. +# ROOT_PATH is the prefix the proxy serves us under, e.g. /crr for https://host/crr/. +# Leave it empty when the app is at the root of the domain. +ROOT_PATH= PORT=8000 # Host directory bind-mounted at /app/data (used by docker compose only). @@ -25,5 +30,5 @@ SMTP_STARTTLS=true # Reminder command looks this many days ahead. REMINDER_DAYS_AHEAD=1 -# Set true when the app is served only over HTTPS. +# Set true when the app is served only over HTTPS (always true behind a TLS proxy). SESSION_HTTPS_ONLY=false diff --git a/Dockerfile b/Dockerfile index 6b1f3b5..80b40c5 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,7 +10,7 @@ RUN pip install --no-cache-dir -r requirements.txt COPY . . RUN mkdir -p /app/data EXPOSE 8000 -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips", "*"] # Development image: base plus dev dependencies. Used by docker-compose.dev.yml, # which supplies the reload command and per-service environment. @@ -18,7 +18,7 @@ FROM base AS dev COPY requirements-dev.txt ./ RUN pip install --no-cache-dir -r requirements-dev.txt -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"] +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload", "--proxy-headers", "--forwarded-allow-ips", "*"] # Keep plain `docker build .` on the production runtime as well. FROM base AS production diff --git a/Makefile b/Makefile index c72214b..64c2c8a 100644 --- a/Makefile +++ b/Makefile @@ -39,7 +39,7 @@ dev-setup: setup # Host run with auto-reload, for fast debugging. dev: setup @test -x $(PYTHON) || (echo "Run 'make dev-setup' first." && exit 1) - $(PYTHON) -m uvicorn app.main:app --reload --port $(PORT) + $(PYTHON) -m uvicorn app.main:app --reload --port $(PORT) --proxy-headers --forwarded-allow-ips '*' # Full app in Docker with bind mounts and auto-reload. dev-up: setup diff --git a/README.md b/README.md index 2771825..7077077 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,8 @@ docker compose ps # includes the HTTP healthcheck status To move to another machine, stop the app, copy the **entire `data/` directory** and your `.env` configuration to the new project checkout, then run the deployment command there. Keep these private files out of Git and Docker images. Stopping the app before copying also avoids copying an active SQLite database mid-write. +Behind a reverse proxy, set `BASE_URL` to the public address (used in e-mail links), `ROOT_PATH` to the prefix the app is served under when it is not at the domain root (for example `/crr` for `https://host/crr/`), and `SESSION_HTTPS_ONLY=true` when the proxy terminates TLS. Uvicorn runs with `--proxy-headers --forwarded-allow-ips '*'`, so `X-Forwarded-Proto`/`X-Forwarded-Host` set the scheme and host used in generated URLs and cookies; the proxy must forward them and keep the prefix it advertises. + `DATA_DIR` changes the Docker host directory mounted at `/app/data`. Keep `DATABASE_URL=sqlite:///./data/bar_rota.db` in Docker: this path is relative to `/app` inside the container. For seamless switching between host and Docker, use the default `DATA_DIR=./data`; a custom directory requires a matching host `DATABASE_URL` when running locally. The port for Make development commands is selected with `PORT=...`; direct Compose commands use `.env`'s `PORT`. Update `BASE_URL` when changing the URL used in notification links. ## Email diff --git a/app/config.py b/app/config.py index 23fd05c..692baf0 100644 --- a/app/config.py +++ b/app/config.py @@ -8,6 +8,11 @@ class Settings(BaseSettings): secret_key: str = "dev-only-change-me" database_url: str = "sqlite:///./data/bar_rota.db" base_url: str = "http://localhost:8000" + # Prefix the reverse proxy serves the app under, e.g. "/crr" for https://host/crr/. + # The proxy must forward that prefix (X-Forwarded-Prefix) or the paths here must match. + root_path: str = "" + # Networks allowed to set X-Forwarded-*; "*" for a private docker network. + trusted_proxy_hosts: str = "*" initial_admin_name: str = "Administrador" initial_admin_username: str = "admin" @@ -31,5 +36,20 @@ class Settings(BaseSettings): def normalized_base_url(self) -> str: return self.base_url.rstrip("/") + @property + def prefix(self) -> str: + """The path the reverse proxy serves the app under, without a trailing slash.""" + return self.root_path.rstrip("/") + + def url(self, path: str) -> str: + """Prefix an internal path so it keeps working under a sub-path deployment.""" + if not self.prefix or not path.startswith("/") or path.startswith("//"): + return path + cut = min( + (index for index in (path.find("?"), path.find("#")) if index != -1), + default=len(path), + ) + return f"{self.prefix}{path[:cut]}{path[cut:]}" + settings = Settings() diff --git a/app/main.py b/app/main.py index 8e53c98..f466a85 100644 --- a/app/main.py +++ b/app/main.py @@ -46,7 +46,9 @@ async def lifespan(app: FastAPI): yield -app = FastAPI(title=settings.app_name, lifespan=lifespan) +app = FastAPI(title=settings.app_name, lifespan=lifespan, root_path=settings.root_path) +# Behind a reverse proxy, uvicorn runs with --proxy-headers so X-Forwarded-Proto/Host +# set the public scheme and host; ROOT_PATH adds the prefix the proxy serves us under. app.add_middleware( SessionMiddleware, secret_key=settings.secret_key, @@ -70,5 +72,6 @@ templates.env.filters.update( "evento": event_type_label, } ) +templates.env.globals["app_path"] = settings.url app.state.templates = templates app.include_router(router) diff --git a/app/templates/admin_assign.html b/app/templates/admin_assign.html index b24010a..4d058fe 100644 --- a/app/templates/admin_assign.html +++ b/app/templates/admin_assign.html @@ -3,26 +3,26 @@ {% block content %}
-

Escalas

+

Escalas

Atribuição por dia

Escolha o dia e a pessoa que fica com cada turno. É uma atribuição direta, não uma troca.

-
+
- ← Dia anterior - Hoje - Dia seguinte → + ← Dia anterior + Hoje + Dia seguinte →

{{ day|dia_longo }}

{% for row in shifts %} -
+
diff --git a/app/templates/admin_schedule.html b/app/templates/admin_schedule.html index 18f5813..e3c4674 100644 --- a/app/templates/admin_schedule.html +++ b/app/templates/admin_schedule.html @@ -3,11 +3,11 @@ {% set schedule = card.schedule %}
-

Escalas

+

Escalas

{{ schedule.name }}

{{ card.kind_label }}{% if schedule.label_time %} · {{ schedule.label_time }}{% endif %}

- + @@ -20,24 +20,24 @@

{{ month_name }} {{ year }}

Pré-preenchido com a ordem da rotação abaixo. Alterar uma data nunca reescreve as outras.

- +

Cada turno automático é dado à próxima pessoa ativa a seguir à responsável pelo turno anterior desta escala, com retorno ao início da rotação. Aplicar a rotação mantém as atribuições manuais e as trocas concluídas. Recalcular substitui a atribuição de uma data, incluindo uma atribuição manual ou uma troca. Uma rotação vazia deixa os turnos automáticos sem atribuição.

-
+

Cria os turnos em falta e atualiza as atribuições automáticas depois da data de referência, até à data final (inclusive). As atribuições manuais e as trocas concluídas são mantidas e usadas como referência.

-
+
@@ -48,7 +48,7 @@
{% for assignment in assignments %} - + {% endfor %} @@ -65,14 +65,14 @@
  • {{ member.user.name }}
    -
    -
    -
    +
    +
    +
  • {% else %}
  • Ainda não há membros.
  • {% endfor %} - + @@ -81,7 +81,7 @@ {% else %}

    Repete todos os meses

    - +
    {% for day in pattern_days %} @@ -112,7 +112,7 @@ {% if item.accepted_by %}, aceite por {{ item.accepted_by.name }}{% endif %} {% if item.message %}
    “{{ item.message }}”{% endif %}
    - + - Cancelar + Cancelar
    {% endblock %} \ No newline at end of file diff --git a/app/templates/admin_users.html b/app/templates/admin_users.html index 990f1e9..1f1d8bf 100644 --- a/app/templates/admin_users.html +++ b/app/templates/admin_users.html @@ -6,7 +6,7 @@

    Adicionar pessoa

    - +
    @@ -25,7 +25,7 @@ {% for person in users %}
    {{ person.name }} {% if person.can_login %}@{{ person.username }}{% else %}sem login{% endif %}{% if not person.is_active %} · inativa{% endif %} - +
    @@ -41,7 +41,7 @@
    - {% if person.id in removable_ids %}{% endif %} + {% if person.id in removable_ids %}{% endif %}
    {% endfor %} diff --git a/app/templates/base.html b/app/templates/base.html index 31c1961..37f5279 100644 --- a/app/templates/base.html +++ b/app/templates/base.html @@ -11,31 +11,31 @@
    - + {{ settings.app_name }} {% if current_user %} {% else %} - + {% endif %}
    diff --git a/app/templates/dashboard.html b/app/templates/dashboard.html index 2f33b18..ec1aab5 100644 --- a/app/templates/dashboard.html +++ b/app/templates/dashboard.html @@ -5,9 +5,9 @@

    {{ month_name }} {{ year }}

    - {% if current_user %}Pedir troca{% endif %} - ← Anterior - Seguinte → + {% if current_user %}Pedir troca{% endif %} + ← Anterior + Seguinte →
    @@ -32,7 +32,7 @@
    {% if current_user and current_user.is_admin and admin_request %}

    Pedido de {{ admin_request.requester.name }}{% if admin_request.target_assignment %} ({{ admin_request.assignment.date|dia }} por {{ admin_request.target_assignment.date|dia }}){% endif %}{% if admin_request.accepted_by %}, aceite por {{ admin_request.accepted_by.name }}{% endif %}

    -
    + {% if admin_request.accepted_by %} @@ -44,7 +44,7 @@ {% endif %} -
    + diff --git a/app/templates/login.html b/app/templates/login.html index f352066..d659eb4 100644 --- a/app/templates/login.html +++ b/app/templates/login.html @@ -7,7 +7,7 @@

    Entrar

    Use o seu utilizador e a sua palavra-passe da escala.

    - +
    DataPessoaOrigemAção