update. 完善用户相关增删改查接口以及Schema模型
This commit is contained in:
@@ -2,8 +2,63 @@ from typing import List
|
||||
|
||||
from django.core.cache import cache
|
||||
from loguru import logger
|
||||
from ninja.errors import HttpError
|
||||
|
||||
from users.models import User, Menu # 替换为你的实际 app 名
|
||||
from functools import wraps
|
||||
import asyncio
|
||||
from asgiref.sync import sync_to_async
|
||||
|
||||
|
||||
# 你的权限检查函数(不变)
|
||||
def has_permission(user_id: int, permission: str) -> bool:
|
||||
# 你原来的逻辑
|
||||
return True
|
||||
|
||||
|
||||
# ====================== 多权限通用装饰器 ======================
|
||||
def require_permissions(*perms: str, match_all: bool = True):
|
||||
"""
|
||||
多权限检查装饰器
|
||||
:param perms: 权限字符串,可传多个
|
||||
:param match_all: True = 必须拥有所有权限(AND),False = 拥有任意一个即可(OR)
|
||||
用法:
|
||||
@require_permissions("role:update", "role:delete") # 两个都要有
|
||||
@require_permissions("role:view", "role:list", match_all=False) # 有一个就行
|
||||
"""
|
||||
|
||||
def decorator(view_func):
|
||||
@wraps(view_func)
|
||||
async def async_wrapper(request, *args, **kwargs):
|
||||
user_id = request.auth.id
|
||||
check = sync_to_async(has_permission)
|
||||
|
||||
# 检查所有权限
|
||||
results = [await check(user_id, perm) for perm in perms]
|
||||
allowed = all(results) if match_all else any(results)
|
||||
|
||||
if not allowed:
|
||||
raise HttpError(403, "权限不足")
|
||||
|
||||
return await view_func(request, *args, **kwargs)
|
||||
|
||||
@wraps(view_func)
|
||||
def sync_wrapper(request, *args, **kwargs):
|
||||
user_id = request.auth.id
|
||||
results = [has_permission(user_id, perm) for perm in perms]
|
||||
allowed = all(results) if match_all else any(results)
|
||||
|
||||
if not allowed:
|
||||
raise HttpError(403, "权限不足")
|
||||
|
||||
return view_func(request, *args, **kwargs)
|
||||
|
||||
# 自动识别同步/异步
|
||||
if asyncio.iscoroutinefunction(view_func):
|
||||
return async_wrapper
|
||||
return sync_wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
|
||||
def get_user_permissions(user_id: int) -> List[str]:
|
||||
|
||||
Reference in New Issue
Block a user