nex_buddy/server/app/api/deps.py

106 lines
3.8 KiB
Python
Raw Normal View History

2026-11-13 06:38:19 +00:00
"""鉴权依赖:Web 会话 token、设备 token。
两种 token 都只把 sha256 存进 Redis,库里不留凭证。
设备 token 形如 ``<device_id>:<secret>``,自带设备标识,省一个请求头。
"""
from __future__ import annotations
from typing import Annotated
from fastapi import Depends, Header, HTTPException, Query, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.security import token_hash
from app.db.session import get_session
from app.models import Device, User
from app.services import redis_store
SessionDep = Annotated[AsyncSession, Depends(get_session)]
def _bearer(authorization: str | None) -> str:
if not authorization or not authorization.lower().startswith("bearer "):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing bearer token")
return authorization[7:].strip()
async def current_user(
authorization: Annotated[str | None, Header()] = None,
db: AsyncSession = Depends(get_session),
) -> User:
token = _bearer(authorization)
uid = await redis_store.load_session(token_hash(token))
if not uid:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "session expired")
user = await db.get(User, uid)
if user is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "user not found")
if user.status != "active":
raise HTTPException(status.HTTP_403_FORBIDDEN, "account disabled")
return user
async def current_admin(user: User = Depends(current_user)) -> User:
if user.role != "admin":
raise HTTPException(status.HTTP_403_FORBIDDEN, "admin only")
return user
async def current_device(
authorization: Annotated[str | None, Header()] = None,
db: AsyncSession = Depends(get_session),
) -> Device:
raw = _bearer(authorization)
device_id, _, secret = raw.partition(":")
if not device_id or not secret:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "malformed device token")
if not await redis_store.load_device_token(device_id, token_hash(secret)):
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device token rejected")
device = await db.get(Device, device_id)
if device is None:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "device unknown")
return device
CurrentUser = Annotated[User, Depends(current_user)]
CurrentAdmin = Annotated[User, Depends(current_admin)]
CurrentDevice = Annotated[Device, Depends(current_device)]
async def current_user_any(
t: Annotated[str | None, Query(description="token(媒体预览用,<img>/<audio> 带不了头)")] = None,
authorization: Annotated[str | None, Header()] = None,
db: AsyncSession = Depends(get_session),
) -> User:
"""接受 ``?t=<token>`` 或 Authorization 头的用户鉴权。
``<img src>`` / ``<audio src>`` 没法加请求头,媒体预览只能把 token 放 query。
只给「读自己媒体文件」这一条路径用,别扩散——URL 里的 token 会进日志和
Referer,风险面比头大。
"""
token = t or (_bearer(authorization) if authorization else None)
if not token:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "missing token")
uid = await redis_store.load_session(token_hash(token))
if not uid:
raise HTTPException(status.HTTP_401_UNAUTHORIZED, "session expired")
user = await db.get(User, uid)
if user is None or user.status != "active":
raise HTTPException(status.HTTP_403_FORBIDDEN, "account unavailable")
return user
CurrentUserAny = Annotated[User, Depends(current_user_any)]
async def user_of_device(device: Device, db: AsyncSession) -> User | None:
if not device.bound_user_id:
return None
return (await db.execute(select(User).where(User.id == device.bound_user_id))).scalar_one_or_none()