from flask import Blueprint, request, jsonify from app.models import Permission, Role, db from sqlalchemy.exc import IntegrityError bp = Blueprint('permissions', __name__) @bp.route('', methods=['GET']) def get_permissions(): permissions = Permission.query.all() permissions_list = [{ 'id': permission.id, 'name': permission.name, 'description': permission.get_detail('description'), 'created_at': permission.created_at.isoformat() if permission.created_at else None } for permission in permissions] return jsonify(permissions_list), 200 @bp.route('/', methods=['GET']) def get_permission_details(permission_id): permission = Permission.query.get(permission_id) if not permission: return jsonify({'message': '权限不存在'}), 404 roles = [{'id': r.id, 'name': r.name} for r in permission.roles] permission_details = { 'id': permission.id, 'name': permission.name, 'description': permission.get_detail('description'), 'created_at': permission.created_at.isoformat() if permission.created_at else None, 'updated_at': permission.updated_at.isoformat() if permission.updated_at else None, 'roles': roles } return jsonify(permission_details), 200 @bp.route('', methods=['POST']) def create_permission(): data = request.get_json() if not data or 'name' not in data: return jsonify({'message': '权限名称是必需的'}), 400 name = data['name'] # 检查权限名称是否已存在 if Permission.query.filter_by(name=name).first(): return jsonify({'message': '权限名称已存在'}), 400 new_permission = Permission(name=name) db.session.add(new_permission) # 如果提供了描述,设置它 if 'description' in data: new_permission.set_detail('description', data['description']) try: db.session.commit() except IntegrityError: db.session.rollback() return jsonify({'message': '创建权限失败,可能是由于数据完整性问题'}), 500 return jsonify({'message': '权限创建成功', 'id': new_permission.id}), 201 @bp.route('/add_to_role', methods=['POST']) def add_permission_to_role(): data = request.get_json() if not data or 'permission_id' not in data or 'role_id' not in data: return jsonify({'message': '权限ID和角色ID都是必需的'}), 400 permission_id = data['permission_id'] role_id = data['role_id'] permission = Permission.query.get(permission_id) if not permission: return jsonify({'message': '权限不存在'}), 404 role = Role.query.get(role_id) if not role: return jsonify({'message': '角色不存在'}), 404 if permission not in role.permissions: role.permissions.append(permission) else: return jsonify({'message': '该角色已经拥有此权限'}), 400 try: db.session.commit() return jsonify({'message': '权限成功添加到角色'}), 200 except IntegrityError: db.session.rollback() return jsonify({'message': '添加权限到角色失败,可能是由于数据完整性问题'}), 500 # 你可以在这里添加更多的权限相关路由...