添加项目数据隔离逻辑

This commit is contained in:
mi9688
2024-10-17 18:17:06 +08:00
parent 0fb3e4bd8d
commit a5c5d88b46
12 changed files with 227 additions and 24 deletions

View File

@ -0,0 +1,23 @@
package com.fastbee.common.holder;
/**
* @author mijiupro
*/
public class ProjectHolder {
private static final ThreadLocal<ProjectInfo> TOKEN_HOLDER = new ThreadLocal<>();
public static void setProjectInfo( ProjectInfo projectInfo) {
TOKEN_HOLDER.set( projectInfo);
}
public static ProjectInfo getProjectInfo() {
return TOKEN_HOLDER.get();
}
public static void clear() {
TOKEN_HOLDER.remove();
}
}

View File

@ -0,0 +1,17 @@
package com.fastbee.common.holder;
import lombok.Builder;
import lombok.Data;
import java.util.List;
@Builder
@Data
public class ProjectInfo {
private String projectName;//项目名称
private String projectAdminId;//项目管理员id
private List<Long> projectIdList;//项目id列表包含子项目id
private String projectId;//当前项目id
}

View File

@ -3,6 +3,7 @@ package com.fastbee.framework.config;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import com.fastbee.framework.interceptor.LanguageInterceptor; import com.fastbee.framework.interceptor.LanguageInterceptor;
import com.fastbee.framework.interceptor.ProjectDataIsolationInterceptor;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@ -32,6 +33,9 @@ public class ResourcesConfig implements WebMvcConfigurer
@Resource @Resource
private LanguageInterceptor languageInterceptor; private LanguageInterceptor languageInterceptor;
@Autowired
private ProjectDataIsolationInterceptor projectDataIsolationInterceptor;
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) public void addResourceHandlers(ResourceHandlerRegistry registry)
{ {
@ -55,6 +59,9 @@ public class ResourcesConfig implements WebMvcConfigurer
//这里配置国际化拦截器的白名单 //这里配置国际化拦截器的白名单
registry.addInterceptor(languageInterceptor).addPathPatterns("/**").excludePathPatterns("/v2/api-docs", registry.addInterceptor(languageInterceptor).addPathPatterns("/**").excludePathPatterns("/v2/api-docs",
"/tool/gen/**"); "/tool/gen/**");
//配置项目数据隔离拦截器
registry.addInterceptor(projectDataIsolationInterceptor)
.addPathPatterns("/gis/groups/**", "/gis/legend/**","/gis/site/**");
} }
/** /**

View File

@ -0,0 +1,71 @@
package com.fastbee.framework.interceptor;
import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fastbee.common.holder.ProjectHolder;
import com.fastbee.common.holder.ProjectInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author mijiupro
*/
@Component
@Slf4j
public class ProjectDataIsolationInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
log.info("进入项目数据隔离拦截器");
//放行预检请求
if ("OPTIONS".equalsIgnoreCase(Objects.requireNonNull(request.getMethod()))) {
return true;
}
if ("DELETE".equalsIgnoreCase(request.getMethod())) {
return true;
}
if ("POST".equalsIgnoreCase(request.getMethod())) {
return true;
}
if ("PUT".equalsIgnoreCase(request.getMethod())) {
return true;
}
//获取路径中的查询字符串参数
String projectIds = request.getParameter("projectIds");
if (StringUtils.isBlank(projectIds)) {
return true;
}
byte[] decode = Base64.decode(projectIds);
//转成List集合
String decodedStr = new String(decode);
JSONArray objects = JSONUtil.parseArray(decodedStr);
ProjectHolder.setProjectInfo(ProjectInfo.builder()
.projectIdList(objects.toList(Long.class))
.build());
return true;
}
@Override
public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, @Nullable Exception ex) {
// 清理本地线程
ProjectHolder.clear();
}
}

View File

@ -9,6 +9,7 @@ public enum GroupTagEnum {
MONITORING_STATIONS(3, "检测站点"), MONITORING_STATIONS(3, "检测站点"),
OTHER_OBJECTS(4, "其他对象"), OTHER_OBJECTS(4, "其他对象"),
WATER_AFFAIRS(5, "水利事务"), WATER_AFFAIRS(5, "水利事务"),
ADMINISTRATIVE_REGION(7, "行政区域"),
ALARM_EVENTS(6, "报警事件"); ALARM_EVENTS(6, "报警事件");
private final int code; private final int code;

View File

@ -4,6 +4,7 @@ package com.fastbee.ggroup.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fastbee.ggroup.domain.GGroups; import com.fastbee.ggroup.domain.GGroups;
import com.fastbee.ggroup.domain.vo.GGroupSiteVo; import com.fastbee.ggroup.domain.vo.GGroupSiteVo;
import com.github.yulichang.base.MPJBaseMapper;
import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Select;
import java.util.List; import java.util.List;
@ -15,7 +16,7 @@ import java.util.List;
* @date 2024-09-27 * @date 2024-09-27
*/ */
public interface GGroupsMapper extends BaseMapper<GGroups> public interface GGroupsMapper extends MPJBaseMapper<GGroups>
{ {
/** /**
* 查询组 * 查询组
@ -36,7 +37,8 @@ public interface GGroupsMapper extends BaseMapper<GGroups>
@Select({ @Select({
"<script>", "<script>",
"select gsg.id, gsg.parent_id as parent_id, gg.name as parent_name, gsg.site_id as siteId, gs.name as name, gs.icon, gs.type, gs.space,gs.space_value", "select gsg.id, gsg.parent_id as parent_id, gg.name as parent_name, gsg.site_id as siteId," +
"gs.name as name, gs.icon, gs.type, gs.space,gs.space_value",
"from g_site_groups gsg", "from g_site_groups gsg",
"left join g_groups gg on gsg.parent_id = gg.id", "left join g_groups gg on gsg.parent_id = gg.id",
"left join g_sites gs on gsg.site_id = gs.id", "left join g_sites gs on gsg.site_id = gs.id",

View File

@ -25,7 +25,7 @@ public interface IGGroupsService
public GGroups selectGGroupsById(Long id); public GGroups selectGGroupsById(Long id);
/** /**
* 查询组列表 * 查询组树状列表
* *
* @param gGroups 组 * @param gGroups 组
* @return 组集合 * @return 组集合

View File

@ -5,6 +5,7 @@ import cn.hutool.extra.ssh.JschUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.fastbee.common.exception.ServiceException; import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.holder.ProjectHolder;
import com.fastbee.common.utils.DateUtils; import com.fastbee.common.utils.DateUtils;
import com.fastbee.ggroup.domain.GGroups; import com.fastbee.ggroup.domain.GGroups;
import com.fastbee.ggroup.domain.GSiteGroups; import com.fastbee.ggroup.domain.GSiteGroups;
@ -16,12 +17,14 @@ import com.fastbee.ggroup.mapper.GSitesMapper;
import com.fastbee.ggroup.service.IGGroupsService; import com.fastbee.ggroup.service.IGGroupsService;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.yulichang.query.MPJLambdaQueryWrapper;
import com.github.yulichang.wrapper.MPJLambdaWrapper; import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.*; import java.util.*;
import java.util.stream.Collectors;
/** /**
@ -36,6 +39,12 @@ public class GGroupsServiceImpl implements IGGroupsService
@Autowired @Autowired
private GGroupsMapper gGroupsMapper; private GGroupsMapper gGroupsMapper;
@Autowired
private GSitesMapper gSitesMapper;
@Autowired
private GSiteGroupsMapper gSiteGroupsMapper;
/** /**
* 查询组 * 查询组
@ -51,7 +60,7 @@ public class GGroupsServiceImpl implements IGGroupsService
/** /**
* 查询组列表 * 查询组树状结构列表
* *
* @param gGroups 组 * @param gGroups 组
* @return 组 * @return 组
@ -59,18 +68,34 @@ public class GGroupsServiceImpl implements IGGroupsService
@Override @Override
public List<GGroups> selectGGroupsList(GGroups gGroups) public List<GGroups> selectGGroupsList(GGroups gGroups)
{ {
return buildTree(gGroupsMapper.selectGGroupsList(gGroups)); // List<GGroups> gGroupsList = gGroupsMapper.selectGGroupsList(gGroups);
List<GGroups> list = new LambdaQueryChainWrapper<>(gGroupsMapper).select(GGroups::getId, GGroups::getName, GGroups::getIcon,
GGroups::getTag, GGroups::getParentId, GGroups::getProjectId, GGroups::getProjectName,
GGroups::getOrderNum, GGroups::getSpace)
.in(GGroups::getProjectId, ProjectHolder.getProjectInfo().getProjectIdList())
.list();
return buildTree(list);
} }
/** /**
* 查询/搜索组列表 * 查询组下面的站点
*
* @param gGroups 组 * @param gGroups 组
* @return 组 * @return 组
*/ */
@Override @Override
public List<GGroupSiteVo> selectGGroupsListSites(GGroups gGroups) { public List<GGroupSiteVo> selectGGroupsListSites(GGroups gGroups) {
return gGroupsMapper.selectGGroupsSiteList(gGroups); MPJLambdaWrapper<GSiteGroups> gSiteGroupsMPJLambdaWrapper = new MPJLambdaWrapper<GSiteGroups>()
.select(GSiteGroups::getId, GSiteGroups::getParentId, GSiteGroups::getSiteId)
// .select(GGroups::getName)//起个别名
// .selectAs(GGroups::getName, "parentName")
.select(GSites::getName, GSites::getIcon, GSites::getType, GSites::getSpace, GSites::getSpaceValue)
.leftJoin(GGroups.class, GGroups::getId, GSiteGroups::getParentId)
.leftJoin(GSites.class, GSites::getId, GSiteGroups::getSiteId)
.eq(GSiteGroups::getParentId, gGroups.getParentId())
.like(StringUtils.isNotBlank(gGroups.getName()), GGroups::getName, gGroups.getName());
;
return gSiteGroupsMapper.selectJoinList(GGroupSiteVo.class,gSiteGroupsMPJLambdaWrapper);
} }
private List<GGroups> buildTree(List<GGroups> groups) { private List<GGroups> buildTree(List<GGroups> groups) {
@ -200,13 +225,29 @@ public class GGroupsServiceImpl implements IGGroupsService
} }
/** /**
* 查询组和站点的树状结构 * 查询组和站点(叶子节点)的树状结构
* @param gGroups 组 * @param gGroups 组
* @return 列表 * @return 列表
*/ */
@Override @Override
public List<?> selectGGroupsAndSitesList(GGroups gGroups) { public List<?> selectGGroupsAndSitesList(GGroups gGroups) {
List<GGroups> list = new LambdaQueryChainWrapper<>(gGroupsMapper)
.select(GGroups::getId, GGroups::getName, GGroups::getParentId,
GGroups::getIcon,GGroups::getTag,
GGroups::getSpace, GGroups::getSpaceValue, GGroups::getProjectId)
.eq(Objects.nonNull(gGroups.getTag()), GGroups::getTag, gGroups.getTag())
.in(GGroups::getProjectId, ProjectHolder.getProjectInfo().getProjectIdList())
.list();
System.err.println(ProjectHolder.getProjectInfo());
ProjectHolder.getProjectInfo().getProjectIdList().forEach(System.err::println);
list.forEach(System.err::println);
List<GGroups> gGroupsList = buildTreeSite(list);
List<List<GGroups>> listList = gGroupsList.stream().map(gGroups1 -> {
List<GGroups> list1 = new ArrayList<>();
list1.add(gGroups1);
return list1;
}).collect(Collectors.toList());
//组的树状结构 //组的树状结构
return buildTreeSite(gGroupsMapper.selectGGroupsList(gGroups)); return listList;
} }
} }

View File

@ -11,7 +11,7 @@ import com.fastbee.common.core.domain.BaseEntity;
* 项目对象 project * 项目对象 project
* *
* @author kerwincui * @author kerwincui
* @date 2024-10-16 * &#064;date 2024-10-17
*/ */
@ApiModel(value = "Project",description = "项目 project") @ApiModel(value = "Project",description = "项目 project")
@Data @Data
@ -101,4 +101,9 @@ public class Project extends BaseEntity
@ApiModelProperty("负责人id") @ApiModelProperty("负责人id")
private Long ownerId; private Long ownerId;
/** 父项目id */
@Excel(name = "父项目id")
@ApiModelProperty("父项目id")
private Long parentId;
} }

