fix: 统一异常处理

This commit is contained in:
sophie committed 2026-05-30 17:06:32 +08:00
1 parent 4daf8dfcaa
commit 0c5cfcaa4a
21 files changed
+2124 -4218

No files matched your search

+10 -34
View File
@@ -1,4 +1,3 @@
"""
backend/app/decorators.py
文件用途:权限控制装饰器集合
@@ -9,7 +8,7 @@ from functools import wraps
from flask import request, jsonify, g, current_app
from app.models import Agent, User
from app.auth_jwt import get_current_user as _auth_current_user
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
def _get_current_user() -> User:
"""Resolve current user via JWT auth flow (legacy headers optional via config)."""
@@ -18,7 +17,6 @@ def _get_current_user() -> User:
g.current_user = user
return user
def require_agent_permission(f):
"""
装饰器:检查当前用户是否有指定 Agent 的访问权限
@@ -35,42 +33,24 @@ def require_agent_permission(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# 从 JSON 请求体中解析数据
data = request.get_json(silent=True) or {}
# 获取 agent_id (优先从 Body,其次从 Query)
agent_id = data.get('agent_id') or request.args.get('agent_id')
# 如果未提供 agent_id,则返回 400 错误
if not agent_id:
return jsonify({'error': 'agent_id is required'}), 400
# 获取当前用户
raise ValidationError('agent_id is required')
user = _get_current_user()
if not user:
return jsonify({'error': 'Unauthorized'}), 401
# 查询目标 Agent 是否存在
raise UnauthorizedError('Unauthorized')
agent = Agent.query.get(agent_id)
if not agent:
return jsonify({'error': 'Agent not found'}), 404
# 将 agent 对象挂在 g 上,方便下游使用
raise NotFoundError('Agent not found')
g.current_agent = agent
# 如果用户是管理员,跳过权限检查直接放行
if user.role == 'admin':
return f(*args, **kwargs)
# 非管理员:检查多对多关联表中是否存在权限
if agent not in user.agents:
return jsonify({'error': 'Permission denied for this agent'}), 403
# 鉴权通过,调用原始视图函数
raise ForbiddenError('Permission denied for this agent')
return f(*args, **kwargs)
return decorated_function
def require_admin(f):
"""
装饰器:限制只有管理员角色才能访问的接口
@@ -81,16 +61,12 @@ def require_admin(f):
@wraps(f)
def decorated_function(*args, **kwargs):
# 获取当前用户
user = _get_current_user()
if not user:
return jsonify({'error': 'Unauthorized'}), 401
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and not request.headers.get('Authorization'):
return jsonify({'error': 'JWT token is required'}), 401
# 如果不是管理员,则返回 403
raise UnauthorizedError('Unauthorized')
if bool(current_app.config.get('AUTH_JWT_REQUIRED', False)) and (not request.headers.get('Authorization')):
raise UnauthorizedError('JWT token is required')
if user.role != 'admin':
return jsonify({'error': 'Admin privilege required'}), 403
# 是管理员则放行
raise ForbiddenError('Admin privilege required')
return f(*args, **kwargs)
return decorated_function
return decorated_function