欧阳劲驰 1 kuukausi sitten
vanhempi
commit
7a8043388b
41 muutettua tiedostoa jossa 1570 lisäystä ja 929 poistoa
  1. 46 0
      custom-gateway-app/pom.xml
  2. BIN
      custom-gateway-app/src/main/resources/alam_server.pfx
  3. 35 0
      custom-gateway-app/src/main/resources/application-zydma.yml
  4. 8 2
      custom-gateway-app/src/main/resources/application.yml
  5. 1 1
      custom-gateway-app/src/main/resources/logback.xml
  6. 5 0
      custom-gateway-core/pom.xml
  7. 21 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/annotation/ExcelMapping.java
  8. 21 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/annotation/InfluxDbMapping.java
  9. 17 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/config/GlobalConfig.java
  10. 62 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/config/InfluxDbConfig.java
  11. 28 20
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/config/SecurityConfig.java
  12. 62 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/config/ValidatorConfig.java
  13. 86 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/Api.java
  14. 0 77
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/ApiURI.java
  15. 39 4
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/CommDefine.java
  16. 30 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/InfluxdbMetadata.java
  17. 41 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/TokenMetadata.java
  18. 14 11
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/domain/CommonToken.java
  19. 42 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/domain/TokenData.java
  20. 0 40
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/ApiJWTBizFilterMgr.java
  21. 0 26
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/CustomAuthenticationProvider.java
  22. 0 90
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/GrantedAuthorityImpl.java
  23. 0 138
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/JWTAuthenticationFilter.java
  24. 47 45
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/JWTControllerCheck.java
  25. 102 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/TokenFilter.java
  26. 2 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/properties/GatewayProperties.java
  27. 48 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/properties/GlobalProperties.java
  28. 11 2
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/properties/InfluxDbProperties.java
  29. 9 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/properties/SecurityProperties.java
  30. 1 1
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/CommTool.java
  31. 0 208
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/HttpTool.java
  32. 231 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/InfluxDbUtil.java
  33. 39 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/RequestUtil.java
  34. 101 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/ResponseUtil.java
  35. 59 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/SecurityUtil.java
  36. 0 264
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/TokenAuthenticationService.java
  37. 218 0
      custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/TokenUtil.java
  38. 16 0
      custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/config/ThirdDockConfig.java
  39. 47 0
      custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/constants/SyncBehavior.java
  40. 34 0
      custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/domain/FieldMapping.java
  41. 47 0
      custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/properties/ThirdDockProperties.java

+ 46 - 0
custom-gateway-app/pom.xml

@@ -40,11 +40,57 @@
                 <groupId>org.apache.maven.plugins</groupId>
                 <artifactId>maven-compiler-plugin</artifactId>
             </plugin>
+            <!--maven-resources-->
+            <plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-resources-plugin</artifactId>
+                <configuration>
+                    <encoding>UTF-8</encoding>
+                    <!-- 过滤后缀为pem、pfx的证书文件 -->
+                    <nonFilteredFileExtensions>
+                        <nonFilteredFileExtension>pem</nonFilteredFileExtension>
+                        <nonFilteredFileExtension>pfx</nonFilteredFileExtension>
+                        <nonFilteredFileExtension>p12</nonFilteredFileExtension>
+                    </nonFilteredFileExtensions>
+                </configuration>
+            </plugin>
             <!--spring-boot-->
             <plugin>
                 <groupId>org.springframework.boot</groupId>
                 <artifactId>spring-boot-maven-plugin</artifactId>
+                <version>${spring.boot.version}</version>
+                <configuration>
+                    <fork>true</fork>
+                    <executable>true</executable>
+                    <mainClass>com.shkpr.service.customgateway.CustomGatewayApplication</mainClass>
+                </configuration>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>build-info</goal>
+                        </goals>
+                    </execution>
+                </executions>
             </plugin>
         </plugins>
+        <!--资源包-->
+        <resources>
+            <!--lib-->
+            <resource>
+                <directory>${project.basedir}/libs</directory>
+                <targetPath>BOOT-INF/lib/</targetPath>
+                <includes>
+                    <include>**/*.jar</include>
+                </includes>
+            </resource>
+            <!--resources-->
+            <resource>
+                <directory>src/main/resources</directory>
+                <includes>
+                    <include>**/**</include>
+                </includes>
+                <filtering>true</filtering>
+            </resource>
+        </resources>
     </build>
 </project>

BIN
custom-gateway-app/src/main/resources/alam_server.pfx


+ 35 - 0
custom-gateway-app/src/main/resources/application-zydma.yml

@@ -0,0 +1,35 @@
+#spring
+spring:
+  #influxDb
+  influx:
+    url: http://119.96.165.176:8086/
+    user: kpr
+    password: kpr.2024@117.influxdb
+    database: iot
+    read-timeout: PT60S
+#第三方对接
+third-dock:
+  #认证信息
+  auth:
+    app-key: "xxxx"
+    app-secret: "xxxx"
+  #字段映射
+  field-mappings:
+    k2_personnel_info:
+      - local-field: "uid"
+        remote-field: "用户Id"
+        description: "用户唯一标识"
+      - local-field: "account"
+        remote-field: "登录名"
+      - local-field: "role_id"
+        sync-behavior: INSERT_ONLY
+        default-value: "255"
+        description: "仅插入时设置为255"
+      - local-field: "org"
+        sync-behavior: INSERT_ONLY
+        default-value: "group"
+      - local-field: "password"
+        default-value: "12345"
+      - local-field: "status"
+        remote-field: "是否冻结"
+        description: "状态转换:冻结→-1,其他→1"

+ 8 - 2
custom-gateway-app/src/main/resources/application.yml

@@ -1,5 +1,7 @@
 #spring
 spring:
+  profiles:
+    active: zydma
   application:
     name: KprCustomGateway
 #web
@@ -9,6 +11,8 @@ server:
     context-path: /custom-gw/
 #security
 security:
+  expiration: P7D
+  secret: TRICP_ALAM_DMA
   permit-pattern:
     - /common/async-results
     - /common/temp-files
@@ -16,6 +20,9 @@ security:
 gateway:
   routes:
     zydma: /zy-dma/
+#全局
+global:
+  cpu-cores:
 #异步
 async:
   result-path-pattern: /common/async-results
@@ -25,5 +32,4 @@ temp-file:
   path-pattern: /common/temp-files
   resource-location: ./temp-files/
   cleanup-interval: PT1M
-  max-age: PT4H
-
+  max-age: PT4H

+ 1 - 1
custom-gateway-app/src/main/resources/logback.xml

@@ -2,7 +2,7 @@
 <!--日志级别高低TRACE < DEBUG < INFO < WARN < ERROR < FATAL-->
 <configuration scan="true" scanPeriod="60 seconds" debug="false">
     <!--引用外部配置文件中的变量属性-->
-    <!--<property scope="context" resource="application.properties" />
+    <!--<property scope="context" resource="application.securityProperties" />
     <springProperty scope="context" name="log.dir" source="hgas.log.dir"/>
     <springProperty scope="context" name="log.appname" source="hgas.log.appname"/>-->
     <contextName>TriCP</contextName>

+ 5 - 0
custom-gateway-core/pom.xml

@@ -40,5 +40,10 @@
             <artifactId>jjwt</artifactId>
             <version>${jjwt.version}</version>
         </dependency>
+        <!--influxdb-->
+        <dependency>
+            <groupId>org.influxdb</groupId>
+            <artifactId>influxdb-java</artifactId>
+        </dependency>
     </dependencies>
 </project>

+ 21 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/annotation/ExcelMapping.java

@@ -0,0 +1,21 @@
+package com.shkpr.service.customgateway.core.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * excel字段映射
+ *
+ * @author 欧阳劲驰
+ * @since 0.0.1
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.FIELD)
+public @interface ExcelMapping {
+    /**
+     * @return excel表头
+     */
+    String value();
+}

+ 21 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/annotation/InfluxDbMapping.java

@@ -0,0 +1,21 @@
+package com.shkpr.service.customgateway.core.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * influx字段映射
+ *
+ * @author 欧阳劲驰
+ * @since 0.0.1
+ */
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.FIELD)
+public @interface InfluxDbMapping {
+    /**
+     * @return influx字段
+     */
+    String value();
+}

+ 17 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/config/GlobalConfig.java

@@ -0,0 +1,17 @@
+package com.shkpr.service.customgateway.core.config;
+
+import com.shkpr.service.customgateway.core.properties.GlobalProperties;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * 全局配置
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Configuration
+@EnableConfigurationProperties(GlobalProperties.class)
+public class GlobalConfig {
+
+}

+ 62 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/config/InfluxDbConfig.java

@@ -0,0 +1,62 @@
+package com.shkpr.service.customgateway.core.config;
+
+import com.shkpr.service.customgateway.core.properties.InfluxDbProperties;
+import okhttp3.OkHttpClient;
+import org.influxdb.InfluxDB;
+import org.influxdb.impl.InfluxDBImpl;
+import org.springframework.beans.factory.ObjectProvider;
+import org.springframework.boot.autoconfigure.influx.InfluxDbOkHttpClientBuilderProvider;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * influxDb配置
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Configuration
+@EnableConfigurationProperties(InfluxDbProperties.class)
+public class InfluxDbConfig {
+    final
+    InfluxDbProperties properties;
+    final
+    OkHttpClient.Builder builder;
+
+    public InfluxDbConfig(InfluxDbProperties properties
+            , ObjectProvider<InfluxDbOkHttpClientBuilderProvider> builder
+            , ObjectProvider<OkHttpClient.Builder> deprecatedBuilder) {
+        this.properties = properties;
+        this.builder = determineBuilder(builder.getIfAvailable(),
+                deprecatedBuilder.getIfAvailable());
+    }
+
+    /**
+     * 确认构建器
+     *
+     * @param builder           默认构建器
+     * @param deprecatedBuilder 弃用构建器
+     * @return 可使用的构建器
+     */
+    private static OkHttpClient.Builder determineBuilder(InfluxDbOkHttpClientBuilderProvider builder
+            , OkHttpClient.Builder deprecatedBuilder) {
+        return builder != null ? builder.get()
+                : deprecatedBuilder != null ? deprecatedBuilder
+                : new OkHttpClient.Builder();
+    }
+
+
+    /**
+     * influxDb客户端
+     *
+     * @return influxDb客户端
+     */
+    @Bean
+    public InfluxDB influxDB() {
+        this.builder.readTimeout(properties.getReadTimeout().toMillis(), TimeUnit.MILLISECONDS);
+        return new InfluxDBImpl(properties.getUrl(), properties.getUser(), properties.getPassword(), this.builder);
+    }
+}

+ 28 - 20
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/config/SecurityConfig.java

@@ -1,6 +1,11 @@
 package com.shkpr.service.customgateway.core.config;
 
+import com.shkpr.service.customgateway.core.constants.ResponseCode;
+import com.shkpr.service.customgateway.core.filter.TokenFilter;
+import com.shkpr.service.customgateway.core.properties.GlobalProperties;
 import com.shkpr.service.customgateway.core.properties.SecurityProperties;
+import com.shkpr.service.customgateway.core.utils.ResponseUtil;
+import com.shkpr.service.customgateway.core.utils.TokenUtil;
 import org.springframework.boot.context.properties.EnableConfigurationProperties;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
@@ -9,6 +14,7 @@ import org.springframework.security.config.annotation.web.builders.WebSecurity;
 import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
 import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
 import org.springframework.security.config.http.SessionCreationPolicy;