View File

@ -3,7 +3,6 @@ package com.fastbee.project.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.fastbee.project.domain.Project; import com.fastbee.project.domain.Project;
import org.apache.ibatis.annotations.Update;
import java.util.List; import java.util.List;
@ -11,7 +10,7 @@ import java.util.List;
* 项目Mapper接口 * 项目Mapper接口
* *
* @author kerwincui * @author kerwincui
* @date 2024-09-26 * @date 2024-10-17
*/ */
public interface ProjectMapper extends BaseMapper<Project> public interface ProjectMapper extends BaseMapper<Project>
{ {

View File

@ -1,18 +1,17 @@
package com.fastbee.project.service.impl; package com.fastbee.project.service.impl;
import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper; import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.fastbee.common.utils.DateUtils; import com.fastbee.common.utils.DateUtils;
import com.fastbee.project.domain.Project; import com.fastbee.project.domain.Project;
import com.fastbee.project.mapper.ProjectMapper; import com.fastbee.project.mapper.ProjectMapper;
import com.fastbee.project.service.IProjectService; import com.fastbee.project.service.IProjectService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/** /**
* 项目Service业务层处理 * 项目Service业务层处理
@ -108,17 +107,50 @@ public class ProjectServiceImpl implements IProjectService
@Override @Override
public Map<String, Object> selectProjectByUserId(Long userId) { public Map<String, Object> selectProjectByUserId(Long userId) {
//查询该管理员所管理的项目id以及子项目id列表
Project project = new LambdaQueryChainWrapper<>(projectMapper) Project project = new LambdaQueryChainWrapper<>(projectMapper)
.select(Project::getProjectId, Project::getProjectName) .select(Project::getProjectId, Project::getProjectName)
.eq(Project::getOwnerId, userId) .eq(Project::getOwnerId, userId)
.one(); .one();
HashMap<String , Object> map = new HashMap<>();
if(Objects.isNull(project)){ if(Objects.isNull(project)){
return null; return null;
} }
List<Long> projects = getAllProjects(project.getProjectId());
//把列表进行Base64编码
String projectsBase64 = Base64.encode(projects.toString());
HashMap<String , Object> map = new HashMap<>();
map.put("projectIds",projectsBase64);
map.put("projectId",project.getProjectId()); map.put("projectId",project.getProjectId());
map.put("projectName", project.getProjectName()); map.put("projectName", project.getProjectName());
return map; return map;
} }
public List<Long> getAllProjects(Long projectId) {
List<Long> allProjects = new ArrayList<>();
// 查询当前项目
Project currentProject = new LambdaQueryChainWrapper<>(projectMapper)
.select(Project::getProjectId, Project::getProjectName)
.eq(Project::getProjectId, projectId)
.one();
if (currentProject != null) {
allProjects.add(currentProject.getProjectId());
// 查询当前项目的子项目
List<Project> children = new LambdaQueryChainWrapper<>(projectMapper)
.select(Project::getProjectId, Project::getProjectName)
.eq(Project::getParentId, projectId)
.list();
// 递归查询子项目
for (Project child : children) {
allProjects.addAll(getAllProjects(child.getProjectId()));
}
}
return allProjects;
}
} }

View File

@ -26,10 +26,11 @@
<result property="tenantId" column="tenant_id" /> <result property="tenantId" column="tenant_id" />
<result property="tenantName" column="tenant_name" /> <result property="tenantName" column="tenant_name" />
<result property="ownerId" column="owner_id" /> <result property="ownerId" column="owner_id" />
<result property="parentId" column="parent_id" />
</resultMap> </resultMap>
<sql id="selectProjectVo"> <sql id="selectProjectVo">
select project_id, project_name, sys_show_name, central_coordinates, scope, administrative_area, owner, logo, image, video_introduction, remark, p_params, introduce, del_flag, create_time, create_by, update_time, remarks, tenant_id, tenant_name, owner_id from project select project_id, project_name, sys_show_name, central_coordinates, scope, administrative_area, owner, logo, image, video_introduction, remark, p_params, introduce, del_flag, create_time, create_by, update_time, remarks, tenant_id, tenant_name, owner_id, parent_id from project
</sql> </sql>
<select id="selectProjectList" parameterType="Project" resultMap="ProjectResult"> <select id="selectProjectList" parameterType="Project" resultMap="ProjectResult">
@ -50,6 +51,7 @@
<if test="tenantId != null "> and tenant_id = #{tenantId}</if> <if test="tenantId != null "> and tenant_id = #{tenantId}</if>
<if test="tenantName != null and tenantName != ''"> and tenant_name like concat('%', #{tenantName}, '%')</if> <if test="tenantName != null and tenantName != ''"> and tenant_name like concat('%', #{tenantName}, '%')</if>
<if test="ownerId != null "> and owner_id = #{ownerId}</if> <if test="ownerId != null "> and owner_id = #{ownerId}</if>
<if test="parentId != null "> and parent_id = #{parentId}</if>
</where> </where>
</select> </select>
@ -82,6 +84,7 @@
<if test="tenantId != null">tenant_id,</if> <if test="tenantId != null">tenant_id,</if>
<if test="tenantName != null">tenant_name,</if> <if test="tenantName != null">tenant_name,</if>
<if test="ownerId != null">owner_id,</if> <if test="ownerId != null">owner_id,</if>
<if test="parentId != null">parent_id,</if>
</trim> </trim>
<trim prefix="values (" suffix=")" suffixOverrides=","> <trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="projectId != null">#{projectId},</if> <if test="projectId != null">#{projectId},</if>
@ -105,6 +108,7 @@
<if test="tenantId != null">#{tenantId},</if> <if test="tenantId != null">#{tenantId},</if>
<if test="tenantName != null">#{tenantName},</if> <if test="tenantName != null">#{tenantName},</if>
<if test="ownerId != null">#{ownerId},</if> <if test="ownerId != null">#{ownerId},</if>
<if test="parentId != null">#{parentId},</if>
</trim> </trim>
</insert> </insert>
@ -131,6 +135,7 @@
<if test="tenantId != null">tenant_id = #{tenantId},</if> <if test="tenantId != null">tenant_id = #{tenantId},</if>
<if test="tenantName != null">tenant_name = #{tenantName},</if> <if test="tenantName != null">tenant_name = #{tenantName},</if>
<if test="ownerId != null">owner_id = #{ownerId},</if> <if test="ownerId != null">owner_id = #{ownerId},</if>
<if test="parentId != null">parent_id = #{parentId},</if>
</trim> </trim>
where project_id = #{projectId} where project_id = #{projectId}
</update> </update>