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

+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)