+import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
 
 /**
  * 安全配置
@@ -21,12 +27,20 @@ import org.springframework.security.config.http.SessionCreationPolicy;
 @EnableGlobalMethodSecurity(prePostEnabled = true)
 @EnableConfigurationProperties(SecurityProperties.class)
 public class SecurityConfig extends WebSecurityConfigurerAdapter {
-    private final SecurityProperties properties;
+    final
+    GlobalProperties globalProperties;
+    final
+    SecurityProperties securityProperties;
+    final
+    TokenUtil tokenUtil;
 
-    public SecurityConfig(SecurityProperties properties) {
-        this.properties = properties;
+    public SecurityConfig(GlobalProperties globalProperties, SecurityProperties securityProperties, TokenUtil tokenUtil) {
+        this.globalProperties = globalProperties;
+        this.securityProperties = securityProperties;
+        this.tokenUtil = tokenUtil;
     }
 
+
     /**
      * http安全配置
      * {@inheritDoc}
@@ -35,20 +49,18 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
     protected void configure(HttpSecurity http) throws Exception {
         //权限
         http.authorizeRequests()
-                .antMatchers(properties.getPermitPattern().toArray(new String[0]))
+                .antMatchers(securityProperties.getPermitPattern().toArray(new String[0]))
                 .permitAll()
                 .anyRequest()
                 .authenticated()
                 .and()
-                // 过滤器
-//                .addFilterBefore(new ApiJWTBizFilterMgr(ApiURI.URI_ALL_BUSI_XXX, authenticationManager()),
-//                        UsernamePasswordAuthenticationFilter.class)
+                //过滤器
+                .addFilterBefore(new TokenFilter(globalProperties, securityProperties, tokenUtil), AnonymousAuthenticationFilter.class)
                 //跨域防伪
                 .csrf().disable()
                 //frame
                 .headers().frameOptions().disable()
                 .and()
-                // 添加过滤器
                 //session
                 .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                 .and()
@@ -56,18 +68,14 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
                 .formLogin().disable()
                 //登出
                 .logout().disable()
-        //异常处理
-//                .exceptionHandling()
-//                .accessDeniedHandler((request, response, accessDeniedException) ->
-////                        ResponseUtil.writeJson(response, new Result<>(HttpStatus.FORBIDDEN.value(), accessDeniedException.getMessage()))
-//                        {
-//                        }
-//                )
-//                .authenticationEntryPoint((request, response, authenticationException) ->
-//                        ResponseUtil.writeJson(response, new Result<>(HttpStatus.UNAUTHORIZED.value(), authenticationException.getMessage()))
-//                        {
-//                        }
-//                )
+                //异常
+                .exceptionHandling()
+                .accessDeniedHandler((request, response, accessDeniedException) ->
+                        ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_ACCESS_DENY, globalProperties.getHttpStatusAlready200())
+                )
+                .authenticationEntryPoint((request, response, authenticationException) ->
+                        ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_NOT_LOGGED_IN, globalProperties.getHttpStatusAlready200())
+                )
         ;
 
     }

+ 62 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/config/ValidatorConfig.java

@@ -0,0 +1,62 @@
+package com.shkpr.service.customgateway.core.config;
+
+import org.hibernate.validator.HibernateValidator;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.context.annotation.DependsOn;
+import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
+
+import javax.validation.Validation;
+import javax.validation.Validator;
+import javax.validation.ValidatorFactory;
+import javax.validation.executable.ExecutableValidator;
+
+/**
+ * 验证配置类
+ */
+@Configuration
+public class ValidatorConfig {
+
+    private ValidatorFactory validatorFactory;
+
+    /**
+     * 验证器工厂
+     */
+    @Bean(destroyMethod = "close")
+    public ValidatorFactory validatorFactory() {
+        this.validatorFactory = Validation.byProvider(HibernateValidator.class)
+                .configure()
+                .addProperty("hibernate.validator.fail_fast", "true")
+                .buildValidatorFactory();
+        return validatorFactory;
+    }
+
+    /**
+     * 标准Bean验证器
+     */
+    @Bean
+    @DependsOn("validatorFactory")
+    public Validator selfValidator() {
+        return validatorFactory.getValidator();
+    }
+
+    /**
+     * 方法验证后处理器
+     */
+    @Bean
+    @DependsOn("selfValidator")
+    public MethodValidationPostProcessor selfMethodValidationPostProcessor() {
+        MethodValidationPostProcessor postProcessor = new MethodValidationPostProcessor();
+        postProcessor.setValidator(selfValidator());
+        return postProcessor;
+    }
+
+    /**
+     * 可执行方法验证器
+     */
+    @Bean
+    @DependsOn("selfValidator")
+    public ExecutableValidator selfExeValidator() {
+        return selfValidator().forExecutables();
+    }
+}

+ 86 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/Api.java

@@ -0,0 +1,86 @@
+package com.shkpr.service.customgateway.core.constants;
+
+/**
+ * api
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+public interface Api {
+    String EXCEPTION_FORMAT = "{%s:%s}:%s"; //{(ios/apk/pc):url}:error reason
+    String WORKSPACE = "Workspace";
+    String URI_XXX_NEW_INFO = "new-info";//新增
+    String URI_XXX_LISTS = "lists"; //分页查询
+    String URI_XXX_RESET = "reset"; //更新(插入或更新)
+    String URI_XXX_SK = "sk";       //以key搜索查询
+    String URI_XXX_SS = "ss";       //模糊搜索查询
+    String URI_XXX_DEL = "del";     //删除
+    String URI_XXX_UPLOAD = "upload";
+    String URI_XXX_DOWNLOAD = "download";
+    String URI_XXX_RESET_PWD = "pwd-reset";
+    String URI_XXX_CHG_PWD = "pwd-chg";
+    String URI_XXX_IMAGES = "images";
+    String URI_XXX_SYS_CHECK = "sys-check";
+    String URI_XXX_SYS_CHECK_CANCEL = "sys-check-cancel";
+    String URI_XXX_SYS_CHECK_RESULTS = "sys-check-results";
+    String URI_XXX_THIRD_IMPORT = "third-import";
+    String URI_XXX_THIRD_IMPORT_GET = "third-import-get";
+    String URI_XXX_THIRD_IMPORT_CANCEL = "third-import-cancel";
+    String URI_XXX_THIRD_IMPORT_PREVIEW = "third-import-preview";
+    String URI_XXX_THIRD_IMPORT_COMMIT = "third-import-commit";
+    String URI_XXX_THIRD_IMPORT_COMMIT_GET = "third-import-commit-get";
+    String URI_XXX_THIRD_EXPORT = "third-export";
+    String URI_XXX_THIRD_EXPORT_GET = "third-export-get";
+    String URI_XXX_CAD_CONVERT = "cad-convert";
+    String URI_XXX_CAD_CONVERT_GET = "cad-convert-get";
+    String URI_XXX_CRS_GET_LIST = "crs-get-list";
+    String URI_XXX_CRS_GET_INFO = "crs-get-info";
+    String URI_XXX_CRS_TRANSFORM = "crs-transform";
+    String URI_XXX_DEVICE_STATUS_LIST = "device-status-list";
+    String URI_XXX_WARING_INFO_LIST = "waring-info-list";
+    String URI_XXX_WARING_INFO_REMOVE = "waring-info-remove";
+    String URI_XXX_TEMP_FILES = "temp-files";
+    String URI_XXX_ASYNC_RESULTS = "async-results";
+    String URI_ACCESS_TOKEN_CHECK = "/kpr-plugin/apply/access-token-check";
+    String URI_FILE_BUSI_XXX = "/files/**";
+    String URI_IMAGE_SHOW_XXX = "/imageShow/**";
+    String URI_ALL_BUSI_XXX = "/kpr-plugin/**";
+    String URI_GIS_SURVEY_H = "/kpr-plugin/gis-survey";
+    String URI_GIS_SURVEY_XXX = URI_GIS_SURVEY_H + "/**";
+    String URI_PIPE_BURST_H = "/kpr-plugin/pipe_burst";
+    String URI_PIPE_BURST_XXX = URI_PIPE_BURST_H + "/**";
+    String URI_USERS_H = "/kpr-plugin/users";
+    String URI_USERS_XXX = URI_USERS_H + "/**";
+    String URI_COMMON_H = "/kpr-plugin/common";
+    String URI_COMMON_XXX = URI_COMMON_H + "/**";
+    String URI_FILES_H = "/kpr-plugin/files";
+    String URI_FILES_XXX = URI_FILES_H + "/**";
+    String URI_INTERNAL_H = "/kpr-plugin/internal";
+    String URI_INTERNAL_XXX = URI_INTERNAL_H + "/**";
+    String URI_INTERNAL_OPS_XXX = "/ops/**";
+    /**
+     * 请求头
+     */
+    interface Headers {
+        //验证口令
+        String AUTH_VERIFY = "Auth-Verify";
+        //ip地址
+        String X_SOURCE_IP = "X-Source-IP";
+        String BIZ_TYPE = "Biz-Type";
+        String CLIENT_TYPE = "Client-Type";
+        String USER_AGENT = "user-agent";
+        String SIGN_KEY = "tri_coorperation_tech_task";
+        String TIMESTAMP = "Timestamp";
+        String SEQUENCE = "Sequence";
+        String SIGNATURE = "Signature";
+        //认证
+        String AUTHORIZATION = "Authorization";
+    }
+
+    /**
+     * 请求属性
+     */
+    interface Attributes {
+
+    }
+}

+ 0 - 77
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/ApiURI.java

@@ -1,77 +0,0 @@
-package com.shkpr.service.customgateway.core.constants;
-
-public class ApiURI {
-    public static final String HEADER_X_SOURCE_IP = "X-Source-IP";
-    public static final String HEADER_BIZ_TYPE = "Biz-Type";
-    public static final String HEADER_CLIENT_TYPE = "Client-Type";
-    public static final String HEADER_USER_AGENT = "user-agent";
-    public static final String HEADER_AUTH_VERIFY = "Auth-Verify";
-    public static final String HEADER_SIGN_KEY = "tri_coorperation_tech_task";
-    public static final String HEADER_TIMESTAMP = "Timestamp";
-    public static final String HEADER_SEQUENCE = "Sequence";
-    public static final String HEADER_SIGNATURE = "Signature";
-    public static final String HEADER_AUTHORIZATION = "Authorization";
-    public static final String EXCEPTION_FORMAT = "{%s:%s}:%s"; //{(ios/apk/pc):url}:error reason
-    public static final String WORKSPACE = "Workspace";
-
-    public static final String URI_XXX_NEW_INFO = "new-info";//新增
-    public static final String URI_XXX_LISTS = "lists"; //分页查询
-    public static final String URI_XXX_RESET = "reset"; //更新(插入或更新)
-    public static final String URI_XXX_SK = "sk";       //以key搜索查询
-    public static final String URI_XXX_SS = "ss";       //模糊搜索查询
-    public static final String URI_XXX_DEL = "del";     //删除
-    public static final String URI_XXX_UPLOAD = "upload";
-    public static final String URI_XXX_DOWNLOAD = "download";
-    public static final String URI_XXX_RESET_PWD = "pwd-reset";
-    public static final String URI_XXX_CHG_PWD = "pwd-chg";
-    public static final String URI_XXX_IMAGES = "images";
-    public static final String URI_XXX_SYS_CHECK = "sys-check";
-    public static final String URI_XXX_SYS_CHECK_CANCEL = "sys-check-cancel";
-    public static final String URI_XXX_SYS_CHECK_RESULTS = "sys-check-results";
-    public static final String URI_XXX_THIRD_IMPORT = "third-import";
-    public static final String URI_XXX_THIRD_IMPORT_GET = "third-import-get";
-    public static final String URI_XXX_THIRD_IMPORT_CANCEL = "third-import-cancel";
-    public static final String URI_XXX_THIRD_IMPORT_PREVIEW = "third-import-preview";
-    public static final String URI_XXX_THIRD_IMPORT_COMMIT = "third-import-commit";
-    public static final String URI_XXX_THIRD_IMPORT_COMMIT_GET = "third-import-commit-get";
-    public static final String URI_XXX_THIRD_EXPORT = "third-export";
-    public static final String URI_XXX_THIRD_EXPORT_GET = "third-export-get";
-    public static final String URI_XXX_CAD_CONVERT = "cad-convert";
-    public static final String URI_XXX_CAD_CONVERT_GET = "cad-convert-get";
-    public static final String URI_XXX_CRS_GET_LIST = "crs-get-list";
-    public static final String URI_XXX_CRS_GET_INFO = "crs-get-info";
-    public static final String URI_XXX_CRS_TRANSFORM = "crs-transform";
-
-    public static final String URI_XXX_DEVICE_STATUS_LIST = "device-status-list";
-    public static final String URI_XXX_WARING_INFO_LIST = "waring-info-list";
-    public static final String URI_XXX_WARING_INFO_REMOVE = "waring-info-remove";
-
-    public static final String URI_XXX_TEMP_FILES = "temp-files";
-    public static final String URI_XXX_ASYNC_RESULTS = "async-results";
-
-    public static final String URI_ACCESS_TOKEN_CHECK = "/kpr-plugin/apply/access-token-check";
-    public static final String URI_FILE_BUSI_XXX = "/files/**";
-    public static final String URI_IMAGE_SHOW_XXX = "/imageShow/**";
-
-    public static final String URI_ALL_BUSI_XXX = "/kpr-plugin/**";
-
-    public static final String URI_GIS_SURVEY_H = "/kpr-plugin/gis-survey";
-    public static final String URI_GIS_SURVEY_XXX = URI_GIS_SURVEY_H + "/**";
-
-    public static final String URI_PIPE_BURST_H = "/kpr-plugin/pipe_burst";
-    public static final String URI_PIPE_BURST_XXX = URI_PIPE_BURST_H + "/**";
-
-    public static final String URI_USERS_H = "/kpr-plugin/users";
-    public static final String URI_USERS_XXX = URI_USERS_H + "/**";
-
-    public static final String URI_COMMON_H = "/kpr-plugin/common";
-    public static final String URI_COMMON_XXX = URI_COMMON_H + "/**";
-
-    public static final String URI_FILES_H = "/kpr-plugin/files";
-    public static final String URI_FILES_XXX = URI_FILES_H + "/**";
-
-    public static final String URI_INTERNAL_H = "/kpr-plugin/internal";
-    public static final String URI_INTERNAL_XXX = URI_INTERNAL_H + "/**";
-
-    public static final String URI_INTERNAL_OPS_XXX = "/ops/**";
-}

