"""鉴权依赖:Web 会话 token、设备 token。 两种 token 都只把 sha256 存进 Redis,库里不留凭证。 设备 token 形如 ``:``,自带设备标识,省一个请求头。 """ 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(媒体预览用,/