|
1 | 1 | #!/usr/bin/env python3 |
2 | 2 | # -*- coding: utf-8 -*- |
3 | | -from typing import TYPE_CHECKING |
4 | 3 |
|
5 | 4 | from fastapi import Request |
6 | 5 | from sqlalchemy import ColumnElement, and_, or_ |
|
13 | 12 | from backend.core.conf import settings |
14 | 13 | from backend.utils.import_parse import dynamic_import_data_model |
15 | 14 |
|
16 | | -if TYPE_CHECKING: |
17 | | - from backend.app.admin.model import DataRule |
18 | | - |
19 | 15 |
|
20 | 16 | class RequestPermission: |
21 | 17 | """ |
@@ -60,35 +56,34 @@ async def filter_data_permission(db: AsyncSession, request: Request) -> ColumnEl |
60 | 56 | :param request: FastAPI 请求对象 |
61 | 57 | :return: |
62 | 58 | """ |
63 | | - # 获取用户角色和数据范围 |
64 | | - data_scopes = [] |
| 59 | + # 获取数据范围 |
| 60 | + unique_data_scopes = {} |
65 | 61 | for role in request.user.roles: |
66 | 62 | for scope in role.scopes: |
67 | 63 | if scope.status: |
68 | | - data_scopes.append(scope) |
| 64 | + unique_data_scopes[scope.id] = scope |
| 65 | + |
| 66 | + # 转换为列表 |
| 67 | + data_scopes = list(unique_data_scopes.values()) |
69 | 68 |
|
70 | 69 | # 超级管理员和无规则用户不做过滤 |
71 | 70 | if request.user.is_superuser or not data_scopes: |
72 | 71 | return or_(1 == 1) |
73 | 72 |
|
74 | 73 | # 获取数据范围规则 |
75 | | - data_rule_list: list[DataRule] = [] |
| 74 | + unique_data_rules = {} |
76 | 75 | for data_scope in data_scopes: |
77 | 76 | data_scope_with_relation = await data_scope_dao.get_with_relation(db, data_scope.id) |
78 | | - data_rule_list.extend(data_scope_with_relation.rules) |
| 77 | + for rule in data_scope_with_relation.rules: |
| 78 | + unique_data_rules[rule.id] = rule |
79 | 79 |
|
80 | | - # 去重 |
81 | | - seen_data_rule_ids = set() |
82 | | - new_data_rule_list = [] |
83 | | - for rule in data_rule_list: |
84 | | - if rule.id not in seen_data_rule_ids: |
85 | | - seen_data_rule_ids.add(rule.id) |
86 | | - new_data_rule_list.append(rule) |
| 80 | + # 转换为列表 |
| 81 | + data_rule_list = list(unique_data_rules.values()) |
87 | 82 |
|
88 | 83 | where_and_list = [] |
89 | 84 | where_or_list = [] |
90 | 85 |
|
91 | | - for data_rule in new_data_rule_list: |
| 86 | + for data_rule in data_rule_list: |
92 | 87 | # 验证规则模型 |
93 | 88 | rule_model = data_rule.model |
94 | 89 | if rule_model not in settings.DATA_PERMISSION_MODELS: |
|
0 commit comments