+ 39 - 4
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/CommDefine.java

@@ -1,15 +1,50 @@
 package com.shkpr.service.customgateway.core.constants;
 
+/**
+ * 通用定义
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
 public interface CommDefine {
-    String REQ_OUTER = "Outer";//外来请求者
+    /**
+     * 外来请求者
+     */
+    String REQ_OUTER = "Outer";
+    /**
+     * 内部请求者
+     */
     String REQ_INNER = "Inner";
-    String INTERNAL_OPERATOR_ID = "FFFFFFFF";
-    String INTERNAL_OPERATOR_ROLE = "SelfOperator";
+    /**
+     * 内部操作员用户id
+     */
+    String INTERNAL_OPERATOR_USER_ID = "FFFFFFFF";
+    /**
+     * 内部操作员角色id
+     */
     String INTERNAL_OPERATOR_ROLE_ID = "FFFFFFFF";
+    /**
+     * 内部操作员角色
+     */
+    String INTERNAL_OPERATOR_ROLE = "SelfOperator";
+    /**
+     * 管理员用户id
+     */
     String ADMIN_USER_ID = "0";
+    /**
+     * 管理员角色id
+     */
     String ADMIN_ROLE_ID = "0";
+    /**
+     * 管理员账号
+     */
     String ADMIN_ACCOUNT = "admin";
+    /**
+     * 无效id
+     */
     String INVALID_STR_ID = "-1";
+    /**
+     * 超级用户id
+     */
     String SUPER_USER_ID = "UUDA12395CB8B325F16";
-    int LIMIT_MAX = 2000;
 }

+ 30 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/InfluxdbMetadata.java

@@ -0,0 +1,30 @@
+package com.shkpr.service.customgateway.core.constants;
+
+/**
+ * influxdb元数据
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+public interface InfluxdbMetadata {
+    /**
+     * 指令
+     */
+    interface Command {
+        /**
+         * 查询数据库
+         */
+        String SHOW_DATABASE = "SHOW DATABASES";
+        /**
+         * 创建数据库
+         */
+        String CREATE_DATABASE = "CREATE DATABASE ";
+    }
+
+    /**
+     * Sql
+     */
+    interface Sql {
+
+    }
+}

+ 41 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/constants/TokenMetadata.java

@@ -0,0 +1,41 @@
+package com.shkpr.service.customgateway.core.constants;
+
+/**
+ * influxdb元数据
+ *
+ * @author 欧阳劲驰
+ * @since 0.0.1-dev
+ */
+public interface TokenMetadata {
+    /**
+     * 参数
+     */
+    interface Claims {
+        /**
+         * 用户id
+         */
+        String FLAG_KEY = "flagkey";
+        /**
+         * 用户账号
+         */
+        String ACCOUNT = "account";
+        /**
+         * 角色id
+         */
+        String ROLE_ID = "roleid";
+    }
+
+    /**
+     * 请求属性
+     */
+    interface RequestAttributes {
+        /**
+         * 用户id
+         */
+        String USER_ID = "UUID";
+        /**
+         * 角色id
+         */
+        String ROLE_ID = "RLID";
+    }
+}

+ 14 - 11
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/domain/CommonToken.java

@@ -8,12 +8,15 @@ import java.util.Collection;
 
 /**
  * 通用token
+ * <p>principal:token信息</p>
+ * <p>credentials:token字符串</p>
+ *
  * @author 欧阳劲驰
  * @since 1.0.0
  */
-public class CommonToken extends AbstractAuthenticationToken implements Serializable {
+public class CommonAuthToken extends AbstractAuthenticationToken implements Serializable {
     /**
-     * 认证信息
+     * token信息
      */
     private final Object principal;
     /**
@@ -21,40 +24,40 @@ public class CommonToken extends AbstractAuthenticationToken implements Serializ
      */
     private final Object credentials;
 
-    public CommonToken(Object principal, Object credentials) {
+    public CommonAuthToken(Object principal, Object credentials) {
         super(null);
         this.principal = principal;
         this.credentials = credentials;
         setAuthenticated(false);
     }
 
-    public CommonToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
+    public CommonAuthToken(Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities) {
         super(authorities);
         this.principal = principal;
         this.credentials = credentials;
-        super.setAuthenticated(true); // must use super, as we override
+        super.setAuthenticated(true);
     }
 
     /**
      * 未认证
      *
-     * @param principal   用户名
+     * @param principal   token信息
      * @param credentials 密码
      * @return 未认证的token
      */
-    public static CommonToken unauthenticated(Object principal, Object credentials) {
-        return new CommonToken(principal, credentials);
+    public static CommonAuthToken unauthenticated(Object principal, Object credentials) {
+        return new CommonAuthToken(principal, credentials);
     }
 
     /**
      * 已认证
      *
-     * @param principal   用户
+     * @param principal   token信息
      * @param authorities 权限
      * @return 已认证的token
      */
-    public static CommonToken authenticated(Object principal, Collection<? extends GrantedAuthority> authorities) {
-        return new CommonToken(principal, null, authorities);
+    public static CommonAuthToken authenticated(Object principal, Collection<? extends GrantedAuthority> authorities) {
+        return new CommonAuthToken(principal, null, authorities);
     }
 
     @Override

+ 42 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/domain/TokenData.java

@@ -0,0 +1,42 @@
+package com.shkpr.service.customgateway.core.domain;
+
+import lombok.AllArgsConstructor;
+import lombok.Data;
+import lombok.NoArgsConstructor;
+
+/**
+ * token数据
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Data
+@NoArgsConstructor
+@AllArgsConstructor
+public class TokenData {
+    /**
+     * 用户id
+     */
+    private String flagKey = "";
+    /**
+     * 角色id
+     */
+    private String roleId = "";
+    /**
+     * Token字符串
+     */
+    private String tokenStr = "";
+    /**
+     * 签发时间(时间戳)
+     */
+    private long issuedAt = 0L;
+    /**
+     * 过期时间(时间戳)
+     */
+    private long expiration = 0L;
+
+    public TokenData(String flagKey, String roleId) {
+        this.flagKey = flagKey;
+        this.roleId = roleId;
+    }
+}

+ 0 - 40
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/ApiJWTBizFilterMgr.java

@@ -1,40 +0,0 @@
-package com.shkpr.service.customgateway.core.filter;
-
-import com.shkpr.service.customgateway.core.constants.ApiURI;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
-import org.springframework.security.web.util.matcher.RequestMatcher;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-public class ApiJWTBizFilterMgr extends JWTAuthenticationFilter {
-    private RequestMatcher mRequestMatcherForUser = null;
-    private RequestMatcher mRequestMatcherForCommon = null;
-    private RequestMatcher mRequestMatcherForGisSurvey = null;
-    private RequestMatcher mRequestMatcherForPipeBurst = null;
-
-
-    public ApiJWTBizFilterMgr(AuthenticationManager authenticationManager) {
-        this(null, authenticationManager);
-    }
-
-    public ApiJWTBizFilterMgr(String url, AuthenticationManager authenticationManager) {
-        super(url, authenticationManager);
-        this.mStrThisSampleName = this.getClass().getSimpleName();
-
-        mRequestMatcherForUser = new AntPathRequestMatcher(ApiURI.URI_USERS_XXX);
-        mRequestMatcherForCommon = new AntPathRequestMatcher(ApiURI.URI_COMMON_XXX);
-        mRequestMatcherForGisSurvey = new AntPathRequestMatcher(ApiURI.URI_GIS_SURVEY_XXX);
-        mRequestMatcherForPipeBurst = new AntPathRequestMatcher(ApiURI.URI_PIPE_BURST_XXX);
-
-    }
-
-    @Override
-    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
-        chain.doFilter(request, response);
-    }
-}

+ 0 - 26
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/CustomAuthenticationProvider.java

@@ -1,26 +0,0 @@
-package com.shkpr.service.customgateway.core.filter;
-
-import org.springframework.security.authentication.AuthenticationProvider;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.AuthenticationException;
-import org.springframework.security.core.userdetails.UsernameNotFoundException;
-
-public class CustomAuthenticationProvider implements AuthenticationProvider{
-    protected String mStrThisSampleName = null;
-    public CustomAuthenticationProvider() {
-        this.mStrThisSampleName = this.getClass().getSimpleName();
-        //innerJsService = SpringContextUtil.getBean(InnerJsService.class);
-    }
-
-    @Override
-    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
-        throw new UsernameNotFoundException(String.format("No account or password error."));
-    }
-
-    @Override
-    public boolean supports(Class<?> aClass) {
-        return aClass.equals(UsernamePasswordAuthenticationToken.class);
-    }
-}
-

+ 0 - 90
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/GrantedAuthorityImpl.java

@@ -1,90 +0,0 @@
-package com.shkpr.service.customgateway.core.filter;
-
-import com.shkpr.service.customgateway.core.constants.LoginUserRoleType;
-import org.springframework.security.core.GrantedAuthority;
-
-import java.util.ArrayList;
-import java.util.List;
-
-public class GrantedAuthorityImpl implements GrantedAuthority {
-    private static volatile List<GrantedAuthorityImpl> msArrRootAdmin = null;
-    private static volatile List<GrantedAuthorityImpl> msArrAdmin = null;
-    private static volatile List<GrantedAuthorityImpl> msArrNormalUser = null;
-    private static volatile List<GrantedAuthorityImpl> msArrTempUser = null;
-
-    private String authority;
-    public GrantedAuthorityImpl(String authority) {
-        this.authority = authority;
-    }
-    public void setAuthority(String authority) {
-        this.authority = authority;
-    }
-    @Override
-    public String getAuthority() {
-        return this.authority;
-    }
-
-    public static List<GrantedAuthorityImpl> generateAuthority(LoginUserRoleType emType){
-        switch (emType){
-            case ROOT_ADMIN:{
-                if (msArrRootAdmin == null){
-                    synchronized(GrantedAuthorityImpl.class){
-                        if (msArrRootAdmin == null){
-                            msArrRootAdmin = new ArrayList<GrantedAuthorityImpl>();
-                            msArrRootAdmin.add(new GrantedAuthorityImpl(emType.toStrValue()));
-                        }
-                    }
-                }
-            }
-            return msArrRootAdmin;
-            case GUEST:{
-                if (msArrTempUser == null){
-                    synchronized(GrantedAuthorityImpl.class){
-                        if (msArrTempUser == null){
-                            msArrTempUser = new ArrayList<GrantedAuthorityImpl>();
-                            msArrTempUser.add(new GrantedAuthorityImpl(emType.toStrValue()));
-                        }
-                    }
-                }
-            }
-            return msArrTempUser;
-            case USER:{
-                if (msArrNormalUser == null){
-                    synchronized(GrantedAuthorityImpl.class){
-                        if (msArrNormalUser == null){
-                            msArrNormalUser = new ArrayList<GrantedAuthorityImpl>();
-                            msArrNormalUser.add(new GrantedAuthorityImpl(emType.toStrValue()));
-                        }
-                    }
-                }
-            }
-            return msArrNormalUser;
-            case NORMAL_ADMIN:{
-                if (msArrAdmin == null){
-                    synchronized(GrantedAuthorityImpl.class){
-                        if (msArrAdmin == null){
-                            msArrAdmin = new ArrayList<GrantedAuthorityImpl>();
-                            msArrAdmin.add(new GrantedAuthorityImpl(emType.toStrValue()));
-                        }
-                    }
-                }
-            }
-            return msArrAdmin;
-            default:
-                break;
-        }
-        return null;
-    }
-
-    public static LoginUserRoleType getRoleTypeByAuthority(List<GrantedAuthorityImpl> authorityList){
-        if (authorityList == msArrRootAdmin)
-            return LoginUserRoleType.ROOT_ADMIN;
-        else if (authorityList == msArrAdmin)
-            return LoginUserRoleType.NORMAL_ADMIN;
-        else if (authorityList == msArrNormalUser)
-            return LoginUserRoleType.USER;
-        else
-            return LoginUserRoleType.GUEST;
-    }
-}
-

+ 0 - 138
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/JWTAuthenticationFilter.java

@@ -1,138 +0,0 @@
-package com.shkpr.service.customgateway.core.filter;
-
-import com.global.base.log.LogLevelFlag;
-import com.global.base.log.LogPrintMgr;
-import com.shkpr.service.customgateway.core.utils.HttpTool;
-import com.shkpr.service.customgateway.core.utils.TokenAuthenticationService;
-import com.shkpr.service.customgateway.core.constants.ApiURI;
-import com.shkpr.service.customgateway.core.constants.LogFlagBusiType;
-import com.shkpr.service.customgateway.core.constants.ResponseCode;
-import com.shkpr.service.customgateway.core.exception.SelfAuthFilterException;
-import com.shkpr.service.customgateway.core.storage.GlobalData;
-import org.springframework.security.authentication.AccountExpiredException;
-import org.springframework.security.authentication.AuthenticationManager;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.authentication.CredentialsExpiredException;
-import org.springframework.security.core.Authentication;
-import org.springframework.security.core.context.SecurityContextHolder;
-import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
-import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
-import org.springframework.security.web.util.matcher.RequestMatcher;
-import org.springframework.util.AntPathMatcher;
-import org.springframework.util.PathMatcher;
-
-import javax.servlet.FilterChain;
-import javax.servlet.ServletException;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-
-/**
- * Token过滤器,检验所有请求的Token是否合法
- * 从http头的Authorization 项读取token数据,然后校验token的合法性
- * 如果校验通过,就认为这是一个取得授权的合法请求
- */
-public class JWTAuthenticationFilter extends BasicAuthenticationFilter {
-    protected String mStrThisSampleName = null;
-    protected JWTControllerCheck mControllerCheck = null;
-    private RequestMatcher mRequestMatcher = null;
-    private PathMatcher mPathMatcher = null;
-
-    public JWTAuthenticationFilter(AuthenticationManager authenticationManager){
-        super(authenticationManager);
-        this.mStrThisSampleName = this.getClass().getSimpleName();
-        mPathMatcher = new AntPathMatcher();
-    }
-
-    public JWTAuthenticationFilter(String url, AuthenticationManager authenticationManager){
-        super(authenticationManager);
-        this.mStrThisSampleName = this.getClass().getSimpleName();
-        if (url != null && !url.isEmpty())
-            this.mRequestMatcher = new AntPathRequestMatcher(url);
-        mPathMatcher = new AntPathMatcher();
-    }
-
-    public void setControllerCheck(JWTControllerCheck mControllerCheck) {
-        this.mControllerCheck = mControllerCheck;
-    }
-
-    @Override
-    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
-        if (this.mRequestMatcher != null && !this.mRequestMatcher.matches(request)){
-            chain.doFilter(request, response);
-            return;
-        }
-
-        //文件映射放行
-        if (this.mPathMatcher != null && (this.mPathMatcher.match(
-                String.format("%s%s", request.getContextPath(), ApiURI.URI_GIS_SURVEY_H + "/" + ApiURI.URI_XXX_SYS_CHECK_RESULTS + "/**"),
-                request.getRequestURI())
-                || this.mPathMatcher.match(
-                String.format("%s%s", request.getContextPath(), ApiURI.URI_GIS_SURVEY_H + "/" + ApiURI.URI_XXX_TEMP_FILES + "/**"),
-                request.getRequestURI())
-                || this.mPathMatcher.match(
-                String.format("%s%s", request.getContextPath(), ApiURI.URI_GIS_SURVEY_H + "/" + ApiURI.URI_XXX_ASYNC_RESULTS + "/**"),
-                request.getRequestURI())
-        )) {
-            chain.doFilter(request, response);
-            return;
-        }
-
-        if (mControllerCheck != null && !mControllerCheck.checkRequest(request, response))  //当前URI已匹配成功,但Request请求格式不对,不再向后传递
-            return;
-
-        int nStatusCode = HttpServletResponse.SC_OK;
-        Authentication authentication = null;
-        try {
-            authentication = TokenAuthenticationService.getAuthentication(request, mControllerCheck.skipCheckAuthToPermit(request, response));
-            if (authentication != null)
-                SecurityContextHolder.getContext().setAuthentication(authentication); //不设置setAuthentication(authentication)将默认返回403,得不到正确结果
-        }
-        /* !!! 注:SecurityContextHolder.getContext().getAuthentication() == null时response.setStatus(xxx)无效,response.status总为403 !!! */
-        catch (BadCredentialsException e){
-            //无Token或者非法的Token
-            nStatusCode = ResponseCode.STATUS_INVALID_TOKEN.getCode();
-            HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_INVALID_TOKEN);
-            //System.out.println(e.getMessage());
-        }catch (CredentialsExpiredException e){
-            //非法Token,或已过期
-            nStatusCode = ResponseCode.STATUS_EXPIRED_TOKEN.getCode();
-            HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_EXPIRED_TOKEN);
-            //System.out.println(e.getMessage());
-        }catch (AccountExpiredException e){
-            //还未注册过,需要注册
-            nStatusCode = ResponseCode.STATUS_NOT_LOGGED_IN.getCode();
-            HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_NOT_LOGGED_IN);
-            //System.out.println(e.getMessage());
-        }catch (SelfAuthFilterException e){
-            nStatusCode = e.getErrorCode();
-            HttpTool.handlerHttpErrorStatus(response, e.getErrorCode(), e.getMessage());
-            //System.out.println(e.getMessage());
-        }catch (Exception e){
-            //其他错误
-            nStatusCode = ResponseCode.STATUS_ACCESS_DENY.getCode();
-            HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_ACCESS_DENY);
-            //System.out.println(e.getMessage());
-        }
-
-        if (authentication == null){
-            //SecurityContextHolder.getContext().setAuthentication(null);           //Token不合法时需要设置setAuthentication(null),不然response仍然返回200并且携带数据结果
-                                                                                   //解决bug:最近一次验证成功过,如此次未验证成功且不设置setAuthentication(null)的话,response.status仍然为200且会携带数据结果
-            if (GlobalData.getInstance().isHttpStatusAlready200()){
-                if (nStatusCode == HttpServletResponse.SC_OK)
-                    HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_ACCESS_DENY);
-            }else{
-                if (response.getStatus() == HttpServletResponse.SC_OK)
-                    HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_ACCESS_DENY);
-            }
-
-            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_WARN, LogFlagBusiType.BUSI_AUTH.toStrValue(), "JWTAuthenticationFilter"
-                    , String.format("Auth Failed Uri{%s} Remote{%s:%d}"
-                            ,request.getRequestURI()
-                            ,request.getRemoteAddr()
-                            ,request.getRemotePort()));
-            return;
-        }
-        chain.doFilter(request, response);
-    }
-}

