刘光辉
13 小时以前 34981c30a78e8bbd7791131059a9210f9928b62c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
package jnpf.dmsService;
 
import jnpf.dmsEntity.permission.entity.DmsFilePermissionEntity;
import jnpf.dmsEntity.permission.entity.DmsPermissionResourceEntity;
import jnpf.dmsEntity.permission.enums.DmsActorType;
import jnpf.dmsEntity.permission.enums.DmsPermissionAction;
import jnpf.dmsEntity.permission.enums.DmsPrincipalType;
import jnpf.dmsEntity.permission.enums.DmsResourceScope;
import jnpf.dmsEntity.permission.enums.DmsResourceType;
import jnpf.dmsEntity.permission.form.PermissionGrantBatchForm;
import jnpf.dmsEntity.permission.form.PermissionGrantItemForm;
import jnpf.dmsEntity.permission.form.PermissionRevokeForm;
import jnpf.dmsEntity.permission.vo.DmsPermissionGrantVO;
import jnpf.dmsIntegration.audit.DmsAuditAdapter;
import jnpf.dmsMapper.DmsFilePermissionMapper;
import jnpf.dmsMapper.DmsPermissionResourceMapper;
import jnpf.dmsPermission.DmsCurrentIdentity;
import jnpf.dmsPermission.DmsPermissionError;
import jnpf.dmsPermission.DmsPermissionException;
import jnpf.dmsPermission.DmsPermissionProperties;
import jnpf.dmsPermission.DmsPrincipalValidator;
import lombok.RequiredArgsConstructor;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.function.Function;
import java.util.stream.Collectors;
 
@Service
@RequiredArgsConstructor
public class DmsPermissionGrantService {
    private static final String FOLDER_CREATOR_CREATE_SOURCE_PREFIX = "folder-creator-create:";
    private static final String FOLDER_CREATOR_CREATE_REASON = "目录创建者默认 CREATE 权限";
 
    private final DmsCurrentIdentity currentIdentity;
    private final DmsPermissionProperties properties;
    private final DmsPrincipalValidator principalValidator;
    private final DmsPermissionResourceMapper resourceMapper;
    private final DmsFilePermissionMapper permissionMapper;
    private final DmsAuditAdapter auditAdapter;
 
    @Transactional
    public List<DmsPermissionGrantVO> grant(PermissionGrantBatchForm form) {
        currentIdentity.requirePermissionAdministrator();
        if (form.getItems().size() > properties.getMaxGrantBatchSize()) {
            throw DmsPermissionException.of(DmsPermissionError.INVALID_REQUEST,
                    "授权批量大小不能超过 " + properties.getMaxGrantBatchSize());
        }
        String tenantId = currentIdentity.tenantId();
        String sourceType = form.getSourceType().name();
        String sourceId = form.getSourceId().trim();
        List<PermissionGrantItemForm> items = normalizeAndValidate(form.getItems());
        permissionMapper.lockSource(tenantId, sourceType, sourceId);
        List<DmsFilePermissionEntity> existing = permissionMapper.selectBySource(tenantId, sourceType, sourceId);
        if (!existing.isEmpty()) {
            verifyIdempotentRetry(existing, items);
            return existing.stream().map(this::toVO).collect(Collectors.toList());
        }
 
        validateResources(tenantId, items);
        principalValidator.validate(items);
        List<DmsFilePermissionEntity> created = new ArrayList<>();
        try {
            for (PermissionGrantItemForm item : items) {
                DmsFilePermissionEntity permission = toEntity(tenantId, sourceType, sourceId, item);
                created.add(permissionMapper.insertReturning(permission));
            }
        } catch (DuplicateKeyException ex) {
            throw DmsPermissionException.of(DmsPermissionError.SOURCE_CONFLICT,
                    "授权来源或授权项与已有数据冲突");
        }
        for (DmsFilePermissionEntity permission : created) {
            auditAdapter.dataChange("CREATE", "创建 DMS 文件权限", "dms_file_permissions",
                    permission.getId().toString(), permission.getGrantReason(), null);
        }
        return created.stream().map(this::toVO).collect(Collectors.toList());
    }
 
