first commit

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
kunkunxiaomaoandClaude committed 2026-11-16 20:45:22 +08:00
commit 9c5fef1a4d
412 files changed
+94582

No files matched your search

+65
View File
@@ -0,0 +1,65 @@
from __future__ import annotations
from typing import Annotated
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from sakura_cloud.core.config import settings
from sakura_cloud.core.security import decode_token
from sakura_cloud.db.session import get_db
from sakura_cloud.models.user import User, UserRole
oauth2_scheme = OAuth2PasswordBearer(tokenUrl=f"{settings.api_prefix}/auth/login")
DbSession = Annotated[Session, Depends(get_db)]
def get_current_user(token: Annotated[str, Depends(oauth2_scheme)], db: DbSession) -> User:
try:
payload = decode_token(token)
except ValueError as exc:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") from exc
if payload.get("type") != "access":
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token type")
user_id = payload.get("sub")
if not user_id:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token subject")
user = db.get(User, str(user_id))
if user is None:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found")
if not user.is_active:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="User is disabled")
if int(payload.get("tv") or 0) != int(user.token_version or 0):
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token has been revoked")
return user
CurrentUser = Annotated[User, Depends(get_current_user)]
def require_admin_user(current_user: CurrentUser) -> User:
if current_user.role not in {UserRole.ADMIN, UserRole.SUPER_ADMIN}:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin privileges required")
return current_user
AdminUser = Annotated[User, Depends(require_admin_user)]
def require_super_admin_user(current_user: CurrentUser) -> User:
if current_user.role != UserRole.SUPER_ADMIN:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Super admin privileges required")
return current_user
SuperAdminUser = Annotated[User, Depends(require_super_admin_user)]
def assert_owner_or_admin(resource_user_id: str, current_user: User) -> None:
if resource_user_id == current_user.id:
return
if current_user.role in {UserRole.ADMIN, UserRole.SUPER_ADMIN}:
return
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Resource not found")