+ 47 - 45
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/JWTControllerCheck.java

@@ -4,17 +4,18 @@ package com.shkpr.service.customgateway.core.filter;
 import com.global.base.log.LogLevelFlag;
 import com.global.base.log.LogPrintMgr;
 import com.global.base.tools.FastJsonUtil;
-import com.shkpr.service.customgateway.core.utils.CommTool;
-import com.shkpr.service.customgateway.core.utils.HttpTool;
-import com.shkpr.service.customgateway.core.utils.TokenAuthenticationService;
 import com.shkpr.service.customgateway.core.constants.LogFlagBusiType;
 import com.shkpr.service.customgateway.core.constants.ResponseCode;
 import com.shkpr.service.customgateway.core.storage.GlobalData;
+import com.shkpr.service.customgateway.core.utils.CommTool;
+import com.shkpr.service.customgateway.core.utils.RequestUtil;
+import com.shkpr.service.customgateway.core.utils.ResponseUtil;
 
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import javax.validation.ConstraintViolation;
 import javax.validation.Validator;
+import java.io.IOException;
 import java.util.Enumeration;
 import java.util.HashMap;
 import java.util.Map;
@@ -25,17 +26,18 @@ import java.util.concurrent.atomic.AtomicInteger;
  * 该类主要用来校验Controller的request头和request参数
  */
 public class JWTControllerCheck {
+    private final AtomicInteger mTmpIndex = new AtomicInteger(0);
     protected Validator mValidator = null;//由于该类不是@Component或@Bean,所以无法对Validator msValidator使用@Autowired
     protected Map<String, String> mMapURI2Method;
     protected String mStrThisSampleName = null;
-    private AtomicInteger mTmpIndex = new AtomicInteger(0);
-    public JWTControllerCheck(Map<String, String> mapURI2Method){
+
+    public JWTControllerCheck(Map<String, String> mapURI2Method) {
         this.mMapURI2Method = mapURI2Method;
         this.mValidator = GlobalData.getInstance().getValidForParam();
         this.mStrThisSampleName = this.getClass().getSimpleName();
     }
 
-    public boolean checkRequest(HttpServletRequest request, HttpServletResponse response){
+    public boolean checkRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
         //解决跨域请求问题
         response.setHeader("Access-Control-Allow-Origin", "*");
         response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT");
@@ -52,14 +54,11 @@ public class JWTControllerCheck {
             return false;
         if (!checkRequestParam(request, response))
             return false;
-        if (!checkRequestBody(request, response))
-            return false;
-        return true;
+        return checkRequestBody(request, response);
     }
 
 
-
-    protected boolean checkServerInternet(HttpServletRequest request, HttpServletResponse response){
+    protected boolean checkServerInternet(HttpServletRequest request, HttpServletResponse response) {
         /*if (!DataTransferMgr.getInstance().isConnected()){
             response.setStatus(ResponseCode.STATUS_SERVER_NET_DISCONN_OR_BUSY.toInt());//服务器端网络异常
             return false;
@@ -67,7 +66,7 @@ public class JWTControllerCheck {
         return true;
     }
 
-    protected boolean checkMaxConcurrentRequest(HttpServletRequest request, HttpServletResponse response){
+    protected boolean checkMaxConcurrentRequest(HttpServletRequest request, HttpServletResponse response) {
         /*if (DataTransferMgr.getInstance().getLiveUnitClient() > GlobalData.getInstance().getMaxConcurrentRequest()){
             response.setStatus(ResponseCode.STATUS_MAX_CONCURRENT_REQUEST_COUNT.toInt());//超过了最大并发请求数
             return false;
@@ -75,77 +74,77 @@ public class JWTControllerCheck {
         return true;
     }
 
-    protected boolean checkRequestHead(HttpServletRequest request, HttpServletResponse response){
+    protected boolean checkRequestHead(HttpServletRequest request, HttpServletResponse response) throws IOException {
         boolean bResult = true;
         if (mMapURI2Method == null)
             return bResult;
 
         String strOldMethod = mMapURI2Method.get(request.getRequestURI());
-        if (strOldMethod == null){
-            for (Map.Entry<String,String> entry:mMapURI2Method.entrySet()){
+        if (strOldMethod == null) {
+            for (Map.Entry<String, String> entry : mMapURI2Method.entrySet()) {
                 String uri = entry.getKey();
                 String method = entry.getValue();
-                if (CommTool.isTheThisFormatMatch(uri, request.getRequestURI())){
+                if (CommTool.isTheThisFormatMatch(uri, request.getRequestURI())) {
                     strOldMethod = method;
                     break;
                 }
             }
         }
-        if (strOldMethod != null){
+        if (strOldMethod != null) {
             String submitMehtod = request.getMethod();
-            submitMehtod = submitMehtod!=null ? submitMehtod.toLowerCase():"xxx";
+            submitMehtod = submitMehtod != null ? submitMehtod.toLowerCase() : "xxx";
 
-            if (submitMehtod.equalsIgnoreCase(strOldMethod)){
+            if (submitMehtod.equalsIgnoreCase(strOldMethod)) {
                 String strContentType = request.getHeader("Content-Type");
-                strContentType = strContentType!=null ? strContentType.toLowerCase():"xxx";
+                strContentType = strContentType != null ? strContentType.toLowerCase() : "xxx";
                 String strContent = request.getHeader("Content");                       //经测试发现ios只能设置Content
-                strContent = strContent!=null ? strContent.toLowerCase():"xxx";
+                strContent = strContent != null ? strContent.toLowerCase() : "xxx";
 
                 String strAccept = request.getHeader("Accept");
-                strAccept = strAccept!=null ? strAccept.toLowerCase():"xxx";
+                strAccept = strAccept != null ? strAccept.toLowerCase() : "xxx";
 
-                String strCompare = TokenAuthenticationService.HEADER_CONTENT_TYPE;
+                String strCompare = "application/json;charset=UTF-8";
                 strCompare = strCompare.toLowerCase();
-                String strShortCompare = TokenAuthenticationService.HEADER_SHORT_CONTENT_TYPE;
+                String strShortCompare = "application/json";
                 strShortCompare = strShortCompare.toLowerCase();
 
                 if (submitMehtod.equals("post")
                         || submitMehtod.equals("delete")
-                        || submitMehtod.equals("put")){
+                        || submitMehtod.equals("put")) {
                     //boolean b = strAccept.contains(strCompare);
                     if (!strContentType.contains(strCompare)
                             && !strContentType.contains(strShortCompare)
                             && !strContent.contains(strCompare)
                             && !strContent.contains(strShortCompare)
                             && !strAccept.contains(strCompare)
-                            && !strAccept.contains(strShortCompare)){
-                        HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_INVALID_CONTENT_TYPE);//POST/DELETE/PUT时Content-Type不对
+                            && !strAccept.contains(strShortCompare)) {
+                        ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_INVALID_CONTENT_TYPE, true);//POST/DELETE/PUT时Content-Type不对
                         bResult = false;
                     }
-                }else if (submitMehtod.equals("get")){
+                } else if (submitMehtod.equals("get")) {
                     /*String strAuthToken = request.getHeader("authortoken");
                     String strUserAgent = request.getHeader(ApiURI.HEADER_USER_AGENT);
                     if (!StringUtils.isEmpty(strAuthToken)
                             || ("apk".equals(CommTool.getPlatformByAgent(strUserAgent)) && !strContentType.contains(strCompare))){
-                        HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_ACCESS_DENY);
+                        ResponseUtil.writeResponseCode();(response, ResponseCode.STATUS_ACCESS_DENY);
                         bResult = false;
                     }*/
                 }
 
-                if (!bResult && mTmpIndex.incrementAndGet()%10==0){
+                if (!bResult && mTmpIndex.incrementAndGet() % 10 == 0) {
                     Map<String, String> mapHeads = new HashMap<String, String>();
                     Enumeration<String> headerNames = request.getHeaderNames();
                     while (headerNames.hasMoreElements()) {
-                        String key = (String)headerNames.nextElement();
+                        String key = headerNames.nextElement();
                         String value = "";
                         Enumeration<String> headerValues = request.getHeaders(key);
-                        while (headerValues.hasMoreElements()){
-                            value = value + (String)headerValues.nextElement();
+                        while (headerValues.hasMoreElements()) {
+                            value = value + headerValues.nextElement();
                         }
                         mapHeads.put(key, value);
                     }
 
-                    String strAddress = HttpTool.getIpAddress(request);
+                    String strAddress = RequestUtil.getIpAddress(request);
                     LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_WARN, LogFlagBusiType.BUSI_AUTH.toStrValue(), mStrThisSampleName, "Inner"
                             , String.format("uri:{%s %s} remote_address:{%s} illegal request for printing... %s"
                                     , submitMehtod
@@ -153,31 +152,34 @@ public class JWTControllerCheck {
                                     , strAddress
                                     , FastJsonUtil.toJSON(mapHeads)));
                 }
-            } else{
-                HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_ERROR_REQUEST_METHOD);//URI对应的Method不对
+            } else {
+                ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_ERROR_REQUEST_METHOD, true);//URI对应的Method不对
                 bResult = false;
             }
-        } else{
-            HttpTool.handlerHttpErrorStatus(response, ResponseCode.STATUS_NOT_MATCHED_URI);//找不到对应的URI
+        } else {
+            ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_NOT_MATCHED_URI, true);//找不到对应的URI
             bResult = false;
         }
         return bResult;
     }
 