    @Transactional
    public DmsFilePermissionEntity ensureFolderCreatorCreatePermission(String tenantId, UUID folderId,
                                                                        String creatorUserId) {
        String sourceType = "SYSTEM";
        String sourceId = FOLDER_CREATOR_CREATE_SOURCE_PREFIX + folderId;
        permissionMapper.lockSource(tenantId, sourceType, sourceId);
        List<DmsFilePermissionEntity> existing = permissionMapper.selectBySource(tenantId, sourceType, sourceId);
        if (!existing.isEmpty()) {
            if (existing.size() != 1 || !sameFolderCreatorCreatePermission(
                    existing.get(0), tenantId, folderId, creatorUserId, sourceId)) {
                throw DmsPermissionException.of(DmsPermissionError.SOURCE_CONFLICT,
                        "目录创建者默认权限来源与已有授权不一致");
            }
            return existing.get(0);
        }
 
        DmsFilePermissionEntity permission = new DmsFilePermissionEntity();
        permission.setTenantId(tenantId);
        permission.setResourceType(DmsResourceType.FOLDER.name());
        permission.setResourceId(folderId);
        permission.setResourceScope(DmsResourceScope.SELF.name());
        permission.setPrincipalType(DmsPrincipalType.USER.name());
        permission.setPrincipalId(creatorUserId);
        permission.setIncludeChildOrgs(false);
        permission.setActionCode(DmsPermissionAction.CREATE.name());
        permission.setSourceType(sourceType);
        permission.setSourceId(sourceId);
        permission.setValidFrom(new Date());
        permission.setGrantReason(FOLDER_CREATOR_CREATE_REASON);
        permission.setGrantedByType(DmsActorType.USER.name());
        permission.setGrantedById(creatorUserId);
        try {
            permission = permissionMapper.insertReturning(permission);
        } catch (DuplicateKeyException ex) {
            throw DmsPermissionException.of(DmsPermissionError.SOURCE_CONFLICT,
                    "目录创建者默认权限与已有授权冲突");
        }
        auditAdapter.dataChange("CREATE", "创建 DMS 目录创建者默认权限", "dms_file_permissions",
                permission.getId().toString(), FOLDER_CREATOR_CREATE_REASON, null);
        return permission;
    }
 
    @Transactional
    public List<DmsPermissionGrantVO> revoke(PermissionRevokeForm form) {
        currentIdentity.requirePermissionAdministrator();
        String tenantId = currentIdentity.tenantId();
        String actorId = currentIdentity.userId();
        String reason = form.getReason().trim();
        List<UUID> ids = new ArrayList<>(new LinkedHashSet<>(form.getPermissionIds()));
        ids.sort(Comparator.comparing(UUID::toString));
        List<DmsFilePermissionEntity> locked = new ArrayList<>();
        for (UUID id : ids) {
            DmsFilePermissionEntity permission = permissionMapper.selectByTenantAndIdForUpdate(tenantId, id);
            if (permission == null) {
                throw DmsPermissionException.of(DmsPermissionError.RESOURCE_NOT_FOUND,
                        "权限不存在: " + id);
            }
            if (permission.getRevokedAt() != null
                    && (!DmsActorType.USER.name().equals(permission.getRevokedByType())
                    || !actorId.equals(permission.getRevokedById())
                    || !reason.equals(permission.getRevokeReason()))) {
                throw DmsPermissionException.of(DmsPermissionError.REVISION_CONFLICT,
                        "权限已被其他请求撤销: " + id);
            }
            locked.add(permission);
        }
        for (DmsFilePermissionEntity permission : locked) {
            if (permission.getRevokedAt() == null) {
                int changed = permissionMapper.revoke(tenantId, permission.getId(), DmsActorType.USER.name(),
                        actorId, reason);
                if (changed != 1) {
                    throw DmsPermissionException.of(DmsPermissionError.REVISION_CONFLICT,
                            "权限撤销发生并发冲突: " + permission.getId());
                }
                auditAdapter.dataChange("UPDATE", "撤销 DMS 文件权限", "dms_file_permissions",
                        permission.getId().toString(), reason, null);
            }
        }
        return ids.stream().map(id -> toVO(permissionMapper.selectByTenantAndId(tenantId, id)))
                .collect(Collectors.toList());
    }
 
    private List<PermissionGrantItemForm> normalizeAndValidate(List<PermissionGrantItemForm> source) {
        List<PermissionGrantItemForm> result = new ArrayList<>();
        Set<String> identities = new HashSet<>();
        for (PermissionGrantItemForm original : source) {
            PermissionGrantItemForm item = copy(original);
            validateItem(item);
            String identity = identity(item);
            if (!identities.add(identity)) {
                throw DmsPermissionException.of(DmsPermissionError.INVALID_REQUEST,
                        "同一授权批次包含重复授权项");
            }
            result.add(item);
        }
        result.sort(Comparator.comparing(this::identity));
        return result;
    }
 
