Browse Source

接口权限控制

andy 1 năm trước cách đây
mục cha
commit
c7e5a9e84b
1 tập tin đã thay đổi với 131 bổ sung168 xóa
  1. 131 168
      src/main/java/com/scbfkj/uni/api/LogAop.java

+ 131 - 168
src/main/java/com/scbfkj/uni/api/LogAop.java

@@ -40,7 +40,11 @@ public class LogAop {
         Object[] args = joinPoint.getArgs();
         Map<String, Object> returnData = null;
         String message = null;
+        Map<String, Object> userInfo = RequestUtil.getUserInfo();
 
+
+        Optional serviceid = Optional.empty();
+        String userId = RequestUtil.getUserId();
         if (Config.isDebug()) {
             System.out.println("请求参数:" + DataFormatUtil.toString(args));
             System.out.println("请求路径:" + uri);
@@ -50,10 +54,7 @@ public class LogAop {
             System.out.println("请求appToken:" + RequestUtil.getAppToken());
         }
 
-        Optional serviceid = Optional.empty();
-        String userId = RequestUtil.getUserId();
         try {
-
             Map body = null;
 
 //            判断服务状态是否为健康状态 runstate!=0
@@ -80,163 +81,15 @@ public class LogAop {
                     }
                 }
             }
-            List<Map<String, Object>> ratelimitruleList = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from ratelimitrule ");
-            Optional<Map<String, Object>> optional = ratelimitruleList.stream().filter(it -> {
-                Object pathMatch = it.get("pathmatch");
-                if (Objects.isNull(pathMatch)) return true;
-                return uri.matches(pathMatch.toString());
-            }).findFirst();
-            if (optional.isPresent()) {
-                Map<String, Object> map = optional.get();
-                String pathMatch = map.get("pathmatch").toString();
-                if (!rateLimiterMap.containsKey(pathMatch)) {
-                    String duration = map.getOrDefault("duration", 1).toString();
-                    String limitValue = map.getOrDefault("limitvalue", 100).toString();
-                    rateLimiterMap.put(pathMatch, RateLimiter.create(Double.parseDouble(limitValue), Integer.parseInt(duration), TimeUnit.SECONDS));
-                }
-                RateLimiter rateLimiter = rateLimiterMap.get(pathMatch);
-                String timeOut = map.getOrDefault("timeout", 1).toString();
-                boolean acquire = rateLimiter.tryAcquire(Integer.parseInt(timeOut), TimeUnit.SECONDS);
-                if (!acquire) {
-                    message = map.getOrDefault("returnmessage", "请求频率过高,请降低请求频率").toString();
-                    return ResponseEntity.ok(UniReturnUtil.fail(message));
-                }
-            }
 
+            message = checkratelimitrule(uri);
 
-            if (Config.isSecurityEnable()) {
-                List<Map<String, Object>> apiInfos = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from apiinfo");
-
-
-                Optional<Map<String, Object>> requestpath = apiInfos.stream().filter(it -> {
-                    Object o = it.get("requestpath");
-                    return Objects.equals(o, uri);
-                }).findAny();
-                if (requestpath.isPresent()) {
-                    Map<String, Object> stringObjectMap = requestpath.get();
-                    Object o = stringObjectMap.get("securitykey");
-                    if (Objects.nonNull(o)) {
-                        String[] securityCheck = o.toString().split(",");
-                        for (String s : securityCheck) {
-                            if (Objects.equals(s, "token")) {
-                                String appToken = RequestUtil.getAppToken();
-                                if (Objects.isNull(appToken)) {
-                                    return ResponseEntity.ok(UniReturnUtil.fail("没有找到token"));
-                                }
-                                try {
-//                                    校验apptoken 成功表示验证通过
-                                    RequestUtil.getApplication();
-                                } catch (Exception e) {
-                                    return ResponseEntity.ok(UniReturnUtil.fail("token验证失败"));
-                                }
-                                if (body != null) {
-                                    List<Map<String, Object>> data = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from userpermissions where userid = ? and serviceid=?", userId, serviceid.get());
-                                    if (data != null && !data.isEmpty()) {
-                                        Map<String, Object> result = data.get(0);
-                                        Object columnlist = result.get("columnlist");
-                                        if (columnlist != null) {
-
-                                            List list = DataFormatUtil.getObjectMapper().readValue(columnlist.toString(), List.class);
-                                            body.put("filterColumns", list);
-                                        }
-                                        Object filterset = result.get("filterset");
-                                        if (filterset != null) {
-
-                                            List list = DataFormatUtil.getObjectMapper().readValue(filterset.toString(), List.class);
-                                            body.put("filterLines", list.stream().map(it -> {
-                                                try {
-                                                    return DataFormatUtil.getObjectMapper().readValue(it.toString(), Map.class);
-                                                } catch (JsonProcessingException e) {
-                                                    throw new RuntimeException(e);
-                                                }
-                                            }).toList());
-                                        }
-                                    }
-                                    body.put("filterColumns", new ArrayList<>() {{
-                                        add("*");
-                                    }});
-
-                                }
-                            }
-                            if (Objects.equals("usertoken", s)) {
-                                String userToken = RequestUtil.getUserToken();
-                                if (Objects.isNull(userToken)) {
-                                    return ResponseEntity.ok(UniReturnUtil.fail("没有找到 usertoken"));
-                                }
-                                Map<String, Object> checkResult = securityService.checkUserToken(userToken);
-                                if (!checkResult.get("code").equals("0")) {
-                                    return ResponseEntity.ok(checkResult);
-                                }
-
-                                if (body != null && serviceid.isPresent()) {
-                                    List<Map<String, Object>> data = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from userpermissions where userid = ? and serviceid=?", userId, serviceid.get());
-                                    if (data != null && !data.isEmpty()) {
-                                        Map<String, Object> result = data.get(0);
-                                        Object columnlist = result.get("selectcolumnlist");
-                                        if (columnlist != null) {
-
-                                            List list = DataFormatUtil.getObjectMapper().readValue(columnlist.toString(), List.class);
-                                            body.put("filterColumns", list);
-                                        }
-                                        Object filterset = result.get("filterset");
-                                        if (filterset != null) {
-
-                                            List list = DataFormatUtil.getObjectMapper().readValue(columnlist.toString(), List.class);
-                                            body.put("filterLines", list.stream().map(it -> {
-                                                try {
-                                                    return DataFormatUtil.getObjectMapper().readValue(it.toString(), Map.class);
-                                                } catch (JsonProcessingException e) {
-                                                    throw new RuntimeException(e);
-                                                }
-                                            }).toList());
-                                        }
-                                    }
-                                }
-                            }
-                        }
-                    }
-                }
+            if (Objects.nonNull(message)) {
+                return ResponseEntity.ok(UniReturnUtil.fail(message));
             }
 
-            if (Objects.nonNull(body) && uri.startsWith("/openApi")) {
-                List<Map<String, Object>> permission = (List<Map<String, Object>>) securityService.permission().get("returnData");
-                if (Objects.nonNull(permission)) {
-                    Optional finalServiceid = serviceid;
-                    Optional<Map<String, Object>> any = permission.stream().filter(it -> Objects.equals(it.get("serviceid"), finalServiceid.get())).findAny();
-                    if (any.isPresent()) {
-                        Map<String, Object> data = any.get();
-                        Object filterset = data.get("filterset");
-                        if (Objects.nonNull(filterset) && !filterset.toString().trim().isEmpty()) {
-                            try {
-                                List list = DataFormatUtil.getObjectMapper().readValue(filterset.toString(), List.class);
-                                body.put("filterLines", list);
-                            } catch (JsonProcessingException e) {
-                                throw new RuntimeException(e);
-                            }
-                        }
-                        Object selectcolumnlist = data.get("selectcolumnlist");
-                        if (Objects.nonNull(selectcolumnlist) && !selectcolumnlist.toString().trim().isEmpty()) {
-                            List list = DataFormatUtil.getObjectMapper().readValue(selectcolumnlist.toString(), List.class);
-                            body.put("filterColumns", list);
-                        }
-                    }
-                }
-                Map<String, Object> userInfo = RequestUtil.getUserInfo();
-                if (Objects.nonNull(userInfo)) {
-                    Object usergroupid = userInfo.get("usergroupid");
-
-//                超级管理员
-                    if (Objects.nonNull(usergroupid) && Objects.equals("0", usergroupid.toString())) {
-                        body.put("filterColumns", Collections.singletonList("*"));
-                    }
-                } else {
-//                    不需要登录也没有设置权限的默认添加一个所有列权限
+            addFilter(body, serviceid);
 
-                    if (body != null && !body.containsKey("filterColumns")) {
-                        body.put("filterColumns", Collections.singletonList("*"));
-                    }
-                }
-            }
             ResponseEntity<Map<String, Object>> responseEntity = (ResponseEntity<Map<String, Object>>) joinPoint.proceed(args);
             if (!responseEntity.getStatusCode().is2xxSuccessful()) {
                 if (Config.isDebug()) {
@@ -275,21 +128,10 @@ public class LogAop {
             System.out.println("返回值:" + DataFormatUtil.toString(returnData));
         }
 
-        Optional<Map<String, Object>> userinfo = Optional.empty();
-        try {
-            userinfo = DATA_BASE.query(Config.getSecurityConnectionStr(), " select usergroupid from userinfo where userid =?", userId).stream().findFirst();
-        } catch (Exception e) {
-            if (Config.isDebug()) {
-                e.printStackTrace();
-            }
-//            错误异常消息
-            message = UniReturnUtil.getMessage(e);
-            returnData = UniReturnUtil.fail(message);
-        }
 
         Object code = returnData.get("code");
-//        过滤数据
-        if (!Config.isDebug() && Objects.nonNull(code) && "0".equals(code.toString()) && userinfo.isPresent() && !"0".equals(userinfo.get().get("usergroupid").toString())) {
+//        过滤返回数据
+        if (!Config.isDebug() && Objects.nonNull(code) && "0".equals(code.toString()) && Objects.nonNull(userInfo) && !"0".equals(userInfo.get("usergroupid").toString())) {
             Object returnData1 = returnData.get("returnData");
             if (returnData1 instanceof List<?> ls) {
                 if (serviceid.isPresent()) {
@@ -317,4 +159,125 @@ public class LogAop {
         }
         return ResponseEntity.ok(returnData);
     }
+
+    private void addFilter(Map<String, Object> body, Optional<String> serviceid) throws Exception {
+
+
+        List<Map<String, Object>> permission = (List<Map<String, Object>>) securityService.permission().get("returnData");
+
+        String uri = RequestUtil.getUri();
+
+        checkToken(uri);
+
+        if (Objects.nonNull(body) && uri.startsWith("/openApi")) {
+
+            Map<String, Object> userInfo = RequestUtil.getUserInfo();
+
+            if (Objects.nonNull(userInfo)) {
+                Object usergroupid = userInfo.get("usergroupid");
+
+//                超级管理员
+                if (Objects.nonNull(usergroupid) && Objects.equals("0", usergroupid.toString())) {
+                    body.put("filterColumns", Collections.singletonList("*"));
+                } else {
+                    if (Objects.nonNull(permission)) {
+                        Optional finalServiceid = serviceid;
+                        Optional<Map<String, Object>> any = permission.stream().filter(it -> Objects.equals(it.get("serviceid"), finalServiceid.get())).filter(it -> Objects.nonNull(it.get("filterset"))).findAny();
+                        if (any.isPresent()) {
+                            Map<String, Object> data = any.get();
+                            Object filterset = data.get("filterset");
+                            if (Objects.nonNull(filterset) && !filterset.toString().trim().isEmpty()) {
+                                try {
+                                    List list = DataFormatUtil.getObjectMapper().readValue(filterset.toString(), List.class);
+                                    body.put("filterLines", list);
+                                } catch (JsonProcessingException e) {
+                                    if (Config.isDebug()) {
+                                        e.printStackTrace();
+                                        throw e;
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+            if (Config.isSecurityEnable()) {
+//                    不需要登录也没有设置权限的默认添加一个所有列权限
+
+                if (body != null && !body.containsKey("filterColumns")) {
+                    body.put("filterColumns", Collections.singletonList("*"));
+                }
+            }
+        }
+    }
+
+    private void checkToken( String uri) throws Exception {
+        if (Config.isSecurityEnable()) {
+            List<Map<String, Object>> apiInfos = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from apiinfo");
+
+
+            Optional<Map<String, Object>> requestpath = apiInfos.stream().filter(it -> {
+                Object o = it.get("requestpath");
+                return Objects.equals(o, uri);
+            }).findAny();
+            if (requestpath.isPresent()) {
+                Map<String, Object> stringObjectMap = requestpath.get();
+                Object o = stringObjectMap.get("securitykey");
+                if (Objects.nonNull(o)) {
+                    String[] securityCheck = o.toString().split(",");
+                    for (String s : securityCheck) {
+                        if (Objects.equals(s, "token")) {
+                            String appToken = RequestUtil.getAppToken();
+                            if (Objects.isNull(appToken)) {
+                                throw new RuntimeException("没有找到token");
+                            }
+                            try {
+//                                    校验apptoken 成功表示验证通过
+                                RequestUtil.getApplication();
+                            } catch (Exception e) {
+                                throw new RuntimeException("token验证失败");
+                            }
+                        }
+                        if (Objects.equals("usertoken", s)) {
+                            String userToken = RequestUtil.getUserToken();
+                            if (Objects.isNull(userToken)) {
+                                throw new RuntimeException("没有找到 usertoken");
+                            }
+                            Map<String, Object> checkResult = securityService.checkUserToken(userToken);
+                            if (!checkResult.get("code").equals("0")) {
+                                throw new RuntimeException(checkResult.getOrDefault("message", "").toString());
+                            }
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+    private String checkratelimitrule(String uri) throws Exception {
+
+        List<Map<String, Object>> ratelimitruleList = DATA_BASE.query(Config.getSecurityConnectionStr(), "select * from ratelimitrule ");
+        Optional<Map<String, Object>> optional = ratelimitruleList.stream().filter(it -> {
+            Object pathMatch = it.get("pathmatch");
+            if (Objects.isNull(pathMatch)) return true;
+            return uri.matches(pathMatch.toString());
+        }).findFirst();
+        if (optional.isPresent()) {
+            Map<String, Object> map = optional.get();
+            String pathMatch = map.get("pathmatch").toString();
+            if (!rateLimiterMap.containsKey(pathMatch)) {
+                String duration = map.getOrDefault("duration", 1).toString();
+                String limitValue = map.getOrDefault("limitvalue", 100).toString();
+                rateLimiterMap.put(pathMatch, RateLimiter.create(Double.parseDouble(limitValue), Integer.parseInt(duration), TimeUnit.SECONDS));
+            }
+            RateLimiter rateLimiter = rateLimiterMap.get(pathMatch);
+            String timeOut = map.getOrDefault("timeout", 1).toString();
+            boolean acquire = rateLimiter.tryAcquire(Integer.parseInt(timeOut), TimeUnit.SECONDS);
+            if (!acquire) {
+                return map.getOrDefault("returnmessage", "请求频率过高,请降低请求频率").toString();
+            }
+        }
+        return null;
+
+    }
 }