"""JWT-based authentication with config-file user management.""" import os from datetime import datetime, timedelta, timezone from pathlib import Path import bcrypt import jwt from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials # ── Config ──────────────────────────────────────────── JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "dev-secret-key-change-in-production") JWT_ALGORITHM = "HS256" JWT_EXPIRE_HOURS = int(os.getenv("JWT_EXPIRE_HOURS", "24")) security = HTTPBearer() # ── 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 = Depends(security)) -> str: """Extract and validate JWT, returning the user_id.""" payload = decode_access_token(credentials.credentials) if payload is None or "user_id" not in payload: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="유효하지 않거나 만료된 토큰입니다", ) return payload["user_id"]