-    protected boolean checkRequestParam(HttpServletRequest request, HttpServletResponse response){ return true; }
+    protected boolean checkRequestParam(HttpServletRequest request, HttpServletResponse response) {
+        return true;
+    }
 
-    protected boolean checkRequestBody(HttpServletRequest request, HttpServletResponse response){
+    protected boolean checkRequestBody(HttpServletRequest request, HttpServletResponse response) {
         return true;
     }
 
-    public <T> boolean checkObjectByValidator(T object, Class<?>... classForObject){
-        if (mValidator != null){
+    public <T> boolean checkObjectByValidator(T object, Class<?>... classForObject) {
+        if (mValidator != null) {
             Set<ConstraintViolation<T>> constraintViolations = mValidator.validate(object, classForObject);
-            if (!(constraintViolations == null || constraintViolations.size() <= 0))
-                return false;
+            return constraintViolations == null || constraintViolations.size() <= 0;
         }
         return true;
     }
 
-    public boolean skipCheckAuthToPermit(HttpServletRequest request, HttpServletResponse response){return false;}
+    public boolean skipCheckAuthToPermit(HttpServletRequest request, HttpServletResponse response) {
+        return false;
+    }
 }

+ 102 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/filter/TokenFilter.java

@@ -0,0 +1,102 @@
+package com.shkpr.service.customgateway.core.filter;
+
+import com.global.base.log.LogLevelFlag;
+import com.global.base.log.LogPrintMgr;
+import com.shkpr.service.customgateway.core.constants.LogFlagBusiType;
+import com.shkpr.service.customgateway.core.constants.ResponseCode;
+import com.shkpr.service.customgateway.core.properties.GlobalProperties;
+import com.shkpr.service.customgateway.core.properties.SecurityProperties;
+import com.shkpr.service.customgateway.core.utils.ResponseUtil;
+import com.shkpr.service.customgateway.core.utils.SecurityUtil;
+import com.shkpr.service.customgateway.core.utils.TokenUtil;
+import lombok.NonNull;
+import org.springframework.security.authentication.AccountExpiredException;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.authentication.CredentialsExpiredException;
+import org.springframework.security.core.Authentication;
+import org.springframework.util.AntPathMatcher;
+import org.springframework.web.filter.OncePerRequestFilter;
+
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+/**
+ * token过滤器
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+public class TokenFilter extends OncePerRequestFilter {
+    private final GlobalProperties globalProperties;
+    private final SecurityProperties securityProperties;
+    private final TokenUtil tokenUtil;
+
+    public TokenFilter(GlobalProperties globalProperties, SecurityProperties securityProperties, TokenUtil tokenUtil) {
+        this.globalProperties = globalProperties;
+        this.securityProperties = securityProperties;
+        this.tokenUtil = tokenUtil;
+    }
+
+    /**
+     * {@inheritDoc}
+     */
+    @Override
+    protected void doFilterInternal(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull FilterChain chain) throws IOException, ServletException {
+        //如果忽略列表包含该url,则直接放行
+        if (securityProperties.getPermitPattern().stream()
+                .anyMatch(s -> new AntPathMatcher().match(String.format("%s%s", request.getContextPath(), s), request.getRequestURI()))) {
+            chain.doFilter(request, response);
+            return;
+        }
+
+        //解析认证
+        int code = HttpServletResponse.SC_OK;
+        Authentication authentication = null;
+        try {
+            authentication = tokenUtil.getAuthentication(request);
+        } catch (BadCredentialsException e) {
+            //无Token或者非法的Token
+            code = ResponseCode.STATUS_INVALID_TOKEN.getCode();
+            ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_INVALID_TOKEN, globalProperties.getHttpStatusAlready200());
+        } catch (CredentialsExpiredException e) {
+            //非法Token,或已过期
+            code = ResponseCode.STATUS_EXPIRED_TOKEN.getCode();
+            ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_EXPIRED_TOKEN, globalProperties.getHttpStatusAlready200());
+        } catch (AccountExpiredException e) {
+            //还未注册过,需要注册
+            code = ResponseCode.STATUS_NOT_LOGGED_IN.getCode();
+            ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_NOT_LOGGED_IN, globalProperties.getHttpStatusAlready200());
+        } catch (IllegalArgumentException e) {
+            //参数异常
+            code = ResponseCode.STATUS_EMPTY_TOKEN.getCode();
+            ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_EMPTY_TOKEN, globalProperties.getHttpStatusAlready200());
+        } catch (Exception e) {
+            //其他错误
+            code = ResponseCode.STATUS_ACCESS_DENY.getCode();
+            ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_ACCESS_DENY, globalProperties.getHttpStatusAlready200());
+        }
+
+        //空认证处理
+        if (authentication == null) {
+            if (globalProperties.getHttpStatusAlready200()) {
+                if (code == HttpServletResponse.SC_OK)
+                    ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_ACCESS_DENY, true);
+            } else if (response.getStatus() == HttpServletResponse.SC_OK)
+                ResponseUtil.writeResponseCode(response, ResponseCode.STATUS_ACCESS_DENY, false);
+
+            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_WARN, LogFlagBusiType.BUSI_AUTH.toStrValue(), "TokenFilter"
+                    , String.format("Auth Failed Uri{%s} Remote{%s:%d}"
+                            , request.getRequestURI()
+                            , request.getRemoteAddr()
+                            , request.getRemotePort()));
+            return;
+        }
+
+        //存入上下文,并放行
+        SecurityUtil.setAuthentication(authentication);
+        chain.doFilter(request, response);
+    }
+}

+ 2 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/properties/GatewayProperties.java

@@ -18,6 +18,8 @@ import java.util.Map;
 public class GatewayProperties {
     /**
      * 路由集合
+     * <p>key: id</p>
+     * <p>value: 路径</p>
      */
     private Map<String, String> routes;
 }

+ 48 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/properties/GlobalProperties.java

@@ -0,0 +1,48 @@
+package com.shkpr.service.customgateway.core.properties;
+
+
+import com.global.base.tools.RandomUtil;
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+/**
+ * 全局属性
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Getter
+@Setter
+@ConfigurationProperties(prefix = "global")
+public class GlobalProperties {
+    /**
+     * Http Status是否总是返回200ok,即所有错误码只能在body当中
+     */
+    private Boolean HttpStatusAlready200 = true;
+    /**
+     * 启用本地缓存策略
+     */
+    private Boolean localCache = true;
+    /**
+     * cpu核心数
+     */
+    private Integer cpuCores = Runtime.getRuntime().availableProcessors();
+    /**
+     * 内部操作人账号
+     */
+    private String internalOperatorAccount = "TriCooperation";
+    /**
+     * 内部操作人密码
+     */
+    private String internalOperatorPassword = "123@asd";
+    /**
+     * 内部信任口令
+     */
+    private String InternalCallPassword = RandomUtil.getRandomStr(8);
+    /**
+     * 服务上线的时间(时间戳/UTC)
+     * <p>默认为2020-02-01 00:00:00</p>
+     */
+    private Long serviceOnline = 1580486400000L;
+}

+ 11 - 2
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/properties/InfluxDbProperties.java

@@ -1,7 +1,10 @@
 package com.shkpr.service.customgateway.core.properties;
 
-import lombok.AllArgsConstructor;
 import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+import java.time.Duration;
 
 /**
  * influxdb属性
@@ -11,7 +14,8 @@ import lombok.Getter;
  * @since 0.0.1-dev
  */
 @Getter
-@AllArgsConstructor
+@Setter
+@ConfigurationProperties(prefix = "spring.influx")
 public class InfluxDbProperties {
     /**
      * 连接地址
@@ -32,4 +36,9 @@ public class InfluxDbProperties {
      * 数据库
      */
     private String database;
+
+    /**
+     * 读取超时时间
+     */
+    private Duration readTimeout = Duration.ofSeconds(60);
 }

+ 9 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/properties/SecurityProperties.java

@@ -5,6 +5,7 @@ import lombok.Getter;
 import lombok.Setter;
 import org.springframework.boot.context.properties.ConfigurationProperties;
 
+import java.time.Duration;
 import java.util.Collections;
 import java.util.List;
 
