Files
o2o-weather/backend/common/auth.py
T
minaChoiandClaude Opus 5.5 e134295ce5 feat: 날씨각 백엔드 API (날씨·노을·지수·주말·계절·피드·로그인·반응)
- FastAPI + PostgreSQL + Redis, web·worker 분리, compose 에 backend·worker·postgres·redis 추가
- 기상청 단기·초단기·중기·특보, 에어코리아, Open-Meteo, TourAPI, 특일정보 연동 (첫 조회 때 받고 캐시)
- 매일 03:00 worker 가 전국 공통 피드 칸을 정하고 지난 데이터를 정리
- 시드: 시군구 256곳, 지수 23개, 노을 대표 지점·명소, 데이트 명소, 읽을거리
- pytest 66개 (테스트 전용 DB·Redis 사용)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-02 11:32:22 +09:00

72 lines
2.8 KiB
Python

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()
async def verify_password(password: str, hashed: str) -> bool:
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), "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"])))
if err is not ErrorType.SUCCESS or user is None or user.status != 1:
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