Improve translation reliability and progress feedback
This commit is contained in:
parent
9439858b11
commit
51a6e845d1
20 changed files with 1194 additions and 216 deletions
|
|
@ -1,21 +1,62 @@
|
|||
"""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 ────────────────────────────────────────────
|
||||
|
||||
JWT_SECRET_KEY = os.getenv("JWT_SECRET_KEY", "dev-secret-key-change-in-production")
|
||||
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()
|
||||
security = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
# ── User Loading ───────────────────────────────────────
|
||||
|
|
@ -74,12 +115,20 @@ def decode_access_token(token: str) -> dict | None:
|
|||
|
||||
# ── Dependency ───────────────────────────────────────
|
||||
|
||||
async def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str:
|
||||
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)
|
||||
if payload is None or "user_id" not in payload:
|
||||
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 payload["user_id"]
|
||||
return user_id
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue