Kamixitong/app/api/decorators.py

64 lines
2.4 KiB
Python
Raw Normal View History

2025-11-15 23:57:24 +08:00
from flask import jsonify
from flask_login import current_user
import functools
def require_login(f):
"""登录用户权限验证装饰器(普通管理员和超级管理员都可以访问)
注意对于API端点不使用@login_required装饰器因为它会重定向到登录页面
而不是返回JSON错误响应我们直接检查认证状态并返回JSON
"""
@functools.wraps(f)
def decorated_function(*args, **kwargs):
# 检查用户是否已认证
# Flask-Login 的 current_user 在未登录时是一个 AnonymousUserMixin 实例
# 它的 is_authenticated 属性为 False
if not hasattr(current_user, 'is_authenticated') or not current_user.is_authenticated:
return jsonify({
'success': False,
'message': '需要登录'
}), 401
# 检查账号是否激活is_active 是 Admin 模型的属性)
if hasattr(current_user, 'is_active') and not current_user.is_active:
return jsonify({
'success': False,
'message': '账号已被禁用'
}), 403
return f(*args, **kwargs)
return decorated_function
def require_admin(f):
"""超级管理员权限验证装饰器(只有超级管理员可以访问)
注意对于API端点不使用@login_required装饰器因为它会重定向到登录页面
而不是返回JSON错误响应我们直接检查认证状态并返回JSON
"""
@functools.wraps(f)
def decorated_function(*args, **kwargs):
# 检查用户是否已认证
if not hasattr(current_user, 'is_authenticated') or not current_user.is_authenticated:
return jsonify({
'success': False,
'message': '需要登录'
}), 401
# 检查账号是否激活
if hasattr(current_user, 'is_active') and not current_user.is_active:
return jsonify({
'success': False,
'message': '账号已被禁用'
}), 403
# 检查是否为超级管理员
if not hasattr(current_user, 'is_super_admin') or not current_user.is_super_admin():
return jsonify({
'success': False,
'message': '需要超级管理员权限'
}), 403
return f(*args, **kwargs)
return decorated_function