    private PermissionGrantItemForm copy(PermissionGrantItemForm value) {
        PermissionGrantItemForm result = new PermissionGrantItemForm();
        result.setResourceType(value.getResourceType());
        result.setResourceId(value.getResourceId());
        result.setResourceScope(value.getResourceScope());
        result.setPrincipalType(value.getPrincipalType());
        result.setPrincipalId(value.getPrincipalId().trim());
        result.setIncludeChildOrgs(value.isIncludeChildOrgs());
        result.setActionCode(value.getActionCode());
        result.setValidFrom(value.getValidFrom());
        result.setValidTo(value.getValidTo());
        result.setMaxUseCount(value.getMaxUseCount());
        result.setGrantReason(trimToNull(value.getGrantReason()));
        return result;
    }
 
    private void validateItem(PermissionGrantItemForm item) {
        if (item.getResourceType() != DmsResourceType.FOLDER
                && item.getResourceScope() != DmsResourceScope.SELF) {
            invalid("Document 和 FileVersion 只允许 SELF 范围");
        }
        if (item.getActionCode() == DmsPermissionAction.CREATE
                && item.getResourceType() != DmsResourceType.FOLDER) {
            invalid("CREATE 只允许授予 Folder");
        }
        if (item.isIncludeChildOrgs() && item.getPrincipalType() != DmsPrincipalType.ORG) {
            invalid("includeChildOrgs 只适用于 ORG 主体");
        }
        if (item.getMaxUseCount() != null && item.getPrincipalType() != DmsPrincipalType.USER) {
            invalid("按次权限只允许授予 USER 主体");
        }
        Date effectiveFrom = item.getValidFrom() == null ? new Date() : item.getValidFrom();
        if (item.getValidTo() != null && !item.getValidTo().after(effectiveFrom)) {
            invalid("validTo 必须晚于 validFrom");
        }
    }
 
    private void validateResources(String tenantId, List<PermissionGrantItemForm> items) {
        List<UUID> ids = items.stream().map(PermissionGrantItemForm::getResourceId).distinct()
                .collect(Collectors.toList());
        Map<UUID, DmsPermissionResourceEntity> resources = resourceMapper.selectByTenantAndIds(tenantId, ids)
                .stream().collect(Collectors.toMap(DmsPermissionResourceEntity::getId, Function.identity()));
        for (PermissionGrantItemForm item : items) {
            DmsPermissionResourceEntity resource = resources.get(item.getResourceId());
            if (resource == null || !item.getResourceType().name().equals(resource.getResourceType())) {
                throw DmsPermissionException.of(DmsPermissionError.RESOURCE_NOT_FOUND,
                        "授权资源不存在或类型不一致: " + item.getResourceId());
            }
        }
    }
 
    private void verifyIdempotentRetry(List<DmsFilePermissionEntity> existing,
                                       List<PermissionGrantItemForm> requested) {
        if (existing.size() != requested.size() || existing.stream().anyMatch(row -> row.getRevokedAt() != null)) {
            throw DmsPermissionException.of(DmsPermissionError.SOURCE_CONFLICT,
                    "source_id 已存在,但授权集合数量不同或包含已撤销权限");
        }
        Map<String, DmsFilePermissionEntity> byIdentity = existing.stream().collect(Collectors.toMap(
                this::identity, Function.identity(), (left, right) -> left, LinkedHashMap::new));
        for (PermissionGrantItemForm item : requested) {
            DmsFilePermissionEntity row = byIdentity.get(identity(item));
            if (row == null || !sameDefinition(row, item)) {
                throw DmsPermissionException.of(DmsPermissionError.SOURCE_CONFLICT,
                        "source_id 已存在,但完整授权集合与本次请求不一致");
            }
        }
    }
 
    private boolean sameDefinition(DmsFilePermissionEntity row, PermissionGrantItemForm item) {
        return (item.getValidFrom() == null || sameInstant(row.getValidFrom(), item.getValidFrom()))
                && sameInstant(row.getValidTo(), item.getValidTo())
                && Objects.equals(row.getMaxUseCount(), item.getMaxUseCount())
                && Objects.equals(row.getGrantReason(), item.getGrantReason());
    }
 