@@ -19,6 +20,14 @@ import java.util.List;
 @ConfigurationProperties(prefix = "security")
 public class SecurityProperties {
     /**
+     * 过期时间
+     */
+    private Duration expiration = Duration.ofDays(7);
+    /**
+     * 密钥
+     */
+    private String secret = "TRICP_ALAM_DMA";
+    /**
      * 放行的请求,ant格式
      */
     private List<String> permitPattern = Collections.emptyList();

+ 1 - 1
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/CommTool.java

@@ -461,7 +461,7 @@ public class CommTool {
 
     public static boolean isRootAdminID(String userId){
         return CommDefine.ADMIN_USER_ID.equals(userId)
-                || CommDefine.INTERNAL_OPERATOR_ID.equals(userId);
+                || CommDefine.INTERNAL_OPERATOR_USER_ID.equals(userId);
     }
 
     //84坐标系转2000坐标系

Tiedoston diff-näkymää rajattu, sillä se on liian suuri
+ 0 - 208
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/HttpTool.java


+ 231 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/InfluxDbUtil.java

@@ -0,0 +1,231 @@
+package com.shkpr.service.customgateway.core.utils;
+
+import com.global.base.log.LogLevelFlag;
+import com.global.base.log.LogPrintMgr;
+import com.shkpr.service.customgateway.core.annotation.InfluxDbMapping;
+import com.shkpr.service.customgateway.core.constants.InfluxdbMetadata;
+import com.shkpr.service.customgateway.core.constants.LogFlagBusiType;
+import com.shkpr.service.customgateway.core.properties.InfluxDbProperties;
+import lombok.extern.slf4j.Slf4j;
+import org.influxdb.InfluxDB;
+import org.influxdb.InfluxDBException;
+import org.influxdb.dto.BatchPoints;
+import org.influxdb.dto.Point;
+import org.influxdb.dto.Query;
+import org.influxdb.dto.QueryResult;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.time.LocalDateTime;
+import java.time.ZonedDateTime;
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/**
+ * influxdb工具类
+ *
+ * @author 欧元劲驰
+ * @since 1.0.0
+ **/
+@Component
+@Slf4j
+public class InfluxDbUtil {
+    /**
+     * log
+     */
+    private static final String mStrClassName = "InfluxDbUtil";
+    private static final String mBizType = LogFlagBusiType.BUSI_ALL.toStrValue();
+    final
+    InfluxDB influxDb;
+    final
+    InfluxDbProperties properties;
+
+    public InfluxDbUtil(InfluxDbProperties properties, InfluxDB influxDb) {
+        this.influxDb = influxDb;
+        this.properties = properties;
+        try {
+            //查询数据库信息
+            QueryResult queryResult = influxDb.query(new Query(InfluxdbMetadata.Command.SHOW_DATABASE, null));
+            List<String> databases = getValues(queryResult).stream()
+                    .map(database -> database.get(0).toString())
+                    .collect(Collectors.toList());
+            //数据库不存在,则创建数据库
+            if (databases.isEmpty() || !databases.contains(properties.getDatabase()))
+                influxDb.query(new Query(InfluxdbMetadata.Command.CREATE_DATABASE + properties.getDatabase(), null));
+        } catch (InfluxDBException e) {
+            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR, mBizType, mStrClassName
+                    , String.format("尝试初始化数据库失败 error:%s", e)
+            );
+        }
+
+        //设置要使用的数据库
+        influxDb.setDatabase(properties.getDatabase());
+    }
+
+    /**
+     * 获取series
+     *
+     * @param queryResult 查询结果
+     * @return series
+     */
+    public static QueryResult.Series getSeries(QueryResult queryResult) {
+        if (queryResult == null) return null;
+
+        //获取结果集合
+        List<QueryResult.Result> results = queryResult.getResults();
+        if (results == null || results.isEmpty()) return null;
+
+        //获取第一个结果
+        QueryResult.Result result = results.get(0);
+        if (result == null) return null;
+
+        //获取series
+        List<QueryResult.Series> series = result.getSeries();
+        if (series == null || series.isEmpty()) return null;
+
+        //获取第一个series
+        return series.get(0);
+    }
+
+    /**
+     * 获取值集合
+     *
+     * @param queryResult 查询结果
+     * @return 值集合
+     */
+    public static List<List<Object>> getValues(QueryResult queryResult) {
+        //获取series
+        QueryResult.Series firstSeries = getSeries(queryResult);
+        if (firstSeries == null) return Collections.emptyList();
+
+        //获取值集合
+        List<List<Object>> values = firstSeries.getValues();
+        return values != null ? values : Collections.emptyList();
+    }
+
+    /**
+     * 插入
+     *
+     * @param point 点
+     * @return 插入状态
+     */
+    public Boolean insert(Point point) {
+        try {
+            influxDb.write(point);
+            return true;
+        } catch (Exception e) {
+            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR, mBizType, mStrClassName
+                    , String.format("插入InfluxDb失败 error:%s", e)
+            );
+            return false;
+        }
+    }
+
+    /**
+     * 批量插入
+     *
+     * @param points 批量点
+     * @return 插入状态
+     */
+    public Boolean insertBatch(BatchPoints points) {
+        try {
+            influxDb.write(points);
+            return true;
+        } catch (Exception e) {
+            LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR, mBizType, mStrClassName
+                    , String.format("插入InfluxDb失败 error:%s", e)
+            );
+            return false;
+        }
+    }
+
+    /**
+     * 查询
+     *
+     * @param sql   sql
+     * @param clazz 实体类
+     * @param <E>   实体类类型
+     * @return 实体类集合
+     */
+    public <E> List<E> query(String sql, Class<E> clazz) {
+        //执行查询
+        QueryResult queryResult = influxDb.query(new Query(sql, properties.getDatabase()));
+        QueryResult.Series series = getSeries(queryResult);
+        if (series == null) return Collections.emptyList();
+        LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_INFO, mBizType, mStrClassName
+                , String.format(
+                        "读取InfluxDb成功,数据量:%s,开始解析"
+                        , series.getValues().size()
+                )
+        );
+
+        //获取字段
+        List<String> columns = series.getColumns();
+        //字段映射
+        Map<Integer, Field> fieldMap = Arrays.stream(clazz.getDeclaredFields())
+                //过滤需要导出的字段
+                .filter(f -> f.isAnnotationPresent(InfluxDbMapping.class))
+                //设置字段公开
+                .peek(f -> f.setAccessible(true))
+                .collect(Collectors.toMap(
+                        f -> {
+                            //获取映射值
+                            String mapping = f.getAnnotation(InfluxDbMapping.class).value();
+                            //获取对应的索引
+                            return IntStream.range(0, columns.size())
+                                    //过滤相同的值
+                                    .filter(index -> columns.get(index).equals(mapping))
+                                    .findFirst().orElse(-1);
+                        }, Function.identity(),
+                        (it1, it2) -> it2,
+                        ConcurrentHashMap::new
+                ));
+
+        //解析数据
+        List<E> dates = series.getValues().parallelStream().map(value -> {
+            try {
+                //实列化数据
+                E data = clazz.getDeclaredConstructor().newInstance();
+                //遍历字段
+                for (Map.Entry<Integer, Field> fieldEntry : fieldMap.entrySet()) {
+                    //跳过未找到的字段
+                    if (fieldEntry.getKey() == -1) continue;
+                    //获取项
+                    Object item = value.get(fieldEntry.getKey());
+                    //设置字段
+                    if (fieldEntry.getValue().getType().equals(LocalDateTime.class))
+                        fieldEntry.getValue().set(data,
+                                item != null ? ZonedDateTime.parse(item.toString())
+                                        .withZoneSameInstant(TimeZone.getDefault().toZoneId())
+                                        .toLocalDateTime()
+                                        : null);
+                    else if (fieldEntry.getValue().getType().equals(Double.class)) {
+                        fieldEntry.getValue().set(data, item != null ? Double.parseDouble(item.toString()) : null);
+                    } else fieldEntry.getValue().set(data, item);
+                }
+                //存入数据
+                return data;
+            } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
+                     NoSuchMethodException e) {
+                LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_ERROR, mBizType, mStrClassName
+                        , String.format("构建数据失败 error:%s", e)
+                );
+                return null;
+            }
+        }).filter(Objects::nonNull).collect(Collectors.toList());
+
+        LogPrintMgr.getInstance().printLogMsg(LogLevelFlag.LOG_INFO, mBizType, mStrClassName
+                , String.format(
+                        "解析InfluxDb成功,数据量:%s"
+                        , series.getValues().size()
+                )
+        );
+
+        return dates;
+    }
+
+}

+ 39 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/RequestUtil.java

@@ -0,0 +1,39 @@
+package com.shkpr.service.customgateway.core.utils;
+
+import com.shkpr.service.customgateway.core.constants.Api;
+import org.apache.commons.lang3.StringUtils;
+
+import javax.servlet.http.HttpServletRequest;
+
+/**
+ * Request工具
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+public class RequestUtil {
+    /**
+     * 获取ip地址
+     *
+     * @param request request
+     * @return ip地址
+     */
+    public static String getIpAddress(HttpServletRequest request) {
+        //ip头
+        String[] headers = {Api.Headers.X_SOURCE_IP, "X-Real-IP", "X-Forwarded-For", "Proxy-Client-IP",
+                "WL-Proxy-Client-IP"};
+
+        //从头获取ip
+        String ip = null;
+        for (String header : headers) {
+            ip = request.getHeader(header);
+            if (StringUtils.isNoneBlank(ip) && !"unknown".equalsIgnoreCase(ip)) break;
+        }
+
+        //回退方案
+        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) ip = request.getRemoteAddr();
+
+        //处理多IP情况
+        return (StringUtils.isNoneBlank(ip) && ip.contains(",")) ? ip.split(",")[0].trim() : ip;
+    }
+}

+ 101 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/ResponseUtil.java

@@ -0,0 +1,101 @@
+package com.shkpr.service.customgateway.core.utils;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.shkpr.service.customgateway.core.constants.ResponseCode;
+import com.shkpr.service.customgateway.core.domain.ResponseRes;
+import org.apache.commons.lang3.BooleanUtils;
+import org.apache.http.HttpStatus;
+import org.springframework.http.MediaType;
+
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * Response工具
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+public class ResponseUtil {
+    private static final ObjectMapper objectMapper = new ObjectMapper();
+
+    /**
+     * 输出json
+     *
+     * @param response response
+     * @param value    json值
+     * @throws IOException io异常
+     */
+    public static void writeJson(HttpServletResponse response, Object value) throws IOException {
+        handleCors(response);
+
+        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
+        response.getWriter().write(objectMapper.writeValueAsString(value));
+    }
+
+    /**
+     * 输出弹窗
+     *
+     * @param response response
+     * @param message  弹窗内容
+     * @throws IOException id异常
+     */
+    public static void writeAlert(HttpServletResponse response, String message) throws IOException {
+        handleCors(response);
+
+        writeHtml(response, String.format("<script>alert('%s');</script>", message));
+    }
+
+    /**
+     * 输出html页面
+     *
+     * @param response response
+     * @param html     html页面
+     * @throws IOException id异常
+     */
+    public static void writeHtml(HttpServletResponse response, String html) throws IOException {
+        handleCors(response);
+        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
+        response.setContentType(MediaType.TEXT_HTML_VALUE);
+
+        response.getWriter().write(html);
+    }
+
+    /**
+     * 输出code
+     *
+     * @param response             response
+     * @param code                 code
+     * @param httpStatusAlready200 始终http状态200
+     */
+    public static void writeResponseCode(HttpServletResponse response, ResponseCode code, Boolean httpStatusAlready200) throws IOException {
+        handleCors(response);
+        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
+        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
+
+        //设置状态
+        response.setStatus(BooleanUtils.isTrue(httpStatusAlready200) ? HttpStatus.SC_OK : code.getCode());
+
+        //构建结果
+        ResponseRes<String> result = new ResponseRes<>();
+        result.setRescode(code.getCode() + "");
+        result.setResmsg(code.getMessage());
+        result.setResdata("");
+        result.setTimestamp(System.currentTimeMillis());
+
+        //输出json
+        response.getWriter().write(objectMapper.writeValueAsString(result));
+    }
+
+    /**
+     * 处理跨域
+     *
+     * @param response response
+     */
+    private static void handleCors(HttpServletResponse response) {
+        response.setHeader("Access-Control-Allow-Origin", "*");
+        response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT");
+        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type,Authorization");
+    }
+}

+ 59 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/SecurityUtil.java

