|
|
@@ -42,11 +42,18 @@ export abstract class GenericCrudService<T extends ObjectLiteral> {
|
|
|
order: { [P in keyof T]?: 'ASC' | 'DESC' } = {},
|
|
|
filters?: {
|
|
|
[key: string]: any;
|
|
|
- }
|
|
|
+ },
|
|
|
+ userId?: string | number
|
|
|
): Promise<[T[], number]> {
|
|
|
const skip = (page - 1) * pageSize;
|
|
|
const query = this.repository.createQueryBuilder('entity');
|
|
|
|
|
|
+ // 添加数据权限过滤
|
|
|
+ if (this.dataPermissionOptions?.enabled && userId) {
|
|
|
+ const userIdField = this.dataPermissionOptions.userIdField;
|
|
|
+ query.andWhere(`entity.${userIdField} = :userId`, { userId });
|
|
|
+ }
|
|
|
+
|
|
|
// 添加关联关系(支持嵌套关联,如 ['contract.client'])
|
|
|
// 使用一致的别名生成策略,确保搜索时能正确引用关联字段
|
|
|
if (relations.length > 0) {
|
|
|
@@ -164,11 +171,60 @@ export abstract class GenericCrudService<T extends ObjectLiteral> {
|
|
|
/**
|
|
|
* 根据ID获取单个实体
|
|
|
*/
|
|
|
- async getById(id: number, relations: string[] = []): Promise<T | null> {
|
|
|
- return this.repository.findOne({
|
|
|
+ async getById(id: number, relations: string[] = [], userId?: string | number): Promise<T | null> {
|
|
|
+ const entity = await this.repository.findOne({
|
|
|
where: { id } as any,
|
|
|
relations
|
|
|
});
|
|
|
+
|
|
|
+ // 数据权限验证
|
|
|
+ if (entity && this.dataPermissionOptions?.enabled && userId) {
|
|
|
+ const hasPermission = await this.checkPermission(entity, userId);
|
|
|
+ if (!hasPermission) {
|
|
|
+ return null; // 没有权限返回null
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ return entity;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 检查用户对实体的权限
|
|
|
+ */
|
|
|
+ private async checkPermission(entity: any, userId: string | number): Promise<boolean> {
|
|
|
+ const options = this.dataPermissionOptions;
|
|
|
+ if (!options?.enabled) return true;
|
|
|
+
|
|
|
+ // 管理员权限覆盖检查
|
|
|
+ if (options.adminOverride?.enabled && options.adminOverride.adminRole) {
|
|
|
+ // 这里需要从认证系统获取用户角色信息
|
|
|
+ // 暂时假设管理员可以访问所有数据
|
|
|
+ // 实际实现中需要集成用户角色检查
|
|
|
+ const isAdmin = await this.checkAdminRole(userId, options.adminOverride.adminRole);
|
|
|
+ if (isAdmin) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 自定义权限验证器
|
|
|
+ if (options.customValidator) {
|
|
|
+ return await options.customValidator(userId, entity);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 基础权限验证:用户ID字段匹配
|
|
|
+ const userIdField = options.userIdField;
|
|
|
+ const entityUserId = entity[userIdField];
|
|
|
+ return entityUserId === userId;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 检查用户是否为管理员
|
|
|
+ * TODO: 需要集成实际的用户角色检查
|
|
|
+ */
|
|
|
+ private async checkAdminRole(userId: string | number, adminRole: string): Promise<boolean> {
|
|
|
+ // 这里需要从认证系统获取用户角色信息
|
|
|
+ // 暂时返回false,实际实现中需要集成用户角色检查
|
|
|
+ return false;
|
|
|
}
|
|
|
|
|
|
/**
|