mirror of
https://github.com/stardrophere/InsightRadar.git
synced 2026-06-05 23:56:36 +08:00
57 lines
1.7 KiB
Python
57 lines
1.7 KiB
Python
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.security import decode_access_token
|
|
from app.database import SessionLocal
|
|
from app.models.models import AppUser
|
|
|
|
bearer_scheme = HTTPBearer(auto_error=False)
|
|
|
|
def get_db():
|
|
"""
|
|
FastAPI 依赖注入:为每个 HTTP 请求提供独立的数据库会话。
|
|
请求处理完成后自动关闭,防止连接泄漏。
|
|
"""
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials | None = Depends(bearer_scheme),
|
|
db: Session = Depends(get_db),
|
|
) -> AppUser:
|
|
"""
|
|
从 Bearer Token 中解析并返回当前登录用户。
|
|
要求:
|
|
1. 必须携带 Authorization: Bearer <token>
|
|
2. token 验签通过且未过期
|
|
3. 用户在数据库中存在
|
|
"""
|
|
if credentials is None or credentials.scheme.lower() != "bearer":
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Authentication credentials were not provided",
|
|
)
|
|
|
|
token = credentials.credentials
|
|
try:
|
|
user_id, email = decode_access_token(token)
|
|
except ValueError:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid or expired token",
|
|
)
|
|
|
|
user = db.query(AppUser).filter(AppUser.id == user_id).first()
|
|
if not user or user.email != email:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Invalid token user",
|
|
)
|
|
|
|
return user
|