feat(api): add FastAPI backend with JWT authentication

REST API serving forecast data with HS256 JWT auth (14-day tokens).
Public: /health, /auth/register, /auth/login.
Protected: /stations, /forecast, /forecast/history, /forecast/{id}, /status.
Includes APScheduler for periodic forecasts and Telegram bot subprocess.
This commit is contained in:
dasemu committed 2026-03-13 09:36:18 +01:00
1 parent c8188e3995
commit 9d97afe538
14 files changed
+1631 -10

No files matched your search

View File
Whitespace-only changes.
+132
View File
@@ -0,0 +1,132 @@
"""JWT authentication: register, login, and token validation."""
from __future__ import annotations
import logging
import os
from datetime import datetime, timedelta, timezone
import jwt
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from passlib.context import CryptContext
from app.api.schemas import TokenResponse, UserCreate, UserResponse
from storage import SQLiteStore
logger = logging.getLogger(__name__)
_TOKEN_EXPIRE_DAYS = 14
_ALGORITHM = "HS256"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/v1/auth/login")
auth_router = APIRouter(prefix="/api/v1/auth", tags=["auth"])
def _get_secret_key() -> str:
key = os.environ.get("JWT_SECRET_KEY")
if not key:
raise RuntimeError("JWT_SECRET_KEY environment variable is not set")
return key
def _create_token(user_id: int, email: str) -> str:
now = datetime.now(timezone.utc)
payload = {
"sub": str(user_id),
"email": email,
"iat": now,
"exp": now + timedelta(days=_TOKEN_EXPIRE_DAYS),
}
return jwt.encode(payload, _get_secret_key(), algorithm=_ALGORITHM)
def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
"""FastAPI dependency that validates the JWT and returns user info."""
try:
payload = jwt.decode(
token, _get_secret_key(), algorithms=[_ALGORITHM]
)
user_id = payload.get("sub")
email = payload.get("email")
if user_id is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="login required",
)
return {"user_id": int(user_id), "email": email}
except jwt.ExpiredSignatureError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="login required",
)
except jwt.InvalidTokenError:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="login required",
)
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@auth_router.post(
"/register",
response_model=UserResponse,
status_code=status.HTTP_201_CREATED,
)
def register(body: UserCreate) -> UserResponse:
"""Create a new user account."""
store = SQLiteStore()
hashed = pwd_context.hash(body.password)
now_iso = datetime.now(timezone.utc).isoformat()
with store.connect() as conn:
existing = conn.execute(
"SELECT id FROM users WHERE email = ?", (body.email,)
).fetchone()
if existing:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="email already registered",
)
cursor = conn.execute(
"""
INSERT INTO users (email, password_hash, created_at)
VALUES (?, ?, ?)
""",
(body.email, hashed, now_iso),
)
user_id = cursor.lastrowid
return UserResponse(id=user_id, email=body.email)
@auth_router.post("/login", response_model=TokenResponse)
def login(form: OAuth2PasswordRequestForm = Depends()) -> TokenResponse:
"""Authenticate and return a JWT token."""
store = SQLiteStore()
with store.connect() as conn:
row = conn.execute(
"SELECT id, email, password_hash FROM users WHERE email = ?",
(form.username,),
).fetchone()
if row is None or not pwd_context.verify(form.password, row["password_hash"]):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="invalid credentials",
)
conn.execute(
"UPDATE users SET last_login_at = ? WHERE id = ?",
(datetime.now(timezone.utc).isoformat(), row["id"]),
)
token = _create_token(row["id"], row["email"])
return TokenResponse(access_token=token)
+277
View File
@@ -0,0 +1,277 @@
"""REST API endpoints for the SkiPredictor backend."""
from __future__ import annotations
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Any
import yaml
from fastapi import APIRouter, Depends, HTTPException, Query
from app.api.auth import get_current_user
from app.api.schemas import (
DayForecast,
ForecastAllResponse,
ForecastHistoryResponse,
ForecastHistoryRun,
ForecastStationResponse,
HealthResponse,
StationForecast,
StationInfo,
StationsResponse,
StatusResponse,
)
from storage import SQLiteStore
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/v1")
_PROJECT_ROOT = Path(__file__).resolve().parents[2]
_STATIONS_YAML = _PROJECT_ROOT / "config" / "stations.yaml"
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
_VALID_STATION_IDS: set[str] | None = None
def _load_stations_config() -> dict[str, Any]:
"""Load and cache the stations YAML configuration."""
with open(_STATIONS_YAML) as fh:
return yaml.safe_load(fh)["stations"]
def _valid_station_ids() -> set[str]:
global _VALID_STATION_IDS
if _VALID_STATION_IDS is None:
_VALID_STATION_IDS = set(_load_stations_config().keys())
return _VALID_STATION_IDS
def _open_label(probability: float) -> str:
if probability >= 0.70:
return "Abierta"
if probability >= 0.40:
return "Probable apertura"
return "Cerrada"
def _get_store() -> SQLiteStore:
return SQLiteStore()
# ---------------------------------------------------------------------------
# Endpoints
# ---------------------------------------------------------------------------
@router.get("/stations", response_model=StationsResponse)
def get_stations(user: dict = Depends(get_current_user)) -> StationsResponse:
"""List all tracked ski stations with metadata."""
cfg = _load_stations_config()
stations = []
for sid, data in cfg.items():
stations.append(
StationInfo(
station_id=sid,
name=data["name"],
max_km=data["max_km_skiable"],
latitude=data["latitude"],
longitude=data["longitude"],
altitude=data["altitude"],
wind_closure_threshold_kmh=data["wind_closure_threshold"],
min_snow_depth_cm=data["minimum_snow_depth"],
)
)
return StationsResponse(stations=stations)
@router.get("/forecast", response_model=ForecastAllResponse)
def get_forecast_all(user: dict = Depends(get_current_user)) -> ForecastAllResponse:
"""Get the latest forecast for all stations."""
store = _get_store()
rows = store.load_current_forecasts()
return _build_forecast_all(rows)
@router.get("/forecast/history", response_model=ForecastHistoryResponse)
def get_forecast_history(
station_id: str | None = Query(None),
date_from: str | None = Query(None),
date_to: str | None = Query(None),
limit: int = Query(50, ge=1, le=200),
offset: int = Query(0, ge=0),
user: dict = Depends(get_current_user),
) -> ForecastHistoryResponse:
"""Get past forecast runs with pagination."""
store = _get_store()
total = store.count_past_forecasts(
station_id=station_id, date_from=date_from, date_to=date_to
)
rows = store.load_past_forecasts(
station_id=station_id,
date_from=date_from,
date_to=date_to,
limit=limit,
offset=offset,
)
runs = [
ForecastHistoryRun(
generated_at=r["generated_at"],
run_hour=r["run_hour"],
prediction_date=r["prediction_date"],
station_id=r["station_id"],
open_probability=r.get("open_probability"),
km_open=r.get("km_open"),
crowd_level=r.get("crowd_level"),
prediction_source=r.get("prediction_source"),
)
for r in rows
]
return ForecastHistoryResponse(
total=total, limit=limit, offset=offset, runs=runs
)
@router.get("/forecast/{station_id}", response_model=ForecastStationResponse)
def get_forecast_station(station_id: str, user: dict = Depends(get_current_user)) -> ForecastStationResponse:
"""Get the latest forecast for a single station."""
valid = _valid_station_ids()
if station_id not in valid:
raise HTTPException(
status_code=404,
detail=f"Station '{station_id}' not found. Valid: {', '.join(sorted(valid))}",
)
store = _get_store()
rows = store.load_current_forecasts(station_id=station_id)
cfg = _load_stations_config()
generated_at = rows[0]["generated_at"] if rows else None
run_hour = rows[0]["run_hour"] if rows else None
station_cfg = cfg[station_id]
max_km = station_cfg["max_km_skiable"]
days = _rows_to_day_forecasts(rows, max_km)
return ForecastStationResponse(
generated_at=generated_at,
run_hour=run_hour,
station_id=station_id,
name=station_cfg["name"],
days=days,
)
@router.get("/health", response_model=HealthResponse)
def get_health() -> HealthResponse:
"""Health check endpoint."""
return HealthResponse(
status="ok",
timestamp=datetime.now().astimezone().isoformat(),
)
@router.get("/status", response_model=StatusResponse)
def get_status(user: dict = Depends(get_current_user)) -> StatusResponse:
"""System status: last/next forecast run, training info, bot status."""
from app.main import app_state
store = _get_store()
# Last forecast run
forecasts = store.load_current_forecasts()
last_forecast = forecasts[0]["generated_at"] if forecasts else None
# Last training run
last_training: str | None = None
with store.connect() as conn:
row = conn.execute(
"SELECT completed_at FROM training_runs ORDER BY completed_at DESC LIMIT 1"
).fetchone()
if row:
last_training = row["completed_at"]
# Model info
models: dict[str, str] = {}
model_dir = _PROJECT_ROOT / "ml" / "models"
if model_dir.exists():
for model_file in model_dir.glob("*.joblib"):
target = model_file.stem
models[target] = target
# Database size
db_size_mb = 0.0
if store.db_path.exists():
db_size_mb = round(store.db_path.stat().st_size / (1024 * 1024), 1)
return StatusResponse(
last_forecast_run=last_forecast,
next_forecast_run=app_state.get("next_forecast_run"),
last_training_run=last_training,
next_training_run=app_state.get("next_training_run"),
models=models,
telegram_bot_active=app_state.get("bot_active", False),
stations_count=len(_valid_station_ids()),
database_size_mb=db_size_mb,
)
# ---------------------------------------------------------------------------
# Internal helpers
# ---------------------------------------------------------------------------
def _rows_to_day_forecasts(
rows: list[dict[str, Any]], max_km: float
) -> list[DayForecast]:
"""Convert raw DB rows into DayForecast models."""
days = []
for r in rows:
prob = r.get("open_probability")
notes_raw = r.get("rule_notes_json") or "[]"
notes = json.loads(notes_raw) if isinstance(notes_raw, str) else notes_raw
days.append(
DayForecast(
date=r["prediction_date"],
open_probability=prob,
open_label=_open_label(prob) if prob is not None else None,
km_open=r.get("km_open"),
max_km=max_km,
crowd_level=r.get("crowd_level"),
weather_summary=r.get("weather_summary"),
rule_notes=notes,
prediction_source=r.get("prediction_source"),
)
)
return days
def _build_forecast_all(rows: list[dict[str, Any]]) -> ForecastAllResponse:
"""Group raw DB rows by station into the all-stations response."""
cfg = _load_stations_config()
generated_at = rows[0]["generated_at"] if rows else None
run_hour = rows[0]["run_hour"] if rows else None
by_station: dict[str, list[dict[str, Any]]] = {}
for r in rows:
by_station.setdefault(r["station_id"], []).append(r)
stations: dict[str, StationForecast] = {}
for sid, station_rows in by_station.items():
station_cfg = cfg.get(sid, {})
max_km = station_cfg.get("max_km_skiable", 0.0)
stations[sid] = StationForecast(
station_id=sid,
name=station_cfg.get("name", sid),
days=_rows_to_day_forecasts(station_rows, max_km),
)
return ForecastAllResponse(
generated_at=generated_at, run_hour=run_hour, stations=stations
)
+111
View File
@@ -0,0 +1,111 @@
"""Pydantic response models for the SkiPredictor REST API."""
from __future__ import annotations
from pydantic import BaseModel, Field
# -- Stations ---------------------------------------------------------------
class StationInfo(BaseModel):
station_id: str
name: str
max_km: float
latitude: float
longitude: float
altitude: int
wind_closure_threshold_kmh: int
min_snow_depth_cm: int
class StationsResponse(BaseModel):
stations: list[StationInfo]
# -- Forecasts ---------------------------------------------------------------
class DayForecast(BaseModel):
date: str
open_probability: float | None = None
open_label: str | None = None
km_open: float | None = None
max_km: float | None = None
crowd_level: str | None = None
weather_summary: str | None = None
rule_notes: list[str] = Field(default_factory=list)
prediction_source: str | None = None
class StationForecast(BaseModel):
station_id: str
name: str
days: list[DayForecast]
class ForecastAllResponse(BaseModel):
generated_at: str | None = None
run_hour: int | None = None
stations: dict[str, StationForecast]
class ForecastStationResponse(BaseModel):
generated_at: str | None = None
run_hour: int | None = None
station_id: str
name: str
days: list[DayForecast]
# -- Forecast history --------------------------------------------------------
class ForecastHistoryRun(BaseModel):
generated_at: str
run_hour: int
prediction_date: str
station_id: str
open_probability: float | None = None
km_open: float | None = None
crowd_level: str | None = None
prediction_source: str | None = None
class ForecastHistoryResponse(BaseModel):
total: int
limit: int
offset: int
runs: list[ForecastHistoryRun]
# -- System ------------------------------------------------------------------
class HealthResponse(BaseModel):
status: str
timestamp: str
class StatusResponse(BaseModel):
last_forecast_run: str | None = None
next_forecast_run: str | None = None
last_training_run: str | None = None
next_training_run: str | None = None
models: dict[str, str] = Field(default_factory=dict)
telegram_bot_active: bool = False
stations_count: int = 0
database_size_mb: float = 0.0
# -- Auth -------------------------------------------------------------------
class UserCreate(BaseModel):
email: str = Field(..., min_length=3)
password: str = Field(..., min_length=8)
class UserResponse(BaseModel):
id: int
email: str
class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"