72 lines
2.6 KiB
Python
72 lines
2.6 KiB
Python
"""
|
|
backend/app/decorators.py
|
|
文件用途:权限控制装饰器集合
|
|
引用文件:flask, functools, models, db
|
|
逻辑关系:为需要鉴权的 API 提供统一的用户获取、权限校验入口
|
|
"""
|
|
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)."""
|
|
user = _auth_current_user()
|
|
if user:
|
|
g.current_user = user
|
|
return user
|
|
|
|
def require_agent_permission(f):
|
|
"""
|
|
装饰器:检查当前用户是否有指定 Agent 的访问权限
|
|
核心逻辑:
|
|
1. 从请求体中读取 agent_id
|
|
2. 获取当前用户 (临时固定为 ID=1)
|
|
3. 如果用户是 admin,则放行
|
|
4. 否则检查 user.agents 是否包含该 agent
|
|
传入参数:
|
|
f: 被装饰的视图函数
|
|
返回值:
|
|
包装后的视图函数
|
|
"""
|
|
|
|
@wraps(f)
|
|
def decorated_function(*args, **kwargs):
|
|
data = request.get_json(silent=True) or {}
|
|
agent_id = data.get('agent_id') or request.args.get('agent_id')
|
|
if not agent_id:
|
|
raise ValidationError('agent_id is required')
|
|
user = _get_current_user()
|
|
if not user:
|
|
raise UnauthorizedError('Unauthorized')
|
|
agent = Agent.query.get(agent_id)
|
|
if not agent:
|
|
raise NotFoundError('Agent not found')
|
|
g.current_agent = agent
|
|
if user.role == 'admin':
|
|
return f(*args, **kwargs)
|
|
if agent not in user.agents:
|
|
raise ForbiddenError('Permission denied for this agent')
|
|
return f(*args, **kwargs)
|
|
return decorated_function
|
|
|
|
def require_admin(f):
|
|
"""
|
|
装饰器:限制只有管理员角色才能访问的接口
|
|
核心逻辑:
|
|
1. 获取当前用户
|
|
2. 判断 user.role 是否为 'admin'
|
|
"""
|
|
|
|
@wraps(f)
|
|
def decorated_function(*args, **kwargs):
|
|
user = _get_current_user()
|
|
if not user:
|
|
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':
|
|
raise ForbiddenError('Admin privilege required')
|
|
return f(*args, **kwargs)
|
|
return decorated_function |