@@ -0,0 +1,59 @@
+package com.shkpr.service.customgateway.core.utils;
+
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.context.SecurityContextHolder;
+
+/**
+ * Security工具类
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+public class SecurityUtil {
+
+    /**
+     * 设置认证信息
+     *
+     * @param authentication 认证信息
+     */
+    public static void setAuthentication(Authentication authentication) {
+        SecurityContextHolder.getContext().setAuthentication(authentication);
+    }
+//
+//    /**
+//     * 获取当前登陆的用户
+//     *
+//     * @return 用户
+//     */
+//    public static Mono<UserDetailsDto> getUser() {
+//        return ReactiveSecurityContextHolder.getContext().flatMap(securityContext -> {
+//            Authentication authentication = securityContext.getAuthentication();
+//            if (authentication != null && authentication.getPrincipal() instanceof UserDetailsDto) {
+//                return Mono.just((UserDetailsDto) authentication.getPrincipal());
+//            }
+//            return Mono.empty();
+//        });
+//    }
+//
+//    /**
+//     * 获取当前登陆的用户的id
+//     *
+//     * @return 用户
+//     */
+//    public static Mono<Long> getUserId() {
+//        //如用户不为空,则返回用户id
+//        return getUser().flatMap(user -> (user != null) ? Mono.just(user.getId()) : Mono.empty());
+//    }
+//
+//    /**
+//     * 获取当前登陆的用户的组织id
+//     *
+//     * @return 组织id
+//     * @deprecated 当前平台不使用组织架构, 故弃用该方法
+//     */
+//    @Deprecated
+//    public static Mono<Long> getOrgId() {
+//        //如用户不为空,则返回用户id
+//        return getUser().flatMap(user -> (user != null) ?  Mono.just(user.getId()) : Mono.empty());
+//    }`
+}

+ 0 - 264
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/TokenAuthenticationService.java

@@ -1,264 +0,0 @@
-package com.shkpr.service.customgateway.core.utils;
-
-import com.shkpr.service.customgateway.core.constants.ApiURI;
-import com.shkpr.service.customgateway.core.constants.CommDefine;
-import com.shkpr.service.customgateway.core.constants.ResponseCode;
-import com.shkpr.service.customgateway.core.domain.AuthTokenData;
-import com.shkpr.service.customgateway.core.exception.SelfAuthFilterException;
-import com.shkpr.service.customgateway.core.filter.GrantedAuthorityImpl;
-import com.shkpr.service.customgateway.core.storage.GlobalData;
-import com.shkpr.service.customgateway.core.storage.UserStore;
-import io.jsonwebtoken.Claims;
-import io.jsonwebtoken.ExpiredJwtException;
-import io.jsonwebtoken.Jwts;
-import io.jsonwebtoken.SignatureAlgorithm;
-import org.springframework.security.authentication.BadCredentialsException;
-import org.springframework.security.authentication.CredentialsExpiredException;
-import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.Authentication;
-import org.springframework.util.StringUtils;
-
-import javax.servlet.http.HttpServletRequest;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.Map;
-
-public class TokenAuthenticationService {
-    public static final int MIN_EXPIRATIONTIME = 7*60*24;                              // 默认Token过期时间为7天(单位:分钟)
-    public static final long MS_EXPIRATIONTIME = MIN_EXPIRATIONTIME*60*1000;         // 默认Token过期时间为7天(单位:毫秒)
-    public static final String SECRET = "TRICP_ALAM_DMA";                              // JWT密码
-    public static final String HEADER_STRING = "Authorization";                       // 存放Token的Header Key
-    public static final String HEADER_CONTENT_TYPE = "application/json;charset=UTF-8";
-    public static final String HEADER_SHORT_CONTENT_TYPE = "application/json";
-    public static final String SIGNATURE_KEY = "tri_coorperation_tech";              //签名秘钥
-    public static final String HEADER_SEQUENCE = "Sequence";
-    public static final String HEADER_USERID = "UUID";
-    public static final String HEADER_ROLEID = "RLID";
-
-    private static AuthTokenData generateToken(Map<String, Object> claims){
-        return generateToken(claims, MIN_EXPIRATIONTIME);
-    }
-
-    private static AuthTokenData generateToken(Map<String, Object> claims, int expired){
-        String strFlagKey = "";
-        String strAccount = "";
-        String roleId = "";
-        try {
-            strFlagKey = (String)claims.get("flagkey");
-        } catch (Exception e){}
-        try {
-            strAccount = (String)claims.get("account");
-        } catch (Exception e){}
-        try {
-            roleId = (String)claims.get("roleid");
-        } catch (Exception e){}
-        return generateToken(strFlagKey, strAccount, roleId, expired);
-    }
-
-    public static AuthTokenData generateToken(String strFlagKey, String strAccount, String roleId, int expired){
-        /*Map<String, Object> claims = new HashMap<>(16);
-        //claims.put("sub", strUsername);
-        claims.put("flagkey", strFlagKey);
-        claims.put("account", strAccount);
-        claims.put("roleid", roleId);
-        return generateToken(claims, expired);*/
-        long nowMillis = System.currentTimeMillis();
-        Date dateExpired  = null;
-        String strToken = null;
-        try {
-            strToken = Jwts.builder()
-                    .setHeaderParam("typ", "JWT")
-                    .setHeaderParam("alg", "HS256")
-                    //.setAudience("APP")
-                    //.setIssuer("SERVICE")
-                    //.setId(UUID.randomUUID().toString())
-                    .setIssuedAt(new Date(nowMillis))
-                    .setExpiration(dateExpired = new Date(nowMillis + expired*60*1000))
-                    .signWith(SignatureAlgorithm.HS256, SECRET.getBytes("UTF-8"))
-                    .claim("flagkey", strFlagKey)
-                    .claim("account", strAccount)
-                    .claim("roleid", roleId)
-                    .compact();
-        } catch (Exception e){
-            strToken = null;
-            e.printStackTrace();
-        }
-
-        return  StringUtils.isEmpty(strToken) ? null:new AuthTokenData(strToken
-                , dateExpired!=null ? dateExpired.getTime():System.currentTimeMillis()
-                , nowMillis
-                , strFlagKey);
-    }
-
-    private static Claims getClaimsFromToken(String token) throws ExpiredJwtException, Exception{
-        Claims claims = null;
-        try {
-            claims = Jwts.parser().setSigningKey(SECRET.getBytes("UTF-8")).parseClaimsJws(token).getBody();
-        }catch (ExpiredJwtException e){
-            claims = null;
-            throw e;
-        }catch (Exception e) {
-            claims = null;
-            throw e;
-        }
-        return claims;
-    }
-
-    public static String getFlagKeyFromToken(String token) throws ExpiredJwtException, Exception{
-        String strKey = null;
-        try {
-            Claims claims = getClaimsFromToken(token);
-            if (claims != null)
-                strKey = (String)claims.get("flagkey");
-        }catch (ExpiredJwtException e){
-            strKey = null;
-            throw e;
-        }catch (Exception e) {
-            strKey = null;
-            throw e;
-        }
-        return strKey;
-    }
-
-    public static AuthTokenData getAuthDataFromToken(String token) throws ExpiredJwtException, Exception{
-        AuthTokenData data = null;
-        try {
-            Claims claims = getClaimsFromToken(token);
-            if (claims != null){
-                String strKey = (String)claims.get("flagkey");
-                String strRoleId = (String)claims.get("roleid");
-                data = new AuthTokenData(token, claims.getExpiration().getTime(), claims.getIssuedAt().getTime(), strKey, strRoleId);
-            }
-        }catch (ExpiredJwtException e){
-            data = null;
-            throw e;
-        }catch (Exception e) {
-            data = null;
-            throw e;
-        }
-        return data;
-    }
-
-    public static String getUserIDFromToken(String token) throws ExpiredJwtException, Exception{
-        String strKey = null;
-        try {
-            strKey = getFlagKeyFromToken(token);
-        }catch (Exception e) {
-            strKey = null;
-            throw e;
-        }
-        int nIndex = (strKey != null) ? strKey.indexOf(":"):-1;
-        if (nIndex >= 0)
-            strKey = strKey.substring(nIndex+1);
-        return strKey;
-    }
-
-    public static Boolean isTokenExpired(String token){
-        try {
-            Claims claims = getClaimsFromToken(token);
-            if (claims != null){
-                Date expiration = claims.getExpiration();
-                return expiration.before(new Date());
-            }
-        } catch (ExpiredJwtException e){
-            return true;
-        } catch (Exception e) {
-            return true;
-        }
-        return true;
-    }
-
-    public static Boolean isTokenExpired(long lExpired){
-        return lExpired <= new Date().getTime();
-    }
-
-    public static AuthTokenData refreshToken(String token, int nExpired) throws ExpiredJwtException, Exception{
-        AuthTokenData tokenData = null;
-        try {
-            Claims claims = getClaimsFromToken(token);
-            if (claims != null){
-                tokenData = generateToken(claims, nExpired);
-            }
-        } catch (ExpiredJwtException e){
-            tokenData = null;
-            throw e;
-        } catch (Exception e) {
-            tokenData = null;
-            throw e;
-        }
-        return tokenData;
-    }
-
-    public static Boolean validateToken(String token) {
-        return !isTokenExpired(token);
-    }
-
-    public static Authentication getAuthentication(HttpServletRequest request, boolean isSkipAuthToPermit) throws Exception{
-        final String strAuthVerify = request.getHeader(ApiURI.HEADER_AUTH_VERIFY);
-        if (GlobalData.getInstance().getInternalCallPassword().equalsIgnoreCase(strAuthVerify)
-                || isSkipAuthToPermit){
-            try {
-                request.setAttribute(HEADER_USERID, CommDefine.INTERNAL_OPERATOR_ID);
-                request.setAttribute(HEADER_ROLEID, CommDefine.INTERNAL_OPERATOR_ROLE_ID);
-            }catch (Exception e){}
-
-            return new UsernamePasswordAuthenticationToken(CommDefine.INTERNAL_OPERATOR_ID,
-                    null,
-                    new ArrayList<GrantedAuthorityImpl>());
-        }
-
-        String strUri = request.getRequestURI();
-        String authHeader = request.getHeader(HEADER_STRING);
-        if (authHeader != null && authHeader.length() > 0 /*&& authHeader.startsWith(TOKEN_PREFIX)*/){
-            String authToken = authHeader/*authHeader.substring(TOKEN_PREFIX.length())*/;
-            AuthTokenData authData = null;
-            try {
-                authData = getAuthDataFromToken(authToken);
-            } catch (ExpiredJwtException e){
-                throw new CredentialsExpiredException("Invalidate token, token is expired.");
-            } catch (Exception e){
-                throw new BadCredentialsException("Invalidate Token, has no user.");
-            }
-
-            boolean bEasy = true;
-            if (bEasy && authData != null){
-                long lTimeLogout = UserStore.getInstance().getLogoutAccountTime(authData.getStrFlagKey());
-                if (lTimeLogout == -1){
-                    if (isTokenExpired(authData.getExpired()))
-                        throw new CredentialsExpiredException("Invalidate token, token is expired.");
-                }else {
-                    if (authData.getIssueAt() <= lTimeLogout)        //签发时间早于注销时间
-                        throw new BadCredentialsException("Invalidate Token, has no user.");
-                    else if (isTokenExpired(authData.getExpired())) //签发时间晚于注销时间,但已过期
-                        throw new CredentialsExpiredException("Invalidate token, token is expired.");
-                }
-
-                try {
-                    request.setAttribute(HEADER_USERID, authData.getStrFlagKey());
-                    request.setAttribute(HEADER_ROLEID, authData.getRoleid());
-                }catch (Exception e){}
-
-                return new UsernamePasswordAuthenticationToken(authData.getStrFlagKey(),
-                        null,
-                        new ArrayList<GrantedAuthorityImpl>());
-            }else{
-                throw new BadCredentialsException("Invalidate Token, has no user.");
-            }
-        }else {
-            throw new SelfAuthFilterException(ResponseCode.STATUS_EMPTY_TOKEN.getCode(), ResponseCode.STATUS_EMPTY_TOKEN.getMessage());
-        }
-    }
-
-    public static boolean isTheSelfUser(String strAuthToken, String strUserId){
-        if (StringUtils.isEmpty(strUserId))
-            return false;
-
-        String strFlagKey = null;
-        try {
-            strFlagKey = TokenAuthenticationService.getFlagKeyFromToken(strAuthToken);
-        }catch (Exception e){
-            return false;
-        }
-        return strUserId.equals(strFlagKey);
-    }
-}

+ 218 - 0
custom-gateway-core/src/main/java/com/shkpr/service/customgateway/core/utils/TokenUtil.java

