"""JWT-based authentication with config-file user management.""" import os import logging import secrets from datetime import datetime, timedelta, timezone from pathlib import Path import bcrypt import jwt from dotenv import load_dotenv from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials # ── Config ──────────────────────────────────────────── PROJECT_ROOT = Path(__file__).parent.parent load_dotenv(PROJECT_ROOT / ".env") def _load_jwt_secret() -> str: configured = os.getenv("JWT_SECRET_KEY") if configured: return configured secret_path = Path( os.getenv("JWT_SECRET_FILE", str(PROJECT_ROOT / "config" / ".jwt-secret")) ) try: secret = secret_path.read_text(encoding="utf-8").strip() if secret: return secret except FileNotFoundError: pass secret = secrets.token_urlsafe(48) try: descriptor = os.open(secret_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) except FileExistsError: secret = secret_path.read_text(encoding="utf-8").strip() if secret: return secret raise RuntimeError(f"JWT secret file is empty: {secret_path}") except OSError as exc: raise RuntimeError( "Set JWT_SECRET_KEY because the JWT secret file could not be created: " f"{secret_path}" ) from exc with os.fdopen(descriptor, "w", encoding="utf-8") as secret_file: secret_file.write(secret) logging.getLogger(__name__).warning("Created JWT secret file at %s", secret_path) return secret JWT_SECRET_KEY = _load_jwt_secret() JWT_ALGORITHM = "HS256" JWT_EXPIRE_HOURS = int(os.getenv("JWT_EXPIRE_HOURS", "24")) security = HTTPBearer(auto_error=False) # ── User Loading ─────────────────────────────────────── def _load_users_file(): """Load users from config file. Auto-hash plain-text passwords on first run.""" import json as j config_path = os.getenv( "USERS_CONFIG_PATH", str(Path(__file__).parent.parent / "config" / "users.json") ) with open(config_path, encoding="utf-8") as f: users_raw = j.load(f) # Migrate plain-text passwords to bcrypt hashes (one-time on startup) migrated = False for user in users_raw: if "password_plain" in user and "password" not in user: pw_bytes = user.pop("password_plain").encode("utf-8") user["password"] = bcrypt.hashpw(pw_bytes, bcrypt.gensalt()).decode("utf-8") migrated = True if migrated: with open(config_path, "w", encoding="utf-8") as f: j.dump(users_raw, f, ensure_ascii=False, indent=2) return users_raw _users_db = _load_users_file() def get_user_by_username(username: str): for u in _users_db: if u["id"] == username: return u return None # ── Token Helpers ───────────────────────────────────── def create_access_token(data: dict) -> str: to_encode = data.copy() expire = datetime.now(timezone.utc) + timedelta(hours=JWT_EXPIRE_HOURS) to_encode.update({"exp": expire}) return jwt.encode(to_encode, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM) def decode_access_token(token: str) -> dict | None: try: return jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM]) except jwt.ExpiredSignatureError: return None except jwt.InvalidTokenError: return None # ── Dependency ─────────────────────────────────────── async def get_current_user( credentials: HTTPAuthorizationCredentials | None = Depends(security), ) -> str: """Extract and validate JWT, returning the user_id.""" if credentials is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="인증이 필요합니다", ) payload = decode_access_token(credentials.credentials) user_id = payload.get("user_id") if payload else None if not isinstance(user_id, str) or get_user_by_username(user_id) is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="유효하지 않거나 만료된 토큰입니다", ) return user_id