Files
2026-09-01 13:00:36 +08:00

31 lines
907 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""API 依赖注入。
- get_current_user: 从 Cookie 读 session → 查库 → 返回 User
- 所有需登录的路由用 Depends(get_current_user)
"""
from fastapi import Depends, Request
from sqlalchemy.orm import Session
from app.core.db import get_session as get_db_session
from app.core.session import SESSION_COOKIE_NAME
from app.models.user import User
from app.services.auth_service import AuthService
def get_db() -> Session:
"""数据库会话依赖(同步 SQLAlchemy)。"""
yield from get_db_session()
def get_current_user(
request: Request,
db: Session = Depends(get_db),
) -> User:
"""从 Cookie 中读取 session token,返回当前登录用户。
未登录或 session 过期抛出 AuthRequiredError401)。
"""
token = request.cookies.get(SESSION_COOKIE_NAME)
auth_service = AuthService(db)
return auth_service.get_current_user(token)