65 lines
2.0 KiB
Python
65 lines
2.0 KiB
Python
from flask import request, jsonify, current_app
|
|
from app import db
|
|
from app.models import Admin
|
|
from . import api_bp
|
|
from flask_login import current_user, login_required
|
|
from werkzeug.security import generate_password_hash
|
|
import functools
|
|
|
|
def require_admin(f):
|
|
"""管理员权限验证装饰器"""
|
|
@functools.wraps(f)
|
|
def decorated_function(*args, **kwargs):
|
|
# 检查用户是否已认证
|
|
if not current_user.is_authenticated:
|
|
return jsonify({
|
|
'success': False,
|
|
'message': '需要登录'
|
|
}), 401
|
|
|
|
# 检查是否为超级管理员
|
|
if not current_user.is_super_admin():
|
|
return jsonify({
|
|
'success': False,
|
|
'message': '需要超级管理员权限'
|
|
}), 403
|
|
|
|
return f(*args, **kwargs)
|
|
return decorated_function
|
|
|
|
def validate_admin_data(data, is_create=True):
|
|
"""验证管理员数据"""
|
|
if not data:
|
|
return False, '请求数据为空'
|
|
|
|
if is_create:
|
|
username = data.get('username', '').strip()
|
|
if not username:
|
|
return False, '用户名不能为空'
|
|
|
|
# 检查用户名是否已存在
|
|
existing = Admin.query.filter_by(username=username).first()
|
|
if existing:
|
|
return False, '用户名已存在'
|
|
|
|
# 检查密码是否为空
|
|
password = data.get('password', '')
|
|
if not password or not password.strip():
|
|
return False, '密码不能为空'
|
|
|
|
# 验证邮箱格式(如果提供)
|
|
email = data.get('email', '').strip()
|
|
if email and '@' not in email:
|
|
return False, '邮箱格式不正确'
|
|
|
|
# 验证角色
|
|
role = data.get('role')
|
|
if role is not None and role not in [0, 1]:
|
|
return False, '角色值无效'
|
|
|
|
# 验证状态
|
|
status = data.get('status')
|
|
if status is not None and status not in [0, 1]:
|
|
return False, '状态值无效'
|
|
|
|
return True, '' |