@@ -0,0 +1,218 @@
+package com.shkpr.service.customgateway.core.utils;
+
+import com.shkpr.service.customgateway.core.constants.Api;
+import com.shkpr.service.customgateway.core.constants.CommDefine;
+import com.shkpr.service.customgateway.core.constants.TokenMetadata;
+import com.shkpr.service.customgateway.core.domain.CommonAuthToken;
+import com.shkpr.service.customgateway.core.domain.TokenData;
+import com.shkpr.service.customgateway.core.properties.GlobalProperties;
+import com.shkpr.service.customgateway.core.properties.SecurityProperties;
+import io.jsonwebtoken.*;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.security.authentication.BadCredentialsException;
+import org.springframework.security.authentication.CredentialsExpiredException;
+import org.springframework.security.core.Authentication;
+import org.springframework.stereotype.Component;
+
+import javax.servlet.http.HttpServletRequest;
+import java.nio.charset.StandardCharsets;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * token工具类
+ *
+ * @author 欧阳劲驰
+ * @since 1.0.0
+ */
+@Component
+public class TokenUtil {
+    final
+    SecurityProperties securityProperties;
+    final
+    GlobalProperties globalProperties;
+
+    public TokenUtil(SecurityProperties securityProperties, GlobalProperties globalProperties) {
+        this.securityProperties = securityProperties;
+        this.globalProperties = globalProperties;
+    }
+
+    /**
+     * 生成token
+     *
+     * @param claims 参数
+     * @return token
+     */
+    private TokenData generateToken(Map<String, Object> claims) {
+        return generateToken(claims, securityProperties.getExpiration());
+    }
+
+    /**
+     * 生成token
+     *
+     * @param claims     参数
+     * @param expiration 过期时间
+     * @return token
+     */
+    public TokenData generateToken(Map<String, Object> claims, Duration expiration) {
+        //获取用户属性
+        String flagKey = Optional.ofNullable(claims.get(TokenMetadata.Claims.FLAG_KEY))
+                .filter(String.class::isInstance)
+                .map(String.class::cast)
+                .orElse("");
+        String account = Optional.ofNullable(claims.get(TokenMetadata.Claims.ACCOUNT))
+                .filter(String.class::isInstance)
+                .map(String.class::cast)
+                .orElse("");
+        String roleId = Optional.ofNullable(claims.get(TokenMetadata.Claims.ROLE_ID))
+                .filter(String.class::isInstance)
+                .map(String.class::cast)
+                .orElse("");
+        //生成token
+        return generateToken(flagKey, account, roleId, expiration);
+    }
+
+    /**
+     * 生成token
+     *
+     * @param flagKey    用户id
+     * @param account    用户账号
+     * @param roleId     角色id
+     * @param expiration 过期时间
+     * @return token
+     */
+    public TokenData generateToken(String flagKey, String account, String roleId, Duration expiration) {
+        //当前时间
+        Date nowDate = new Date();
+        //过期时间
+        Date expirationDate = new Date(nowDate.getTime() + expiration.toMillis());
+        //token字符串
+        String strToken = Jwts.builder()
+                .setHeaderParam("typ", "JWT")
+                .setHeaderParam("alg", "HS256")
+                .setIssuedAt(nowDate)
+                .setExpiration(expirationDate)
+                .signWith(SignatureAlgorithm.HS256, securityProperties.getSecret().getBytes(StandardCharsets.UTF_8))
+                .claim(TokenMetadata.Claims.FLAG_KEY, flagKey)
+                .claim(TokenMetadata.Claims.ACCOUNT, account)
+                .claim(TokenMetadata.Claims.ROLE_ID, roleId)
+                .compact();
+        if (StringUtils.isEmpty(strToken)) return null;
+        //构建dto
+        return new TokenData(flagKey, roleId, strToken, expirationDate.getTime(), nowDate.getTime());
+    }
+
+    /**
+     * 解析token
+     *
+     * @param token token字符串
+     * @return 反映指定紧凑声明JWS字符串的{@link Jws Jws}实例
+     * @throws UnsupportedJwtException  如果{@code claimsJws}参数不表示声明JWS
+     * @throws MalformedJwtException    如果{@code claimsJws}字符串不是有效的JWS
+     * @throws SignatureException       如果{@code claimsJws} JWS签名验证失败
+     * @throws ExpiredJwtException      如果指定的JWT是声明JWT且声明在此方法调用时间之前已过期
+     * @throws IllegalArgumentException 如果{@code claimsJws}字符串为{@code null}、空或仅包含空白字符
+     */
+    public Jws<Claims> parseToken(String token) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
+        return Jwts.parser()
+                .setSigningKey(securityProperties.getSecret().getBytes(StandardCharsets.UTF_8))
+                .parseClaimsJws(token);
+    }
+
+    /**
+     * 解析token
+     *
+     * @param token token字符串
+     * @return 反映指定紧凑声明JWS字符串的{@link Jws Jws}实例
+     * @throws UnsupportedJwtException  如果{@code claimsJws}参数不表示声明JWS
+     * @throws MalformedJwtException    如果{@code claimsJws}字符串不是有效的JWS
+     * @throws SignatureException       如果{@code claimsJws} JWS签名验证失败
+     * @throws ExpiredJwtException      如果指定的JWT是声明JWT且声明在此方法调用时间之前已过期
+     * @throws IllegalArgumentException 如果{@code claimsJws}字符串为{@code null}、空或仅包含空白字符
+     */
+    public TokenData parseTokenData(String token) throws ExpiredJwtException, UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
+        //解析token
+        Jws<Claims> jws = parseToken(token);
+        //获取参数
+        Claims claims = jws.getBody();
+        if (claims == null) return null;
+        String flagKey = (String) claims.get(TokenMetadata.Claims.FLAG_KEY);
+        String roleId = (String) claims.get(TokenMetadata.Claims.ROLE_ID);
+        //构建dto
+        return new TokenData(flagKey, roleId, token, claims.getIssuedAt().getTime(), claims.getExpiration().getTime());
+    }
+
+
+    /**
+     * 是否过期
+     *
+     * @param token token字符串
+     * @return 过期状态
+     * @throws UnsupportedJwtException  如果{@code claimsJws}参数不表示声明JWS
+     * @throws MalformedJwtException    如果{@code claimsJws}字符串不是有效的JWS
+     * @throws SignatureException       如果{@code claimsJws} JWS签名验证失败
+     * @throws IllegalArgumentException 如果{@code claimsJws}字符串为{@code null}、空或仅包含空白字符
+     */
+    public Boolean isExpired(String token) throws UnsupportedJwtException, MalformedJwtException, SignatureException, IllegalArgumentException {
+        try {
+            //获取参数
+            Claims claims = parseToken(token).getBody();
+            if (claims == null) return null;
+            //判断超时
+            Date expiration = claims.getExpiration();
+            return expiration.before(new Date());
+        } catch (ExpiredJwtException e) {
+            return true;
+        }
+    }
+
+    /**
+     * 获取认证token
+     *
+     * @param request 请求
+     * @return 认证token
+     * @throws IllegalArgumentException    无效凭证
+     * @throws CredentialsExpiredException 凭证过期
+     * @throws BadCredentialsException     错误凭证
+     */
+    public Authentication getAuthentication(HttpServletRequest request) throws IllegalArgumentException, CredentialsExpiredException, BadCredentialsException {
+        //获取验证口令
+        final String authVerify = request.getHeader(Api.Headers.AUTH_VERIFY);
+        //验证口令通过
+        if (StringUtils.equalsIgnoreCase(globalProperties.getInternalCallPassword(), authVerify)) {
+            //设置用户和角色信息,并返回token
+            request.setAttribute(TokenMetadata.RequestAttributes.USER_ID, CommDefine.INTERNAL_OPERATOR_USER_ID);
+            request.setAttribute(TokenMetadata.RequestAttributes.ROLE_ID, CommDefine.INTERNAL_OPERATOR_ROLE_ID);
+            return CommonAuthToken.authenticated(
+                    new TokenData(CommDefine.INTERNAL_OPERATOR_USER_ID, CommDefine.INTERNAL_OPERATOR_ROLE_ID),
+                    Collections.emptyList());
+        }
+
+        //获取token
+        String token = request.getHeader(Api.Headers.AUTHORIZATION);
+        if (!StringUtils.isNoneBlank(token)) throw new IllegalArgumentException();
+
+        //解析token
+        TokenData tokenData;
+        try {
+            tokenData = parseTokenData(token);
+        } catch (ExpiredJwtException e) {
+            throw new CredentialsExpiredException("Invalidate token, token is expired.");
+        } catch (Exception e) {
+            throw new BadCredentialsException("Invalidate Token, has no user.");
+        }
+
+        //检查token解析结果
+        if (tokenData == null) throw new BadCredentialsException("Invalidate Token, has no user.");
+        if (tokenData.getExpiration() <= System.currentTimeMillis())
+            throw new CredentialsExpiredException("Invalidate token, token is expired.");
+
+        //设置用户和角色信息,并返回token
+        request.setAttribute(TokenMetadata.RequestAttributes.USER_ID, tokenData.getFlagKey());
+        request.setAttribute(TokenMetadata.RequestAttributes.ROLE_ID, tokenData.getRoleId());
+        return CommonAuthToken.authenticated(tokenData, Collections.emptyList());
+    }
+}

+ 16 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/config/ThirdDockConfig.java

@@ -0,0 +1,16 @@
+package com.shkpr.service.customgateway.zydma.config;
+
+import com.shkpr.service.customgateway.zydma.properties.ThirdDockProperties;
+import org.springframework.boot.context.properties.EnableConfigurationProperties;
+import org.springframework.context.annotation.Configuration;
+
+/**
+ * 第三方对接配置
+ *
+ * @author 欧元劲驰
+ * @since 1.0.0
+ */
+@Configuration
+@EnableConfigurationProperties(ThirdDockProperties.class)
+public class ThirdDockConfig {
+}

+ 47 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/constants/SyncBehavior.java

@@ -0,0 +1,47 @@
+package com.shkpr.service.customgateway.zydma.constants;
+
+import lombok.Getter;
+
+/**
+ * 同步行为
+ *
+ * @author 欧元劲驰
+ * @since 1.0.0
+ */
+@Getter
+public enum SyncBehavior {
+    /**
+     * 始终同步
+     */
+    ALWAYS,
+    /**
+     * 仅插入
+     */
+    INSERT_ONLY,
+    /**
+     * 仅插入
+     */
+    UPDATE_ONLY,
+    /**
+     * 永不同步
+     */
+    NEVER;
+
+    /**
+     * 检查是否应处理插入操作
+     *
+     * @return 是否应处理插入操作
+     */
+    public boolean shouldHandleInsert() {
+        return this == ALWAYS || this == INSERT_ONLY;
+    }
+
+    /**
+     * 检查是否应处理更新操作
+     *
+     * @return 是否应处理更新操作
+     */
+    public boolean shouldHandleUpdate() {
+        return this == ALWAYS || this == UPDATE_ONLY;
+    }
+}

+ 34 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/domain/FieldMapping.java

@@ -0,0 +1,34 @@
+package com.shkpr.service.customgateway.zydma.domain;
+
+import com.shkpr.service.customgateway.zydma.constants.SyncBehavior;
+import lombok.Data;
+
+/**
+ * 字段映射
+ *
+ * @author 欧元劲驰
+ * @since 1.0.0
+ */
+@Data
+public class FieldMapping {
+    /**
+     * 本地系统字段名
+     */
+    private String localField;
+    /**
+     * 第三方系统字段名
+     */
+    private String remoteField;
+    /**
+     * 字段描述
+     */
+    private String description;
+    /**
+     * 同步行为
+     */
+    private SyncBehavior syncBehavior = SyncBehavior.ALWAYS;
+    /**
+     * 默认值
+     */
+    private Object defaultValue;
+}

+ 47 - 0
custom-gateway-zydma/src/main/java/com/shkpr/service/customgateway/zydma/properties/ThirdDockProperties.java

@@ -0,0 +1,47 @@
+package com.shkpr.service.customgateway.zydma.properties;
+
+import com.shkpr.service.customgateway.zydma.domain.FieldMapping;
+import lombok.Data;
+import lombok.Getter;
+import lombok.Setter;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 第三方对接属性
+ *
+ * @author 欧元劲驰
+ * @since 1.0.0
+ */
+@Getter
+@Setter
+@ConfigurationProperties("third-dock")
+public class ThirdDockProperties {
+    /**
+     * 认证信息
+     */
+    private Auth auth;
+    /**
+     * 字段映射
+     * <p>key: 表名</p>
+     * <p>value: 映射关系</p>
+     */
+    private Map<String, List<FieldMapping>> fieldMappings;
+
+    /**
+     * 第三方认证
+     */
+    @Data
+    public static class Auth {
+        /**
+         * key
+         */
+        private String appKey;
+        /**
+         * Secret
+         */
+        private String appSecret;
+    }
+}