Sfoglia il codice sorgente

修改数据权限 添加webflux支持

785834757 1 anno fa
parent
commit
aaf29697a8

+ 0 - 1
authentication/pom.xml

@@ -14,7 +14,6 @@
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
-            <version>3.0.0</version>
         </dependency>
 
         <dependency>

+ 28 - 33
authentication/src/main/java/com/jzg/config/JzgAuthenticationProvider.java

@@ -97,40 +97,35 @@ public class JzgAuthenticationProvider implements AuthenticationProvider {
         SysUserJzgVo jzgUserInfo = sysUserService.getJzgUserInfo(byId.getId());
 
         //角色数据权限
-//        List<String> roleIds = userPerms.stream().map(x -> x.getRoleId()).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
-//        List<SysRoleDataScope> sysRoleDataScopes = sysRoleDataScopeMapper.selectList(new LambdaQueryWrapper<SysRoleDataScope>()
-//                .eq(SysRoleDataScope::getRoleId, roleIds));
-//        //设置角色数据权限
-//        SysRoleDataScopeVo sysRoleDataScopeVo = new SysRoleDataScopeVo();
-//        String dataMark = "";
-//        List<String> dataDeptIds = new ArrayList<>();
-//        if(sysRoleDataScopes.stream().filter(x->x.getDataMark().equals("2")).count() > 0){
-//            dataMark = "2";
-//            sysRoleDataScopeVo.setDataMark("2");
-//        }else{
-//            List<SysRoleDataScope> dataScopes = sysRoleDataScopes.stream().filter(x -> x.getDataMark().equals("1")).collect(Collectors.toList());
-//            dataDeptIds.add(jzgUserInfo.getDeptId());
-//            List<SysRoleDataScope> dataScopes3 = sysRoleDataScopes.stream().filter(x -> x.getDataMark().equals("3")).collect(Collectors.toList());
-//            List<String> dataScopeLinkRoleIds = dataScopes3.stream().map(x -> x.getRoleId()).collect(Collectors.toList());
-//            List<SysRoleDataScopeLink> sysRoleDataScopeLinks = sysRoleDataScopeLinkMapper.selectList(new LambdaQueryWrapper<SysRoleDataScopeLink>()
-//                    .eq(SysRoleDataScopeLink::getRoleId, dataScopeLinkRoleIds));
-//            List<String> deptIds = sysRoleDataScopeLinks.stream().map(x -> x.getDeptId()).collect(Collectors.toList());
-//            sysRoleDataScopeVo.setDataMark("3");
-//            sysRoleDataScopeVo.setDeptIds(deptIds);
-//        }
-
-        if (details instanceof java.util.Map) {
-            java.util.Map<String, Object> detailMap = (java.util.Map<String, Object>) details;
-            detailMap.put("systemcode", system);
-            detailMap.put("deptId",jzgUserInfo.getDeptId());
-//            detailMap.put("dataScope",sysRoleDataScopeVo);
-        } else {
-            java.util.Map<String, Object> detailMap = new java.util.HashMap<>();
-            detailMap.put("systemcode", system);
-            detailMap.put("deptId",jzgUserInfo.getDeptId());
-//            detailMap.put("dataScope",sysRoleDataScopeVo);
-            details = detailMap;
+        List<String> roleIds = userPerms.stream().map(x -> x.getRoleId()).collect(Collectors.toList()).stream().distinct().collect(Collectors.toList());
+        List<SysRoleDataScope> sysRoleDataScopes = sysRoleDataScopeMapper.selectList(new LambdaQueryWrapper<SysRoleDataScope>()
+                .in(SysRoleDataScope::getRoleId, roleIds));
+        //设置角色数据权限
+        SysRoleDataScopeVo sysRoleDataScopeVo = new SysRoleDataScopeVo();
+        if(!username.equals("admin")) {
+
+            String dataMark = "";
+            List<String> dataDeptIds = new ArrayList<>();
+            if (sysRoleDataScopes.stream().filter(x -> x.getDataMark().equals("2")).count() > 0) {
+                dataMark = "2";
+                sysRoleDataScopeVo.setDataMark("2");
+            } else {
+                List<SysRoleDataScope> dataScopes = sysRoleDataScopes.stream().filter(x -> x.getDataMark().equals("1")).collect(Collectors.toList());
+                dataDeptIds.add(jzgUserInfo.getDeptId());
+                List<SysRoleDataScope> dataScopes3 = sysRoleDataScopes.stream().filter(x -> x.getDataMark().equals("3")).collect(Collectors.toList());
+                List<String> dataScopeLinkRoleIds = dataScopes3.stream().map(x -> x.getRoleId()).collect(Collectors.toList());
+                List<SysRoleDataScopeLink> sysRoleDataScopeLinks = sysRoleDataScopeLinkMapper.selectList(new LambdaQueryWrapper<SysRoleDataScopeLink>()
+                        .in(SysRoleDataScopeLink::getRoleId, dataScopeLinkRoleIds));
+                List<String> deptIds = sysRoleDataScopeLinks.stream().map(x -> x.getDeptId()).collect(Collectors.toList());
+                sysRoleDataScopeVo.setDataMark("3");
+                sysRoleDataScopeVo.setDeptIds(deptIds);
+            }
         }
+        java.util.Map<String, Object> detailMap = new java.util.HashMap<>();
+        detailMap.put("systemcode", system);
+        detailMap.put("deptId",jzgUserInfo.getDeptId());
+        detailMap.put("dataScope",sysRoleDataScopeVo);
+        details = detailMap;
 
         Object finalDetails = details;
         return new UsernamePasswordAuthenticationToken(username, rawPassword, authorities) {{

+ 1 - 1
authentication/src/main/java/com/jzg/config/SecurityConfig.java

@@ -56,7 +56,7 @@ public class SecurityConfig {
 
     @Bean
     public AuthenticationProvider authenticationProvider(UserDetailsService userDetailsService) {
-        return new JzgAuthenticationProvider(userDetailsService,sysUserService,sysRoleService,redissonClient);
+        return new JzgAuthenticationProvider(userDetailsService,sysUserService,sysRoleService,redissonClient,sysRoleDataScopeMapper,sysRoleDataScopeLinkMapper);
     }
 
     @Bean

+ 2 - 0
authentication/src/main/java/com/jzg/entity/RedisToken.java

@@ -1,5 +1,6 @@
 package com.jzg.entity;
 
+import com.jzg.commons.entity.vo.SysRoleDataScopeVo;
 import com.jzg.config.JzgGrantedAuthority;
 import lombok.Data;
 import org.springframework.security.core.authority.SimpleGrantedAuthority;
@@ -11,5 +12,6 @@ public class RedisToken {
     private String username;
     private String system;
     private String deptId;
+    private SysRoleDataScopeVo dataScope;
     private List<JzgGrantedAuthority> auths;
 }

+ 5 - 0
authentication/src/main/java/com/jzg/handler/JzgAuthenticationSuccessHandler.java

@@ -1,6 +1,9 @@
 package com.jzg.handler;
 
 import com.alibaba.fastjson.JSONObject;
+import com.jzg.commons.entity.po.SysRole;
+import com.jzg.commons.entity.po.SysRoleDataScope;
+import com.jzg.commons.entity.vo.SysRoleDataScopeVo;
 import com.jzg.config.JzgGrantedAuthority;
 import com.jzg.config.JzgTokenService;
 import com.jzg.entity.RedisToken;
@@ -35,6 +38,7 @@ public class JzgAuthenticationSuccessHandler implements AuthenticationSuccessHan
     public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
         // 获取用户信息
         String username = authentication.getName();
+        SysRoleDataScopeVo dataScopeVo = (SysRoleDataScopeVo) ((HashMap<?, ?>) authentication.getDetails()).get("dataScope");
         String system = ((HashMap<String, String>) authentication.getDetails()).get("systemcode");
         String deptId = ((HashMap<String, String>) authentication.getDetails()).get("deptId");
         RedisToken redisToken = new RedisToken();
@@ -49,6 +53,7 @@ public class JzgAuthenticationSuccessHandler implements AuthenticationSuccessHan
 
         redisToken.setSystem(system);
         redisToken.setDeptId(deptId);
+        redisToken.setDataScope(dataScopeVo);
         String token = tokenService.generateToken(username);
         // 生成 JWT Token
         tokenService.saveToken(username,token,JSONObject.toJSONString(redisToken));

+ 6 - 0
commons/pom.xml

@@ -12,6 +12,12 @@
     <url>http://maven.apache.org</url>
     <dependencies>
 
+        <!-- Spring Boot Starter Web -->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
         <dependency>
             <groupId>org.projectlombok</groupId>
             <artifactId>lombok</artifactId>

+ 3 - 2
commons/src/main/java/com/jzg/commons/aop/aspect/PermissionAspect.java

@@ -6,6 +6,7 @@ import com.alibaba.fastjson.JSONObject;
 import com.jzg.commons.aop.PremissionCheck;
 import com.jzg.commons.constants.RedisKeyConstants;
 import com.jzg.commons.exception.SystemException;
+import com.jzg.commons.exception.TokenExpireException;
 import jakarta.servlet.http.HttpServletRequest;
 import org.aspectj.lang.annotation.Aspect;
 import org.aspectj.lang.annotation.Before;
@@ -48,12 +49,12 @@ public class PermissionAspect {
         String system = request.getHeader("System");
 
         if(Objects.isNull(token)){
-            throw new Exception("无权限访问");
+            throw new TokenExpireException("无权限访问");
         }
         String userTokenDataStr = redissonClient.getBucket(token).get().toString();
         if(Objects.isNull(userTokenDataStr))
         {
-            throw new Exception("用户未登录");
+            throw new TokenExpireException();
         }
         //判断是否是admin用户 如果是的话则不进行权限过滤
         if(JSON.parseObject(userTokenDataStr).getString("username").equals("admin")){

+ 71 - 24
commons/src/main/java/com/jzg/commons/config/DataPermissionInterceptor.java

@@ -1,7 +1,9 @@
 package com.jzg.commons.config;
 
+import com.alibaba.fastjson.JSONObject;
 import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
 import com.jzg.commons.core.base.BaseController;
+import com.jzg.commons.entity.properties.DataScopeProperties;
 import org.apache.ibatis.executor.Executor;
 import org.apache.ibatis.executor.statement.StatementHandler;
 import org.apache.ibatis.mapping.MappedStatement;
@@ -10,13 +12,18 @@ import org.apache.ibatis.mapping.BoundSql;
 import org.apache.ibatis.reflection.MetaObject;
 import org.apache.ibatis.session.ResultHandler;
 import org.apache.ibatis.session.RowBounds;
+import org.apache.ibatis.session.SqlSession;
+import org.apache.ibatis.session.SqlSessionFactory;
 import org.redisson.api.RedissonClient;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 
 import java.lang.reflect.Field;
 import java.sql.Connection;
 import java.sql.SQLException;
+import java.util.ArrayList;
+import java.util.List;
 import java.util.Properties;
 
 /**
@@ -27,40 +34,80 @@ import java.util.Properties;
 //        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
 })
 public class DataPermissionInterceptor implements InnerInterceptor {
+
+    private List<String> ignoredTables;
+
+    private DataScopeProperties dataScopeProperties;
+
     private final RedissonClient redissonClient;
 
     private final BaseController baseController;
 
-    public DataPermissionInterceptor(RedissonClient redissonClient,BaseController baseController){
+    private SqlSessionFactory sqlSessionFactory;
+
+    public DataPermissionInterceptor(RedissonClient redissonClient, BaseController baseController,
+                                     DataScopeProperties dataScopeProperties){
         this.redissonClient = redissonClient;
         this.baseController = baseController;
+        this.dataScopeProperties = dataScopeProperties;
+    }
+
+
+
+    private boolean shouldIgnoreTable(String sql) {
+        for (String table : dataScopeProperties.getTables()) {
+            if (sql.toLowerCase().contains(table.toLowerCase())) {
+                return true;
+            }
+        }
+        return false;
     }
 
     @Override
     public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
-//        try {
-//            String currentUserDeptId = baseController.getUserDeptId();
-//            // 获取原始 SQL
-//            String sql = boundSql.getSql();
-//
-//            if (sql.toLowerCase().contains("select")) {
-//                sql += " AND dept_id = '" + currentUserDeptId + "'";
-//                Field field = null;
-//                try {
-//                    field = BoundSql.class.getDeclaredField("sql");
-//                } catch (NoSuchFieldException e) {
-//                    throw new RuntimeException(e);
-//                }
-//                field.setAccessible(true);
-//                try {
-//                    field.set(boundSql, sql);
-//                } catch (IllegalAccessException e) {
-//                    throw new RuntimeException(e);
-//                }
-//            }
-//        }catch (Exception e){
-//
-//        }
 
+        try {
+            if(shouldIgnoreTable(boundSql.getSql())) {
+                String currentUserDeptId = baseController.getUserDeptId();
+                String userDataScope = baseController.getUserDataScope();
+                JSONObject dataScope = JSONObject.parseObject(userDataScope);
+                List<String> deptIds = new ArrayList<>();
+                StringBuilder additionalSql = new StringBuilder();
+                if (dataScope.getString("dataMark").equals("2")) {
+                    additionalSql.append(" AND dept_id in (");
+                    additionalSql.append("select id from sys_dept where route like '"+currentUserDeptId+"%'");
+                    additionalSql.append(")");
+                }else {
+                    deptIds = dataScope.getObject("deptIds", List.class);
+                    additionalSql.append(" AND dept_id in (");
+                    deptIds.forEach(deptId -> {
+                        additionalSql.append("'" + deptId + "',");
+                    });
+                    additionalSql.deleteCharAt(additionalSql.length() - 1);
+                    additionalSql.append(")");
+                }
+
+                // 获取原始 SQL
+                String sql = boundSql.getSql();
+
+                if (sql.toLowerCase().contains("select")) {
+                    sql += additionalSql.toString();
+                    Field field = null;
+                    try {
+                        field = BoundSql.class.getDeclaredField("sql");
+                    } catch (NoSuchFieldException e) {
+                        throw new RuntimeException(e);
+                    }
+                    field.setAccessible(true);
+                    try {
+                        field.set(boundSql, sql);
+                    } catch (IllegalAccessException e) {
+                        throw new RuntimeException(e);
+                    }
+                }
+            }
+        }catch (Exception e){
+            System.out.printf(e.getMessage());
+        }
     }
 }

+ 6 - 5
commons/src/main/java/com/jzg/commons/config/MyBatisPlusConfig.java

@@ -5,6 +5,7 @@ import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
 import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
 import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
 import com.jzg.commons.core.base.BaseController;
+import com.jzg.commons.entity.properties.DataScopeProperties;
 import com.jzg.commons.entity.properties.TenantProperties;
 import org.redisson.api.RedissonClient;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -15,7 +16,7 @@ import org.springframework.transaction.annotation.EnableTransactionManagement;
 
 @EnableTransactionManagement(proxyTargetClass = true)
 @Configuration
-@EnableConfigurationProperties(TenantProperties.class)
+@EnableConfigurationProperties({TenantProperties.class,DataScopeProperties.class})
 public class MyBatisPlusConfig {
 
     @Autowired
@@ -25,8 +26,8 @@ public class MyBatisPlusConfig {
     BaseController baseController;
 
     @Bean
-    public DataPermissionInterceptor dataPermissionInterceptor() {
-        return new DataPermissionInterceptor(redissonClient,baseController);
+    public DataPermissionInterceptor dataPermissionInterceptor(DataScopeProperties dataScopeProperties){
+        return new DataPermissionInterceptor(redissonClient,baseController,dataScopeProperties);
     }
 
     @Bean
@@ -36,7 +37,7 @@ public class MyBatisPlusConfig {
     }
 
     @Bean
-    public MybatisPlusInterceptor mybatisPlusInterceptor(TenantProperties tenantProperties) {
+    public MybatisPlusInterceptor mybatisPlusInterceptor(TenantProperties tenantProperties,DataScopeProperties dataScopeProperties) {
 
 
         MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
@@ -45,7 +46,7 @@ public class MyBatisPlusConfig {
             // 启用多租户插件拦截
             interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(new MultiTenantHandler(tenantProperties,baseController)));
         }
-        interceptor.addInnerInterceptor(dataPermissionInterceptor());
+        interceptor.addInnerInterceptor(dataPermissionInterceptor(dataScopeProperties));
         interceptor.addInnerInterceptor(paginationInnerInterceptor());
         return interceptor;
     }

+ 23 - 0
commons/src/main/java/com/jzg/commons/constants/WorkPersonConstants.java

@@ -0,0 +1,23 @@
+package com.jzg.commons.constants;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.Getter;
+
+/**
+ * 工作人员属性
+ */
+@Getter
+@AllArgsConstructor
+public enum WorkPersonConstants {
+    MEMBER(1,"成员"),
+    TEAM_LEADER(2,"团队长"),
+    AGENT(3,"代理人"),
+    CHANNEL_LEADER(4,"渠道负责人"),
+    ORDER_ISSUER(5,"出单员");
+
+
+
+    private Integer code;
+    private String desc;
+}

+ 16 - 0
commons/src/main/java/com/jzg/commons/core/base/BaseController.java

@@ -98,4 +98,20 @@ public class BaseController {
         return userInfo.getString("system");
     }
 
+    /**
+     * 获取用户数据权限
+     * @return
+     */
+    public String getUserDataScope(){
+        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
+        HttpServletRequest request = attributes.getRequest();
+        String authorizationHeader = request.getHeader("Authorization");
+        if(Objects.isNull(authorizationHeader) || Objects.isNull(redissonClient.getBucket(authorizationHeader).get())){
+            throw new SystemException("用户登录信息过期");
+        }
+        String userJsonStr = redissonClient.getBucket(authorizationHeader).get().toString();
+        JSONObject userInfo = JSONObject.parseObject(userJsonStr);
+        return userInfo.getString("dataScope");
+    }
+
 }

+ 23 - 0
commons/src/main/java/com/jzg/commons/entity/properties/DataScopeProperties.java

@@ -0,0 +1,23 @@
+package com.jzg.commons.entity.properties;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+import java.util.List;
+
+/**
+ * 多租户配置属性类
+ *
+ * @author dongxin
+ */
+@Data
+@ConfigurationProperties(prefix = "datascope")
+public class DataScopeProperties {
+
+    /**
+     * 如果存在此表则进行数据权限过滤
+     */
+    private List<String> tables;
+
+
+}

+ 6 - 0
commons/src/main/java/com/jzg/commons/exception/GlobalExceptionHandler.java

@@ -45,6 +45,12 @@ public class GlobalExceptionHandler {
         return HttpResult.error(Integer.parseInt(validateException.getCode()), validateException.getMessage());
     }
 
+    @ExceptionHandler(value = TokenExpireException.class)
+    @ResponseBody
+    public HttpResult systemExceptionHandle(TokenExpireException tokenExpireException) {
+        return HttpResult.error(Integer.parseInt(tokenExpireException.getCode()), tokenExpireException.getMessage());
+    }
+
     @ExceptionHandler(value = MethodArgumentNotValidException.class)
     @ResponseBody
     public HttpResult methodArgumentNotValidExceptionHandle(MethodArgumentNotValidException methodArgumentNotValidException) {

+ 36 - 0
commons/src/main/java/com/jzg/commons/exception/TokenExpireException.java

@@ -0,0 +1,36 @@
+package com.jzg.commons.exception;
+
+/**
+ * token过期异常处理类
+ */
+public class TokenExpireException extends RuntimeException {
+
+    private final String code;
+
+    public TokenExpireException() {
+        super("token过期,请重新登录");
+        this.code = "400";
+
+    }
+
+    public TokenExpireException(String message) {
+        super(message);
+        this.code = "400";
+    }
+
+    public TokenExpireException(String code, String message) {
+        super(message);
+        this.code = code;
+    }
+
+    public TokenExpireException(String code, String message, Throwable cause) {
+        super(message, cause);
+        this.code = code;
+    }
+
+    public String getCode() {
+        return code;
+    }
+
+}
+

+ 0 - 5
gateway/pom.xml

@@ -11,11 +11,6 @@
     <name>gateway Maven Webapp</name>
     <url>http://maven.apache.org</url>
     <dependencies>
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-web</artifactId>
-            <version>3.0.0</version>
-        </dependency>
 
         <dependency>
             <groupId>org.springframework.cloud</groupId>

+ 5 - 0
platform/pom.xml

@@ -12,6 +12,11 @@
     <url>http://maven.apache.org</url>
     <dependencies>
 
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
         <dependency>
             <groupId>io.minio</groupId>
             <artifactId>minio</artifactId>

+ 4 - 0
platform/src/main/resources/application.yml

@@ -40,8 +40,12 @@ tenant:
     - sys_role_data_scope_link
   ignoreLoginNames:
 
+data-scope:
+  ignoreTables:
+
 minio:
   url: http://192.168.5.250:9000
   access-key: v7Zb8XhyLcYNcSHlxvyK
   secret-key: 58YibMwpxGKtXcekPL065OM4GonC1hf2tFMjI9EN
   bucket-name: jzg
+

+ 6 - 6
pom.xml

@@ -39,11 +39,6 @@
 
   <dependencies>
 
-    <!-- Spring Boot Starter Web -->
-    <dependency>
-      <groupId>org.springframework.boot</groupId>
-      <artifactId>spring-boot-starter-web</artifactId>
-    </dependency>
 
     <!-- Spring Boot Starter Test -->
     <dependency>
@@ -80,7 +75,12 @@
   <dependencyManagement>
     <dependencies>
 
-
+      <!-- Spring Boot Starter Web -->
+      <dependency>
+        <groupId>org.springframework.boot</groupId>
+        <artifactId>spring-boot-starter-web</artifactId>
+        <version>3.0.0</version>
+      </dependency>
 
       <!-- Spring Boot Starter Webflux -->
       <dependency>

+ 0 - 1
tenant/organization/pom.xml

@@ -14,7 +14,6 @@
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
-            <version>3.0.0</version>
         </dependency>
 
         <dependency>

+ 0 - 5
tenant/organization/src/main/java/com/jzg/organization/controller/UserController.java

@@ -75,9 +75,4 @@ public class UserController extends BaseController {
         return sysUserService.getUserInfoById(id);
     }
 
-
-
-
-
-
 }

+ 4 - 1
tenant/organization/src/main/resources/application.yml

@@ -37,5 +37,8 @@ tenant:
     - sys_role_perms
     - sys_area
     - sys_dict
-    - sys_user_jzg_info
+    - sys_user
   ignoreLoginNames:
+
+data-scope:
+  tables: