Files
KCGL/inventory-backend/app/api/v1/permission.py

95 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# inventory-backend/app/api/v1/permission.py
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt
from app.services.permission_service import PermissionService
from app.utils.decorators import permission_required, audit_log
permission_bp = Blueprint('permission', __name__)
def _get_operator_company():
"""从 JWT 获取当前操作者公司None=超管,具体值=该角色所属公司)"""
claims = get_jwt()
role = claims.get('role', '')
if role and role.upper() == 'SUPER_ADMIN':
return None # 超管不限制公司
return claims.get('company_name', '')
def _has_system_permission(role_code):
"""检查角色是否有 system_permission"""
try:
from app.services.auth_service import AuthService
perm_dict = AuthService.get_user_permissions(role_code)
all_perms = perm_dict.get('menus', []) + perm_dict.get('elements', [])
return 'system_permission' in all_perms
except Exception:
return False
@permission_bp.route('/tree', methods=['GET'])
@jwt_required()
@permission_required('system_permission')
def get_tree():
"""获取权限树"""
try:
data = PermissionService.get_permission_tree()
return jsonify({'code': 200, 'msg': '获取成功', 'data': data}), 200
except Exception as e:
current_app.logger.error(f"Get Tree Failed: {str(e)}")
return jsonify({'code': 500, 'msg': f'服务器内部错误: {str(e)}'}), 500
@permission_bp.route('/role/<string:role_code>', methods=['GET'])
@jwt_required()
def get_role_perms(role_code):
"""获取某个角色的权限列表。
- 查自己角色:不需要额外权限
- 查其他角色:需要 system_permission
"""
try:
claims = get_jwt()
current_role = (claims.get('role') or '').upper()
# 非管理员查其他角色 → 拒绝
if current_role != role_code.upper() and current_role != 'SUPER_ADMIN':
if not _has_system_permission(current_role):
return jsonify({'code': 403, 'msg': '无权查看其他角色的权限'}), 403
company_name = _get_operator_company()
data = PermissionService.get_role_permissions(role_code, company_name=company_name)
return jsonify({'code': 200, 'msg': '获取成功', 'data': data}), 200
except Exception as e:
current_app.logger.error(f"Get Role Perms Failed: {str(e)}")
return jsonify({'code': 500, 'msg': str(e)}), 500
@permission_bp.route('/assign', methods=['POST'])
@jwt_required()
@permission_required('system_permission:operation')
@audit_log(
module='权限管理',
action='分配',
get_target_name_fn=lambda: request.get_json().get('role_code') if request.get_json() else None
)
def assign_perms():
"""保存权限分配(自动带上当前操作者的公司标识)"""
try:
data = request.get_json()
role_code = data.get('role_code')
permissions = data.get('permissions', [])
# ★ 防自锁:操作者修改自己角色时,强制保留权限管理的关键权限
claims = get_jwt()
operator_role = claims.get('role', '')
if operator_role and operator_role.upper() == role_code.upper():
for required in ('system_permission', 'system_permission:operation'):
if required not in permissions:
permissions.append(required)
company_name = _get_operator_company()
PermissionService.assign_permissions(role_code, permissions, company_name=company_name)
return jsonify({'code': 200, 'msg': '保存成功'}), 200
except Exception as e:
current_app.logger.error(f"Assign Perms Failed: {str(e)}")
return jsonify({'code': 500, 'msg': str(e)}), 500