f1ad4273f4
- FastAPI 单进程托管 frontend/dist,systemd 替代 PM2 - 超级管理员 admin、注册开关与用户管理 - README/DEPLOY/USAGE 说明:改代码须本地构建 dist 后 push,服务器 update.sh - 提交 frontend/dist 与 build-frontend 脚本
41 lines
1.6 KiB
Python
41 lines
1.6 KiB
Python
import uuid
|
|
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
from jose import JWTError, jwt
|
|
from sqlalchemy.orm import Session
|
|
|
|
from app.core.config import settings
|
|
from app.core.database import get_db
|
|
from app.models.user import User
|
|
|
|
security = HTTPBearer(auto_error=False)
|
|
|
|
|
|
def get_current_user(
|
|
credentials: HTTPAuthorizationCredentials | None = Depends(security),
|
|
db: Session = Depends(get_db),
|
|
) -> User:
|
|
if credentials is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="未登录")
|
|
token = credentials.credentials
|
|
try:
|
|
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
|
user_id: str | None = payload.get("sub")
|
|
token_type: str | None = payload.get("type")
|
|
if user_id is None or token_type != "access":
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="无效令牌")
|
|
except JWTError as exc:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="无效令牌") from exc
|
|
|
|
user = db.get(User, uuid.UUID(user_id))
|
|
if user is None:
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户不存在")
|
|
return user
|
|
|
|
|
|
def get_superuser(current_user: User = Depends(get_current_user)) -> User:
|
|
if not current_user.is_superuser:
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="需要超级管理员权限")
|
|
return current_user
|