    private boolean sameFolderCreatorCreatePermission(DmsFilePermissionEntity row, String tenantId,
                                                       UUID folderId, String creatorUserId, String sourceId) {
        return tenantId.equals(row.getTenantId())
                && DmsResourceType.FOLDER.name().equals(row.getResourceType())
                && folderId.equals(row.getResourceId())
                && DmsResourceScope.SELF.name().equals(row.getResourceScope())
                && DmsPrincipalType.USER.name().equals(row.getPrincipalType())
                && creatorUserId.equals(row.getPrincipalId())
                && Boolean.FALSE.equals(row.getIncludeChildOrgs())
                && DmsPermissionAction.CREATE.name().equals(row.getActionCode())
                && "SYSTEM".equals(row.getSourceType())
                && sourceId.equals(row.getSourceId())
                && row.getValidTo() == null
                && row.getMaxUseCount() == null
                && FOLDER_CREATOR_CREATE_REASON.equals(row.getGrantReason())
                && DmsActorType.USER.name().equals(row.getGrantedByType())
                && creatorUserId.equals(row.getGrantedById());
    }
 
    private DmsFilePermissionEntity toEntity(String tenantId, String sourceType, String sourceId,
                                             PermissionGrantItemForm item) {
        DmsFilePermissionEntity entity = new DmsFilePermissionEntity();
        entity.setTenantId(tenantId);
        entity.setResourceType(item.getResourceType().name());
        entity.setResourceId(item.getResourceId());
        entity.setResourceScope(item.getResourceScope().name());
        entity.setPrincipalType(item.getPrincipalType().name());
        entity.setPrincipalId(item.getPrincipalId());
        entity.setIncludeChildOrgs(item.isIncludeChildOrgs());
        entity.setActionCode(item.getActionCode().name());
        entity.setSourceType(sourceType);
        entity.setSourceId(sourceId);
        entity.setValidFrom(item.getValidFrom() == null ? new Date() : item.getValidFrom());
        entity.setValidTo(item.getValidTo());
        entity.setMaxUseCount(item.getMaxUseCount());
        entity.setGrantReason(item.getGrantReason());
        entity.setGrantedByType(DmsActorType.USER.name());
        entity.setGrantedById(currentIdentity.userId());
        return entity;
    }
 
    private String identity(PermissionGrantItemForm item) {
        return item.getResourceType() + "|" + item.getResourceId() + "|" + item.getResourceScope()
                + "|" + item.getPrincipalType() + "|" + item.getPrincipalId() + "|"
                + item.isIncludeChildOrgs() + "|" + item.getActionCode();
    }
 
    private String identity(DmsFilePermissionEntity item) {
        return item.getResourceType() + "|" + item.getResourceId() + "|" + item.getResourceScope()
                + "|" + item.getPrincipalType() + "|" + item.getPrincipalId() + "|"
                + item.getIncludeChildOrgs() + "|" + item.getActionCode();
    }
 
    private boolean sameInstant(Date left, Date right) {
        return left == null ? right == null : right != null && left.toInstant().equals(right.toInstant());
    }
 
    private String trimToNull(String value) {
        return value == null || value.trim().isEmpty() ? null : value.trim();
    }
 
    private void invalid(String message) {
        throw DmsPermissionException.of(DmsPermissionError.INVALID_REQUEST, message);
    }
 
    public DmsPermissionGrantVO toVO(DmsFilePermissionEntity value) {
        DmsPermissionGrantVO result = new DmsPermissionGrantVO();
        result.setId(value.getId());
        result.setResourceType(value.getResourceType());
        result.setResourceId(value.getResourceId());
        result.setResourceScope(value.getResourceScope());
        result.setPrincipalType(value.getPrincipalType());
        result.setPrincipalId(value.getPrincipalId());
        result.setIncludeChildOrgs(value.getIncludeChildOrgs());
        result.setActionCode(value.getActionCode());
        result.setSourceType(value.getSourceType());
        result.setSourceId(value.getSourceId());
        result.setValidFrom(value.getValidFrom());
        result.setValidTo(value.getValidTo());
        result.setMaxUseCount(value.getMaxUseCount());
        result.setUsedCount(value.getUsedCount());
        result.setGrantReason(value.getGrantReason());
        result.setRevokedAt(value.getRevokedAt());
        result.setRevokeReason(value.getRevokeReason());
        result.setRevision(value.getRevision());
        result.setCreatedAt(value.getCreatedAt());
        result.setUpdatedAt(value.getUpdatedAt());
        return result;
    }
}