import asyncio import uuid from datetime import datetime, timedelta, timezone from typing import Optional import bcrypt from fastapi import Depends, Header, HTTPException from jose import JWTError, jwt from common.database.db_session_manager import DB_SESSION_MNG from common.database.model.models import User from common.enums import ErrorType from config.settings import settings from crud.user_crud import UserCRUD _ALGORITHM = "HS256" async def hash_password(password: str) -> str: """bcrypt 는 느려서 이벤트 루프를 막지 않게 스레드로 뺀다.""" return (await asyncio.to_thread(bcrypt.hashpw, password.encode(), bcrypt.gensalt())).decode() PASSWORD_MAX_BYTES = 72 # bcrypt 가 받는 최대 길이 async def verify_password(password: str, hashed: str) -> bool: if len(password.encode()) > PASSWORD_MAX_BYTES: return False return await asyncio.to_thread(bcrypt.checkpw, password.encode(), hashed.encode()) def issue_tokens(user: User) -> tuple[str, str]: if not settings.jwt_access_secret or not settings.jwt_refresh_secret: raise RuntimeError("JWT_ACCESS_SECRET / JWT_REFRESH_SECRET is empty") now = datetime.now(timezone.utc) access = jwt.encode( {"sub": str(user.user_id), "ver": user.token_version, "type": "access", "exp": now + timedelta(minutes=settings.jwt_access_minutes)}, settings.jwt_access_secret, algorithm=_ALGORITHM, ) refresh = jwt.encode( {"sub": str(user.user_id), "ver": user.token_version, "type": "refresh", "exp": now + timedelta(days=settings.jwt_refresh_days)}, settings.jwt_refresh_secret, algorithm=_ALGORITHM, ) return access, refresh def decode(token: str, secret: str, token_type: str) -> Optional[dict]: try: claims = jwt.decode(token, secret, algorithms=[_ALGORITHM]) except JWTError: return None return claims if claims.get("type") == token_type else None async def _user_from_header(authorization: Optional[str]) -> Optional[User]: if not authorization or not authorization.startswith("Bearer "): return None claims = decode(authorization.removeprefix("Bearer "), settings.jwt_access_secret, "access") if claims is None: raise HTTPException(status_code=401, detail=ErrorType.AUTH_TOKEN_INVALID.name) err, user = await DB_SESSION_MNG.execute_lambda(lambda s: UserCRUD().get(s, uuid.UUID(claims["sub"]))) # 로그아웃하면 token_version 이 올라가서 그 전에 받은 토큰은 모두 무효 if err is not ErrorType.SUCCESS or user is None or user.status != 1 or user.token_version != claims.get("ver"): raise HTTPException(status_code=401, detail=ErrorType.AUTH_TOKEN_INVALID.name) return user async def optional_user(authorization: Optional[str] = Header(None)) -> Optional[User]: """로그인했으면 사용자, 아니면 None. 토큰이 잘못됐으면 401.""" return await _user_from_header(authorization) async def current_user(user: Optional[User] = Depends(optional_user)) -> User: if user is None: raise HTTPException(status_code=401, detail=ErrorType.AUTH_REQUIRED.name) return user