From 1c9fcbf47568e94640f42371aa116512bf94114a Mon Sep 17 00:00:00 2001 From: zlt Date: Wed, 16 Oct 2019 18:00:56 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=85=A8=E5=8A=9F=E8=83=BDsp?= =?UTF-8?q?ring-cloud-gateway=EF=BC=8C=E4=BC=98=E5=8C=96=E9=83=A8=E5=88=86?= =?UTF-8?q?=E5=85=AC=E5=85=B1=E6=A8=A1=E5=9D=97=E9=80=82=E9=85=8DwebFlux?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 2 + pom.xml | 16 +- zlt-business/file-center/pom.xml | 4 + .../search-center/search-server/pom.xml | 8 + zlt-business/user-center/pom.xml | 9 + zlt-commons/pom.xml | 1 + .../pom.xml | 5 +- .../config/DefaultResourceServerConf.java | 15 +- .../config/SecurityPropertiesConfig.java | 15 + .../common/service/IPermissionService.java | 21 -- .../impl/DefaultPermissionServiceImpl.java | 15 +- .../central/oauth2/common/util/AuthUtils.java | 2 +- .../main/resources/META-INF/spring.factories | 2 + zlt-commons/zlt-common-core/pom.xml | 91 +++++ .../common/annotation/LoginClient.java | 0 .../central/common/annotation/LoginUser.java | 42 +-- .../common/config/BannerInitializer.java | 0 .../common/config/DefaultAsycTaskConfig.java | 116 +++--- .../common/config/DefaultPasswordConfig.java | 40 +-- .../common/config/DefaultWebMvcConfig.java | 0 .../common/config/LoginArgResolverConfig.java | 70 ++-- .../common/constant/CommonConstant.java | 256 ++++++------- .../common/constant/ConfigConstants.java | 0 .../common/constant/SecurityConstants.java | 338 +++++++++--------- .../common/constant/ServiceNameConstants.java | 38 +- .../context/LbIsolationContextHolder.java | 0 .../common/context/TenantContextHolder.java | 0 .../common/exception/BusinessException.java | 28 +- .../exception/DefaultExceptionAdvice.java | 206 +++++------ .../exception/IdempotencyException.java | 28 +- .../common/exception/LockException.java | 28 +- .../com/central/common/feign/UserService.java | 102 +++--- .../fallback/UserServiceFallbackFactory.java | 94 ++--- .../common/lock/AbstractDistributedLock.java | 70 ++-- .../central/common/lock/DistributedLock.java | 186 +++++----- .../com/central/common/model/CodeEnum.java | 36 +- .../central/common/model/LoginAppUser.java | 130 +++---- .../com/central/common/model/PageResult.java | 68 ++-- .../java/com/central/common/model/Result.java | 98 ++--- .../com/central/common/model/SuperEntity.java | 70 ++-- .../com/central/common/model/SysMenu.java | 78 ++-- .../com/central/common/model/SysRole.java | 38 +- .../com/central/common/model/SysUser.java | 82 ++--- .../com/central/common/model/UserType.java | 36 +- .../common/properties/TenantProperties.java | 0 .../resolver/ClientArgumentResolver.java | 0 .../resolver/TokenArgumentResolver.java | 170 ++++----- .../central/common/service/ISuperService.java | 118 +++--- .../common/service/impl/SuperServiceImpl.java | 282 +++++++-------- .../com/central/common/utils/AddrUtil.java | 0 .../central/common/utils/CustomBanner.java | 0 .../utils/CustomThreadPoolTaskExecutor.java | 0 .../com/central/common/utils/ExcelUtil.java | 240 ++++++------- .../com/central/common/utils/IdGenerator.java | 0 .../central/common/utils/ResponseUtil.java | 154 ++++---- .../com/central/common/utils/RsaUtils.java | 0 .../com/central/common/utils/Sequence.java | 0 .../com/central/common/utils/SpringUtil.java | 68 ++-- .../main/resources/META-INF/spring.factories | 2 + .../src/main/resources/zltmp/logo.txt | 0 .../zlt-common-spring-boot-starter/pom.xml | 74 +--- .../central/common/filter/TenantFilter.java | 3 + .../central/common/filter/TraceFilter.java | 3 + .../main/resources/META-INF/spring.factories | 3 - .../zlt-db-spring-boot-starter/pom.xml | 2 +- .../zlt-redis-spring-boot-starter/pom.xml | 2 +- .../zlt-ribbon-spring-boot-starter/pom.xml | 3 +- .../ribbon/LbIsolationAutoConfigure.java | 18 + .../common/ribbon/RibbonAutoConfigure.java | 11 - .../ribbon/config/FeignInterceptorConfig.java | 2 +- .../ribbon/filter/LbIsolationFilter.java | 5 + .../ribbon/rule/CustomIsolationRule.java | 9 +- .../main/resources/META-INF/spring.factories | 3 +- .../zlt-sentinel-spring-boot-starter/pom.xml | 2 +- .../zlt-swagger2-spring-boot-starter/pom.xml | 2 +- .../main/resources/application-dev.properties | 2 +- zlt-gateway/pom.xml | 3 + zlt-gateway/sc-gateway/pom.xml | 134 +++++++ .../main/java/com/central/SCGatewayApp.java | 22 ++ .../auth/CustomAuthenticationManager.java | 49 +++ .../gateway/auth/JsonAccessDeniedHandler.java | 26 ++ .../auth/JsonAuthenticationEntryPoint.java | 26 ++ .../auth/Oauth2AuthSuccessHandler.java | 45 +++ .../gateway/auth/PermissionAuthManager.java | 48 +++ .../central/gateway/config/CorsConfig.java | 39 ++ .../gateway/config/DynamicRouteConfig.java | 40 +++ .../config/ResourceServerConfiguration.java | 77 ++++ .../central/gateway/feign/MenuService.java | 23 ++ .../fallback/MenuServiceFallbackFactory.java | 25 ++ .../gateway/filter/LbIsolationFilter.java | 47 +++ .../filter/RequestStatisticsFilter.java | 45 +++ .../central/gateway/filter/TraceFilter.java | 52 +++ .../route/NacosRouteDefinitionRepository.java | 94 +++++ .../gateway/swagger/SwaggerAggProperties.java | 62 ++++ .../gateway/swagger/SwaggerHandler.java | 57 +++ .../gateway/swagger/SwaggerProvider.java | 73 ++++ .../gateway/utils/ReactiveAddrUtil.java | 76 ++++ .../src/main/resources/application.yml | 133 +++++++ .../src/main/resources/bootstrap.yml | 19 + .../sc-gateway/src/main/resources/pubkey.txt | 9 + zlt-gateway/zuul-gateway/pom.xml | 4 + .../config/ResourceServerConfiguration.java | 25 -- .../gateway/filter/pre/LbIsolationFilter.java | 52 --- .../service/impl/PermissionServiceImpl.java | 6 + .../src/main/resources/application.yml | 5 +- zlt-monitor/log-center/pom.xml | 5 +- zlt-uaa/pom.xml | 8 + .../oauth/config/CorsConfigration.java | 47 --- .../central/oauth/config/SecurityConfig.java | 6 - zlt-uaa/src/main/resources/bootstrap.yml | 4 + .../src/main/resources/static/module/admin.js | 2 +- .../static/pages/attestation/app.html | 2 +- .../resources/static/pages/files/files.html | 2 +- .../static/pages/generator/list.html | 2 +- .../static/pages/log/slowQueryLog.html | 2 +- .../resources/static/pages/log/sysLog.html | 2 +- .../static/pages/search/index_manager.html | 2 +- .../static/pages/search/user_search.html | 2 +- .../resources/static/pages/system/myInfo.html | 2 +- .../resources/static/pages/system/role.html | 2 +- .../resources/static/pages/system/tokens.html | 2 +- .../resources/static/pages/system/user.html | 10 +- 122 files changed, 3144 insertions(+), 1936 deletions(-) create mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/SecurityPropertiesConfig.java delete mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/IPermissionService.java create mode 100644 zlt-commons/zlt-auth-client-spring-boot-starter/src/main/resources/META-INF/spring.factories create mode 100644 zlt-commons/zlt-common-core/pom.xml rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/annotation/LoginClient.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/annotation/LoginUser.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/config/BannerInitializer.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/config/DefaultAsycTaskConfig.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/config/DefaultPasswordConfig.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/config/DefaultWebMvcConfig.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/config/LoginArgResolverConfig.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/constant/CommonConstant.java (94%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/constant/ConfigConstants.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/constant/SecurityConstants.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/constant/ServiceNameConstants.java (94%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/context/LbIsolationContextHolder.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/context/TenantContextHolder.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/exception/BusinessException.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/exception/DefaultExceptionAdvice.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/exception/IdempotencyException.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/exception/LockException.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/feign/UserService.java (97%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/lock/AbstractDistributedLock.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/lock/DistributedLock.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/CodeEnum.java (93%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/LoginAppUser.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/PageResult.java (94%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/Result.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/SuperEntity.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/SysMenu.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/SysRole.java (95%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/SysUser.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/model/UserType.java (90%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/properties/TenantProperties.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/resolver/ClientArgumentResolver.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/resolver/TokenArgumentResolver.java (97%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/service/ISuperService.java (96%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/service/impl/SuperServiceImpl.java (97%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/AddrUtil.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/CustomBanner.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/ExcelUtil.java (97%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/IdGenerator.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/ResponseUtil.java (62%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/RsaUtils.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/Sequence.java (100%) rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/java/com/central/common/utils/SpringUtil.java (96%) create mode 100644 zlt-commons/zlt-common-core/src/main/resources/META-INF/spring.factories rename zlt-commons/{zlt-common-spring-boot-starter => zlt-common-core}/src/main/resources/zltmp/logo.txt (100%) create mode 100644 zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/LbIsolationAutoConfigure.java create mode 100644 zlt-gateway/sc-gateway/pom.xml create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/SCGatewayApp.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomAuthenticationManager.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAccessDeniedHandler.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAuthenticationEntryPoint.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/DynamicRouteConfig.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/MenuService.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/fallback/MenuServiceFallbackFactory.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/LbIsolationFilter.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerAggProperties.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerHandler.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerProvider.java create mode 100644 zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java create mode 100644 zlt-gateway/sc-gateway/src/main/resources/application.yml create mode 100644 zlt-gateway/sc-gateway/src/main/resources/bootstrap.yml create mode 100644 zlt-gateway/sc-gateway/src/main/resources/pubkey.txt delete mode 100644 zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/filter/pre/LbIsolationFilter.java delete mode 100644 zlt-uaa/src/main/java/com/central/oauth/config/CorsConfigration.java diff --git a/README.md b/README.md index 41e45496..0f92de17 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,7 @@ central-platform -- 父项目,公共依赖 │ │ │ ├─search-server -- 搜索中心服务端[7100] │ │─zlt-commons -- 通用工具一级工程 │ │ ├─zlt-auth-client-spring-boot-starter -- 封装spring security client端的通用操作逻辑 +│ │ ├─zlt-common-core -- 封装通用操作逻辑 │ │ ├─zlt-common-spring-boot-starter -- 封装通用操作逻辑 │ │ ├─zlt-db-spring-boot-starter -- 封装数据库通用操作逻辑 │ │ ├─zlt-log-spring-boot-starter -- 封装log通用操作逻辑 @@ -119,6 +120,7 @@ central-platform -- 父项目,公共依赖 │ ├─zlt-config -- 配置中心 │ ├─zlt-doc -- 项目文档 │ ├─zlt-gateway -- api网关一级工程 +│ │ ├─sc-gateway -- spring-cloud-gateway[9900] │ │ ├─zuul-gateway -- netflix-zuul[9900] │ ├─zlt-job -- 分布式任务调度一级工程 │ │ ├─job-admin -- 任务管理器[8081] diff --git a/pom.xml b/pom.xml index 3e3d22a4..4241ae9b 100644 --- a/pom.xml +++ b/pom.xml @@ -46,7 +46,6 @@ 1.1.6.RELEASE 2.6 4.0.1 - 2.1.0.RELEASE 2.1.8.RELEASE Greenwich.SR3 @@ -140,7 +139,11 @@ zlt-config ${project.version} - + + com.zlt + zlt-common-core + ${project.version} + io.jsonwebtoken jjwt @@ -343,13 +346,6 @@ pom import - org.springframework.cloud spring-cloud-dependencies @@ -441,6 +437,8 @@ LeTao Zhu zltdiablo@163.com + https://github.com/zlt2000 + https://blog.csdn.net/zlt2000 \ No newline at end of file diff --git a/zlt-business/file-center/pom.xml b/zlt-business/file-center/pom.xml index 8090896a..96b279c8 100644 --- a/zlt-business/file-center/pom.xml +++ b/zlt-business/file-center/pom.xml @@ -35,6 +35,10 @@ com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery + + org.springframework.boot + spring-boot-starter-web + org.springframework diff --git a/zlt-business/search-center/search-server/pom.xml b/zlt-business/search-center/search-server/pom.xml index 2d211ce2..b295cbb9 100644 --- a/zlt-business/search-center/search-server/pom.xml +++ b/zlt-business/search-center/search-server/pom.xml @@ -14,10 +14,18 @@ com.zlt zlt-config + + com.zlt + zlt-common-spring-boot-starter + com.zlt search-client + + org.springframework.boot + spring-boot-starter-web + com.alibaba.cloud diff --git a/zlt-business/user-center/pom.xml b/zlt-business/user-center/pom.xml index 02b28324..cd7d5692 100644 --- a/zlt-business/user-center/pom.xml +++ b/zlt-business/user-center/pom.xml @@ -44,6 +44,10 @@ search-client + + org.springframework.boot + spring-boot-starter-web + com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery @@ -67,6 +71,11 @@ io.micrometer micrometer-registry-prometheus + + + org.springframework.social + spring-social-security + diff --git a/zlt-commons/pom.xml b/zlt-commons/pom.xml index 8fa235e6..8b9cad41 100644 --- a/zlt-commons/pom.xml +++ b/zlt-commons/pom.xml @@ -19,5 +19,6 @@ zlt-ribbon-spring-boot-starter zlt-auth-client-spring-boot-starter zlt-sentinel-spring-boot-starter + zlt-common-core \ No newline at end of file diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml b/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml index f69e1034..179b0e36 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/pom.xml @@ -12,10 +12,6 @@ zlt-auth-client-spring-boot-starter 认证客户端通用组件 - - com.zlt - zlt-common-spring-boot-starter - org.springframework.cloud spring-cloud-starter-oauth2 @@ -23,6 +19,7 @@ com.zlt zlt-redis-spring-boot-starter + true org.springframework.cloud diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultResourceServerConf.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultResourceServerConf.java index 39cafbb8..e3c4ccf7 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultResourceServerConf.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/DefaultResourceServerConf.java @@ -6,6 +6,7 @@ import org.springframework.context.annotation.Import; import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; +import org.springframework.security.config.http.SessionCreationPolicy; import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; import org.springframework.security.oauth2.provider.error.OAuth2AccessDeniedHandler; @@ -52,12 +53,14 @@ public class DefaultResourceServerConf extends ResourceServerConfigurerAdapter { .antMatchers(HttpMethod.OPTIONS).permitAll() .anyRequest(); setAuthenticate(authorizedUrl); - //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题 - http.headers() - .frameOptions() - .disable() - .and() - .csrf().disable(); + + http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED) + .and() + .httpBasic().disable() + .headers() + .frameOptions().disable() + .and() + .csrf().disable(); } /** diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/SecurityPropertiesConfig.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/SecurityPropertiesConfig.java new file mode 100644 index 00000000..e85ed2a2 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/config/SecurityPropertiesConfig.java @@ -0,0 +1,15 @@ +package com.central.oauth2.common.config; + +import com.central.oauth2.common.properties.SecurityProperties; +import org.springframework.boot.context.properties.EnableConfigurationProperties; + +/** + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@EnableConfigurationProperties(SecurityProperties.class) +public class SecurityPropertiesConfig { +} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/IPermissionService.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/IPermissionService.java deleted file mode 100644 index 01f75c85..00000000 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/IPermissionService.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.central.oauth2.common.service; - -import org.springframework.security.core.Authentication; - -import javax.servlet.http.HttpServletRequest; - -/** - * 请求权限判断service - * - * @author zlt - * @date 2018/10/28 - */ -public interface IPermissionService { - /** - * 判断请求是否有权限 - * - * @param authentication 认证信息 - * @return 是否有权限 - */ - boolean hasPermission(HttpServletRequest request, Authentication authentication); -} diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java index 07f5bdfe..954cf054 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/service/impl/DefaultPermissionServiceImpl.java @@ -6,7 +6,6 @@ import com.central.common.constant.CommonConstant; import com.central.common.context.TenantContextHolder; import com.central.common.model.SysMenu; import com.central.oauth2.common.properties.SecurityProperties; -import com.central.oauth2.common.service.IPermissionService; import com.central.oauth2.common.util.AuthUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; @@ -18,7 +17,6 @@ import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.oauth2.provider.OAuth2Authentication; import org.springframework.util.AntPathMatcher; -import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.stream.Collectors; @@ -29,7 +27,7 @@ import java.util.stream.Collectors; * @date 2018/10/28 */ @Slf4j -public abstract class DefaultPermissionServiceImpl implements IPermissionService { +public abstract class DefaultPermissionServiceImpl { @Autowired private SecurityProperties securityProperties; @@ -43,10 +41,9 @@ public abstract class DefaultPermissionServiceImpl implements IPermissionService */ public abstract List findMenuByRoleCodes(String roleCodes); - @Override - public boolean hasPermission(HttpServletRequest request, Authentication authentication) { + public boolean hasPermission(Authentication authentication, String requestMethod, String requestURI) { // 前端跨域OPTIONS请求预检放行 也可通过前端配置代理实现 - if (HttpMethod.OPTIONS.name().equalsIgnoreCase(request.getMethod())) { + if (HttpMethod.OPTIONS.name().equalsIgnoreCase(requestMethod)) { return true; } if (!(authentication instanceof AnonymousAuthenticationToken)) { @@ -68,7 +65,7 @@ public abstract class DefaultPermissionServiceImpl implements IPermissionService //判断不进行url权限认证的api,所有已登录用户都能访问的url for (String path : securityProperties.getAuth().getUrlPermission().getIgnoreUrls()) { - if (antPathMatcher.match(path, request.getRequestURI())) { + if (antPathMatcher.match(path, requestURI)) { return true; } } @@ -86,9 +83,9 @@ public abstract class DefaultPermissionServiceImpl implements IPermissionService String roleCodes = grantedAuthorityList.stream().map(SimpleGrantedAuthority::getAuthority).collect(Collectors.joining(", ")); List menuList = findMenuByRoleCodes(roleCodes); for (SysMenu menu : menuList) { - if (StringUtils.isNotEmpty(menu.getUrl()) && antPathMatcher.match(menu.getUrl(), request.getRequestURI())) { + if (StringUtils.isNotEmpty(menu.getUrl()) && antPathMatcher.match(menu.getUrl(), requestURI)) { if (StrUtil.isNotEmpty(menu.getPathMethod())) { - return request.getMethod().equalsIgnoreCase(menu.getPathMethod()); + return requestMethod.equalsIgnoreCase(menu.getPathMethod()); } else { return true; } diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java index aa5a36dc..948e3602 100644 --- a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/java/com/central/oauth2/common/util/AuthUtils.java @@ -52,7 +52,7 @@ public class AuthUtils { Enumeration headers = request.getHeaders(CommonConstant.TOKEN_HEADER); while (headers.hasMoreElements()) { String value = headers.nextElement(); - if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE.toLowerCase()))) { + if ((value.toLowerCase().startsWith(OAuth2AccessToken.BEARER_TYPE))) { String authHeaderValue = value.substring(OAuth2AccessToken.BEARER_TYPE.length()).trim(); int commaIndex = authHeaderValue.indexOf(','); if (commaIndex > 0) { diff --git a/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..479efca8 --- /dev/null +++ b/zlt-commons/zlt-auth-client-spring-boot-starter/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.central.oauth2.common.config.SecurityPropertiesConfig \ No newline at end of file diff --git a/zlt-commons/zlt-common-core/pom.xml b/zlt-commons/zlt-common-core/pom.xml new file mode 100644 index 00000000..80a5e6e2 --- /dev/null +++ b/zlt-commons/zlt-common-core/pom.xml @@ -0,0 +1,91 @@ + + 4.0.0 + + com.zlt + zlt-commons + 2.7.2 + + zlt-common-core + 公共通用组件 + jar + + + com.zlt + zlt-log-spring-boot-starter + + + com.baomidou + mybatis-plus + true + + + org.springframework.social + spring-social-security + + + org.springframework.security.oauth + spring-security-oauth2 + true + + + + cn.hutool + hutool-all + + + javax.servlet + javax.servlet-api + true + + + com.fasterxml.jackson.core + jackson-annotations + + + com.fasterxml.jackson.core + jackson-databind + + + org.springframework.cloud + spring-cloud-starter-openfeign + true + + + org.apache.poi + poi + + + org.apache.poi + poi-ooxml + + + + cn.afterturn + easypoi-base + + + com.google.guava + guava + + + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + com.nepxion + banner + + + + io.projectreactor + reactor-core + true + + + \ No newline at end of file diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/annotation/LoginClient.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/annotation/LoginClient.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/annotation/LoginClient.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/annotation/LoginClient.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/annotation/LoginUser.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/annotation/LoginUser.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/annotation/LoginUser.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/annotation/LoginUser.java index c5ce71b0..c18332e9 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/annotation/LoginUser.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/annotation/LoginUser.java @@ -1,21 +1,21 @@ -package com.central.common.annotation; - -import java.lang.annotation.*; - -/** - * 请求的方法参数SysUser上添加该注解,则注入当前登录人信息 - * 例1:public void test(@LoginUser SysUser user) //只有username 和 roles - * 例2:public void test(@LoginUser(isFull = true) SysUser user) //能获取SysUser对象的所有信息 - * - * @author zlt - * @date 2018/7/24 16:44 - */ -@Target(ElementType.PARAMETER) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface LoginUser { - /** - * 是否查询SysUser对象所有信息,true则通过rpc接口查询 - */ - boolean isFull() default false; -} +package com.central.common.annotation; + +import java.lang.annotation.*; + +/** + * 请求的方法参数SysUser上添加该注解,则注入当前登录人信息 + * 例1:public void test(@LoginUser SysUser user) //只有username 和 roles + * 例2:public void test(@LoginUser(isFull = true) SysUser user) //能获取SysUser对象的所有信息 + * + * @author zlt + * @date 2018/7/24 16:44 + */ +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface LoginUser { + /** + * 是否查询SysUser对象所有信息,true则通过rpc接口查询 + */ + boolean isFull() default false; +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/BannerInitializer.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/BannerInitializer.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/BannerInitializer.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/config/BannerInitializer.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/DefaultAsycTaskConfig.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultAsycTaskConfig.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/DefaultAsycTaskConfig.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultAsycTaskConfig.java index c8378ecd..5ee315e0 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/DefaultAsycTaskConfig.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultAsycTaskConfig.java @@ -1,58 +1,58 @@ -package com.central.common.config; - -import com.central.common.utils.CustomThreadPoolTaskExecutor; -import lombok.Getter; -import lombok.Setter; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.context.annotation.Bean; -import org.springframework.core.task.TaskExecutor; -import org.springframework.scheduling.annotation.EnableAsync; -import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; - -import java.util.concurrent.ThreadPoolExecutor; - -/** - * @author zlt - * @date 2018/12/13 - */ -@Setter -@Getter -@EnableAsync(proxyTargetClass = true) -public class DefaultAsycTaskConfig { - /** - * 线程池维护线程的最小数量. - */ - @Value("${asyc-task.corePoolSize:10}") - private int corePoolSize; - /** - * 线程池维护线程的最大数量 - */ - @Value("${asyc-task.maxPoolSize:200}") - private int maxPoolSize; - /** - * 队列最大长度 - */ - @Value("${asyc-task.queueCapacity:10}") - private int queueCapacity; - /** - * 线程池前缀 - */ - @Value("${asyc-task.threadNamePrefix:ZltExecutor-}") - private String threadNamePrefix; - - @Bean - public TaskExecutor taskExecutor() { - ThreadPoolTaskExecutor executor = new CustomThreadPoolTaskExecutor(); - executor.setCorePoolSize(corePoolSize); - executor.setMaxPoolSize(maxPoolSize); - executor.setQueueCapacity(queueCapacity); - executor.setThreadNamePrefix(threadNamePrefix); - /* - rejection-policy:当pool已经达到max size的时候,如何处理新任务 - CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行 - */ - executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); - executor.initialize(); - return executor; - } -} +package com.central.common.config; + +import com.central.common.utils.CustomThreadPoolTaskExecutor; +import lombok.Getter; +import lombok.Setter; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.core.task.TaskExecutor; +import org.springframework.scheduling.annotation.EnableAsync; +import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; + +import java.util.concurrent.ThreadPoolExecutor; + +/** + * @author zlt + * @date 2018/12/13 + */ +@Setter +@Getter +@EnableAsync(proxyTargetClass = true) +public class DefaultAsycTaskConfig { + /** + * 线程池维护线程的最小数量. + */ + @Value("${asyc-task.corePoolSize:10}") + private int corePoolSize; + /** + * 线程池维护线程的最大数量 + */ + @Value("${asyc-task.maxPoolSize:200}") + private int maxPoolSize; + /** + * 队列最大长度 + */ + @Value("${asyc-task.queueCapacity:10}") + private int queueCapacity; + /** + * 线程池前缀 + */ + @Value("${asyc-task.threadNamePrefix:ZltExecutor-}") + private String threadNamePrefix; + + @Bean + public TaskExecutor taskExecutor() { + ThreadPoolTaskExecutor executor = new CustomThreadPoolTaskExecutor(); + executor.setCorePoolSize(corePoolSize); + executor.setMaxPoolSize(maxPoolSize); + executor.setQueueCapacity(queueCapacity); + executor.setThreadNamePrefix(threadNamePrefix); + /* + rejection-policy:当pool已经达到max size的时候,如何处理新任务 + CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行 + */ + executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); + executor.initialize(); + return executor; + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/DefaultPasswordConfig.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultPasswordConfig.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/DefaultPasswordConfig.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultPasswordConfig.java index 605b60bf..372024cc 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/DefaultPasswordConfig.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultPasswordConfig.java @@ -1,20 +1,20 @@ -package com.central.common.config; - -import org.springframework.context.annotation.Bean; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.crypto.password.PasswordEncoder; - -/** -* @author zlt -* 密码工具类 -*/ -public class DefaultPasswordConfig { - /** - * 装配BCryptPasswordEncoder用户密码的匹配 - * @return - */ - @Bean - public PasswordEncoder passwordEncoder() { - return new BCryptPasswordEncoder(); - } -} +package com.central.common.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.crypto.password.PasswordEncoder; + +/** +* @author zlt +* 密码工具类 +*/ +public class DefaultPasswordConfig { + /** + * 装配BCryptPasswordEncoder用户密码的匹配 + * @return + */ + @Bean + public PasswordEncoder passwordEncoder() { + return new BCryptPasswordEncoder(); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/DefaultWebMvcConfig.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultWebMvcConfig.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/DefaultWebMvcConfig.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/config/DefaultWebMvcConfig.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/LoginArgResolverConfig.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/LoginArgResolverConfig.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/LoginArgResolverConfig.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/config/LoginArgResolverConfig.java index 5506c433..bbffbf4f 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/config/LoginArgResolverConfig.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/config/LoginArgResolverConfig.java @@ -1,35 +1,35 @@ -package com.central.common.config; - -import com.central.common.feign.UserService; -import com.central.common.resolver.ClientArgumentResolver; -import com.central.common.resolver.TokenArgumentResolver; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; - -import java.util.List; - -/** - * 公共配置类, 一些公共工具配置 - * - * @author zlt - * @date 2018/8/25 - */ -public class LoginArgResolverConfig implements WebMvcConfigurer { - @Lazy - @Autowired - private UserService userService; - /** - * Token参数解析 - * - * @param argumentResolvers 解析类 - */ - @Override - public void addArgumentResolvers(List argumentResolvers) { - //注入用户信息 - argumentResolvers.add(new TokenArgumentResolver(userService)); - //注入应用信息 - argumentResolvers.add(new ClientArgumentResolver()); - } -} +package com.central.common.config; + +import com.central.common.feign.UserService; +import com.central.common.resolver.ClientArgumentResolver; +import com.central.common.resolver.TokenArgumentResolver; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; + +/** + * 公共配置类, 一些公共工具配置 + * + * @author zlt + * @date 2018/8/25 + */ +public class LoginArgResolverConfig implements WebMvcConfigurer { + @Lazy + @Autowired + private UserService userService; + /** + * Token参数解析 + * + * @param argumentResolvers 解析类 + */ + @Override + public void addArgumentResolvers(List argumentResolvers) { + //注入用户信息 + argumentResolvers.add(new TokenArgumentResolver(userService)); + //注入应用信息 + argumentResolvers.add(new ClientArgumentResolver()); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/CommonConstant.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/CommonConstant.java similarity index 94% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/CommonConstant.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/CommonConstant.java index 762135c8..56462665 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/CommonConstant.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/CommonConstant.java @@ -1,128 +1,128 @@ -package com.central.common.constant; - -/** - * 全局公共常量 - * - * @author zlt - * @date 2018/10/29 - */ -public interface CommonConstant { - /** - * 项目版本号(banner使用) - */ - String PROJECT_VERSION = "2.7.2"; - - /** - * token请求头名称 - */ - String TOKEN_HEADER = "Authorization"; - - /** - * The access token issued by the authorization server. This value is REQUIRED. - */ - String ACCESS_TOKEN = "access_token"; - - String BEARER_TYPE = "Bearer"; - - /** - * 标签 header key - */ - String HEADER_LABEL = "x-label"; - - /** - * 标签 header 分隔符 - */ - String HEADER_LABEL_SPLIT = ","; - - /** - * 标签或 名称 - */ - String LABEL_OR = "labelOr"; - - /** - * 标签且 名称 - */ - String LABEL_AND = "labelAnd"; - - /** - * 权重key - */ - String WEIGHT_KEY = "weight"; - - /** - * 删除 - */ - String STATUS_DEL = "1"; - - /** - * 正常 - */ - String STATUS_NORMAL = "0"; - - /** - * 锁定 - */ - String STATUS_LOCK = "9"; - - /** - * 目录 - */ - Integer CATALOG = -1; - - /** - * 菜单 - */ - Integer MENU = 1; - - /** - * 权限 - */ - Integer PERMISSION = 2; - - /** - * 删除标记 - */ - String DEL_FLAG = "is_del"; - - /** - * 超级管理员用户名 - */ - String ADMIN_USER_NAME = "admin"; - - /** - * 公共日期格式 - */ - String MONTH_FORMAT = "yyyy-MM"; - String DATE_FORMAT = "yyyy-MM-dd"; - String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; - String SIMPLE_MONTH_FORMAT = "yyyyMM"; - String SIMPLE_DATE_FORMAT = "yyyyMMdd"; - String SIMPLE_DATETIME_FORMAT = "yyyyMMddHHmmss"; - - String DEF_USER_PASSWORD = "123456"; - - String LOCK_KEY_PREFIX = "LOCK_KEY:"; - - /** - * 租户id参数 - */ - String TENANT_ID_PARAM = "tenantId"; - - - /** - * 日志链路追踪id信息头 - */ - String TRACE_ID_HEADER = "x-traceId-header"; - /** - * 日志链路追踪id日志标志 - */ - String LOG_TRACE_ID = "traceId"; - /** - * 负载均衡策略-版本号 信息头 - */ - String Z_L_T_VERSION = "z-l-t-version"; - /** - * 注册中心元数据 版本号 - */ - String METADATA_VERSION = "version"; -} +package com.central.common.constant; + +/** + * 全局公共常量 + * + * @author zlt + * @date 2018/10/29 + */ +public interface CommonConstant { + /** + * 项目版本号(banner使用) + */ + String PROJECT_VERSION = "2.7.2"; + + /** + * token请求头名称 + */ + String TOKEN_HEADER = "Authorization"; + + /** + * The access token issued by the authorization server. This value is REQUIRED. + */ + String ACCESS_TOKEN = "access_token"; + + String BEARER_TYPE = "Bearer"; + + /** + * 标签 header key + */ + String HEADER_LABEL = "x-label"; + + /** + * 标签 header 分隔符 + */ + String HEADER_LABEL_SPLIT = ","; + + /** + * 标签或 名称 + */ + String LABEL_OR = "labelOr"; + + /** + * 标签且 名称 + */ + String LABEL_AND = "labelAnd"; + + /** + * 权重key + */ + String WEIGHT_KEY = "weight"; + + /** + * 删除 + */ + String STATUS_DEL = "1"; + + /** + * 正常 + */ + String STATUS_NORMAL = "0"; + + /** + * 锁定 + */ + String STATUS_LOCK = "9"; + + /** + * 目录 + */ + Integer CATALOG = -1; + + /** + * 菜单 + */ + Integer MENU = 1; + + /** + * 权限 + */ + Integer PERMISSION = 2; + + /** + * 删除标记 + */ + String DEL_FLAG = "is_del"; + + /** + * 超级管理员用户名 + */ + String ADMIN_USER_NAME = "admin"; + + /** + * 公共日期格式 + */ + String MONTH_FORMAT = "yyyy-MM"; + String DATE_FORMAT = "yyyy-MM-dd"; + String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; + String SIMPLE_MONTH_FORMAT = "yyyyMM"; + String SIMPLE_DATE_FORMAT = "yyyyMMdd"; + String SIMPLE_DATETIME_FORMAT = "yyyyMMddHHmmss"; + + String DEF_USER_PASSWORD = "123456"; + + String LOCK_KEY_PREFIX = "LOCK_KEY:"; + + /** + * 租户id参数 + */ + String TENANT_ID_PARAM = "tenantId"; + + + /** + * 日志链路追踪id信息头 + */ + String TRACE_ID_HEADER = "x-traceId-header"; + /** + * 日志链路追踪id日志标志 + */ + String LOG_TRACE_ID = "traceId"; + /** + * 负载均衡策略-版本号 信息头 + */ + String Z_L_T_VERSION = "z-l-t-version"; + /** + * 注册中心元数据 版本号 + */ + String METADATA_VERSION = "version"; +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/ConfigConstants.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ConfigConstants.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/ConfigConstants.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ConfigConstants.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/SecurityConstants.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/SecurityConstants.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java index 367df06b..788ed929 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/SecurityConstants.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/SecurityConstants.java @@ -1,169 +1,169 @@ -package com.central.common.constant; - -/** - * Security 权限常量 - * - * @author zlt - */ -public interface SecurityConstants { - /** - * 用户信息分隔符 - */ - String USER_SPLIT = ":"; - - /** - * 用户信息头 - */ - String USER_HEADER = "x-user-header"; - - /** - * 用户id信息头 - */ - String USER_ID_HEADER = "x-userid-header"; - - /** - * 角色信息头 - */ - String ROLE_HEADER = "x-role-header"; - - /** - * 租户信息头(应用) - */ - String TENANT_HEADER = "x-tenant-header"; - - /** - * 基础角色 - */ - String BASE_ROLE = "ROLE_USER"; - - /** - * 授权码模式 - */ - String AUTHORIZATION_CODE = "authorization_code"; - - /** - * 密码模式 - */ - String PASSWORD = "password"; - - /** - * 刷新token - */ - String REFRESH_TOKEN = "refresh_token"; - - /** - * oauth token - */ - String OAUTH_TOKEN_URL = "/oauth/token"; - - /** - * 默认的处理验证码的url前缀 - */ - String DEFAULT_VALIDATE_CODE_URL_PREFIX = "/validata/code"; - - /** - * 手机号的处理验证码的url前缀 - */ - String MOBILE_VALIDATE_CODE_URL_PREFIX = "/validata/smsCode"; - - /** - * 默认生成图形验证码宽度 - */ - String DEFAULT_IMAGE_WIDTH = "100"; - - /** - * 默认生成图像验证码高度 - */ - String DEFAULT_IMAGE_HEIGHT = "35"; - - /** - * 默认生成图形验证码长度 - */ - String DEFAULT_IMAGE_LENGTH = "4"; - - /** - * 默认生成图形验证码过期时间 - */ - int DEFAULT_IMAGE_EXPIRE = 60; - - /** - * 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. - */ - String DEFAULT_COLOR_FONT = "blue"; - - /** - * 图片边框 - */ - String DEFAULT_IMAGE_BORDER = "no"; - - /** - * 默认图片间隔 - */ - String DEFAULT_CHAR_SPACE = "5"; - - /** - * 默认保存code的前缀 - */ - String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY"; - - /** - * 验证码文字大小 - */ - String DEFAULT_IMAGE_FONT_SIZE = "30"; - /** - * zlt公共前缀 - */ - String ZLT_PREFIX = "zlt:"; - /** - * 缓存client的redis key,这里是hash结构存储 - */ - String CACHE_CLIENT_KEY = "oauth_client_details"; - /** - * OAUTH模式登录处理地址 - */ - String OAUTH_LOGIN_PRO_URL = "/user/login"; - /** - * PASSWORD模式登录处理地址 - */ - String PASSWORD_LOGIN_PRO_URL = "/oauth/user/token"; - /** - * 获取授权码地址 - */ - String AUTH_CODE_URL = "/oauth/authorize"; - /** - * 登录页面 - */ - String LOGIN_PAGE = "/login.html"; - /** - * 默认的OPENID登录请求处理url - */ - String OPENID_TOKEN_URL = "/oauth/openId/token"; - /** - * 手机登录URL - */ - String MOBILE_TOKEN_URL = "/oauth/mobile/token"; - /** - * 登出URL - */ - String LOGOUT_URL = "/oauth/remove/token"; - /** - * 默认token过期时间(1小时) - */ - Integer ACCESS_TOKEN_VALIDITY_SECONDS = 60 * 60; - /** - * redis中授权token对应的key - */ - String REDIS_TOKEN_AUTH = "auth:"; - /** - * redis中应用对应的token集合的key - */ - String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access:"; - /** - * redis中用户名对应的token集合的key - */ - String REDIS_UNAME_TO_ACCESS = "uname_to_access:"; - /** - * rsa公钥 - */ - String RSA_PUBLIC_KEY = "pubkey.txt"; -} +package com.central.common.constant; + +/** + * Security 权限常量 + * + * @author zlt + */ +public interface SecurityConstants { + /** + * 用户信息分隔符 + */ + String USER_SPLIT = ":"; + + /** + * 用户信息头 + */ + String USER_HEADER = "x-user-header"; + + /** + * 用户id信息头 + */ + String USER_ID_HEADER = "x-userid-header"; + + /** + * 角色信息头 + */ + String ROLE_HEADER = "x-role-header"; + + /** + * 租户信息头(应用) + */ + String TENANT_HEADER = "x-tenant-header"; + + /** + * 基础角色 + */ + String BASE_ROLE = "ROLE_USER"; + + /** + * 授权码模式 + */ + String AUTHORIZATION_CODE = "authorization_code"; + + /** + * 密码模式 + */ + String PASSWORD = "password"; + + /** + * 刷新token + */ + String REFRESH_TOKEN = "refresh_token"; + + /** + * oauth token + */ + String OAUTH_TOKEN_URL = "/oauth/token"; + + /** + * 默认的处理验证码的url前缀 + */ + String DEFAULT_VALIDATE_CODE_URL_PREFIX = "/validata/code"; + + /** + * 手机号的处理验证码的url前缀 + */ + String MOBILE_VALIDATE_CODE_URL_PREFIX = "/validata/smsCode"; + + /** + * 默认生成图形验证码宽度 + */ + String DEFAULT_IMAGE_WIDTH = "100"; + + /** + * 默认生成图像验证码高度 + */ + String DEFAULT_IMAGE_HEIGHT = "35"; + + /** + * 默认生成图形验证码长度 + */ + String DEFAULT_IMAGE_LENGTH = "4"; + + /** + * 默认生成图形验证码过期时间 + */ + int DEFAULT_IMAGE_EXPIRE = 60; + + /** + * 边框颜色,合法值: r,g,b (and optional alpha) 或者 white,black,blue. + */ + String DEFAULT_COLOR_FONT = "blue"; + + /** + * 图片边框 + */ + String DEFAULT_IMAGE_BORDER = "no"; + + /** + * 默认图片间隔 + */ + String DEFAULT_CHAR_SPACE = "5"; + + /** + * 默认保存code的前缀 + */ + String DEFAULT_CODE_KEY = "DEFAULT_CODE_KEY"; + + /** + * 验证码文字大小 + */ + String DEFAULT_IMAGE_FONT_SIZE = "30"; + /** + * zlt公共前缀 + */ + String ZLT_PREFIX = "zlt:"; + /** + * 缓存client的redis key,这里是hash结构存储 + */ + String CACHE_CLIENT_KEY = "oauth_client_details"; + /** + * OAUTH模式登录处理地址 + */ + String OAUTH_LOGIN_PRO_URL = "/user/login"; + /** + * PASSWORD模式登录处理地址 + */ + String PASSWORD_LOGIN_PRO_URL = "/oauth/user/token"; + /** + * 获取授权码地址 + */ + String AUTH_CODE_URL = "/oauth/authorize"; + /** + * 登录页面 + */ + String LOGIN_PAGE = "/login.html"; + /** + * 默认的OPENID登录请求处理url + */ + String OPENID_TOKEN_URL = "/oauth/openId/token"; + /** + * 手机登录URL + */ + String MOBILE_TOKEN_URL = "/oauth/mobile/token"; + /** + * 登出URL + */ + String LOGOUT_URL = "/oauth/remove/token"; + /** + * 默认token过期时间(1小时) + */ + Integer ACCESS_TOKEN_VALIDITY_SECONDS = 60 * 60; + /** + * redis中授权token对应的key + */ + String REDIS_TOKEN_AUTH = "auth:"; + /** + * redis中应用对应的token集合的key + */ + String REDIS_CLIENT_ID_TO_ACCESS = "client_id_to_access:"; + /** + * redis中用户名对应的token集合的key + */ + String REDIS_UNAME_TO_ACCESS = "uname_to_access:"; + /** + * rsa公钥 + */ + String RSA_PUBLIC_KEY = "pubkey.txt"; +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/ServiceNameConstants.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ServiceNameConstants.java similarity index 94% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/ServiceNameConstants.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ServiceNameConstants.java index 7a3fd053..ce6ace1a 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/constant/ServiceNameConstants.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/constant/ServiceNameConstants.java @@ -1,19 +1,19 @@ -package com.central.common.constant; - -/** - * 服务名称常量 - * - * @author zlt - * @date 2018/7/27 13:50 - */ -public interface ServiceNameConstants { - - /** - * 用户权限服务 - */ - String USER_SERVICE = "user-center"; - /** - * 搜索中心服务 - */ - String SEARCH_SERVICE = "search-center"; -} +package com.central.common.constant; + +/** + * 服务名称常量 + * + * @author zlt + * @date 2018/7/27 13:50 + */ +public interface ServiceNameConstants { + + /** + * 用户权限服务 + */ + String USER_SERVICE = "user-center"; + /** + * 搜索中心服务 + */ + String SEARCH_SERVICE = "search-center"; +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/context/LbIsolationContextHolder.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/context/LbIsolationContextHolder.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/context/LbIsolationContextHolder.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/context/LbIsolationContextHolder.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/context/TenantContextHolder.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/context/TenantContextHolder.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/context/TenantContextHolder.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/context/TenantContextHolder.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/BusinessException.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/BusinessException.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/BusinessException.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/BusinessException.java index 45864df8..476e5e9d 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/BusinessException.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/BusinessException.java @@ -1,14 +1,14 @@ -package com.central.common.exception; - -/** - * 业务异常 - * - * @author zlt - */ -public class BusinessException extends RuntimeException { - private static final long serialVersionUID = 6610083281801529147L; - - public BusinessException(String message) { - super(message); - } -} +package com.central.common.exception; + +/** + * 业务异常 + * + * @author zlt + */ +public class BusinessException extends RuntimeException { + private static final long serialVersionUID = 6610083281801529147L; + + public BusinessException(String message) { + super(message); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/DefaultExceptionAdvice.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/DefaultExceptionAdvice.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/DefaultExceptionAdvice.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/DefaultExceptionAdvice.java index 41c473cb..c5dca7d7 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/DefaultExceptionAdvice.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/DefaultExceptionAdvice.java @@ -1,103 +1,103 @@ -package com.central.common.exception; - -import com.central.common.model.Result; -import lombok.extern.slf4j.Slf4j; -import org.springframework.http.HttpStatus; -import org.springframework.security.access.AccessDeniedException; -import org.springframework.web.HttpMediaTypeNotSupportedException; -import org.springframework.web.HttpRequestMethodNotSupportedException; -import org.springframework.web.bind.annotation.*; - -import java.sql.SQLException; - -/** - * 异常通用处理 - * - * @author zlt - */ -@ResponseBody -@Slf4j -public class DefaultExceptionAdvice { - /** - * IllegalArgumentException异常处理返回json - * 返回状态码:400 - */ - @ResponseStatus(HttpStatus.BAD_REQUEST) - @ExceptionHandler({IllegalArgumentException.class}) - public Result badRequestException(IllegalArgumentException e) { - return defHandler("参数解析失败", e); - } - - /** - * AccessDeniedException异常处理返回json - * 返回状态码:403 - */ - @ResponseStatus(HttpStatus.FORBIDDEN) - @ExceptionHandler({AccessDeniedException.class}) - public Result badMethodExpressException(AccessDeniedException e) { - return defHandler("没有权限请求当前方法", e); - } - - /** - * 返回状态码:405 - */ - @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) - @ExceptionHandler({HttpRequestMethodNotSupportedException.class}) - public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { - return defHandler("不支持当前请求方法", e); - } - - /** - * 返回状态码:415 - */ - @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) - @ExceptionHandler({HttpMediaTypeNotSupportedException.class}) - public Result handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) { - return defHandler("不支持当前媒体类型", e); - } - - /** - * SQLException sql异常处理 - * 返回状态码:500 - */ - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - @ExceptionHandler({SQLException.class}) - public Result handleSQLException(SQLException e) { - return defHandler("服务运行SQLException异常", e); - } - - /** - * BusinessException 业务异常处理 - * 返回状态码:500 - */ - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - @ExceptionHandler(BusinessException.class) - public Result handleException(BusinessException e) { - return defHandler("业务异常", e); - } - - /** - * IdempotencyException 幂等性异常 - * 返回状态码:200 - */ - @ResponseStatus(HttpStatus.OK) - @ExceptionHandler(IdempotencyException.class) - public Result handleException(IdempotencyException e) { - return Result.failed(e.getMessage()); - } - - /** - * 所有异常统一处理 - * 返回状态码:500 - */ - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) - @ExceptionHandler(Exception.class) - public Result handleException(Exception e) { - return defHandler("未知异常", e); - } - - private Result defHandler(String msg, Exception e) { - log.error(msg, e); - return Result.failed(msg); - } -} +package com.central.common.exception; + +import com.central.common.model.Result; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.web.HttpMediaTypeNotSupportedException; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.annotation.*; + +import java.sql.SQLException; + +/** + * 异常通用处理 + * + * @author zlt + */ +@ResponseBody +@Slf4j +public class DefaultExceptionAdvice { + /** + * IllegalArgumentException异常处理返回json + * 返回状态码:400 + */ + @ResponseStatus(HttpStatus.BAD_REQUEST) + @ExceptionHandler({IllegalArgumentException.class}) + public Result badRequestException(IllegalArgumentException e) { + return defHandler("参数解析失败", e); + } + + /** + * AccessDeniedException异常处理返回json + * 返回状态码:403 + */ + @ResponseStatus(HttpStatus.FORBIDDEN) + @ExceptionHandler({AccessDeniedException.class}) + public Result badMethodExpressException(AccessDeniedException e) { + return defHandler("没有权限请求当前方法", e); + } + + /** + * 返回状态码:405 + */ + @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) + @ExceptionHandler({HttpRequestMethodNotSupportedException.class}) + public Result handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) { + return defHandler("不支持当前请求方法", e); + } + + /** + * 返回状态码:415 + */ + @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE) + @ExceptionHandler({HttpMediaTypeNotSupportedException.class}) + public Result handleHttpMediaTypeNotSupportedException(HttpMediaTypeNotSupportedException e) { + return defHandler("不支持当前媒体类型", e); + } + + /** + * SQLException sql异常处理 + * 返回状态码:500 + */ + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ExceptionHandler({SQLException.class}) + public Result handleSQLException(SQLException e) { + return defHandler("服务运行SQLException异常", e); + } + + /** + * BusinessException 业务异常处理 + * 返回状态码:500 + */ + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ExceptionHandler(BusinessException.class) + public Result handleException(BusinessException e) { + return defHandler("业务异常", e); + } + + /** + * IdempotencyException 幂等性异常 + * 返回状态码:200 + */ + @ResponseStatus(HttpStatus.OK) + @ExceptionHandler(IdempotencyException.class) + public Result handleException(IdempotencyException e) { + return Result.failed(e.getMessage()); + } + + /** + * 所有异常统一处理 + * 返回状态码:500 + */ + @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) + @ExceptionHandler(Exception.class) + public Result handleException(Exception e) { + return defHandler("未知异常", e); + } + + private Result defHandler(String msg, Exception e) { + log.error(msg, e); + return Result.failed(msg); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/IdempotencyException.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/IdempotencyException.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/IdempotencyException.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/IdempotencyException.java index e6a4f4bb..7222d6c0 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/IdempotencyException.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/IdempotencyException.java @@ -1,14 +1,14 @@ -package com.central.common.exception; - -/** - * 幂等性异常 - * - * @author zlt - */ -public class IdempotencyException extends RuntimeException { - private static final long serialVersionUID = 6610083281801529147L; - - public IdempotencyException(String message) { - super(message); - } -} +package com.central.common.exception; + +/** + * 幂等性异常 + * + * @author zlt + */ +public class IdempotencyException extends RuntimeException { + private static final long serialVersionUID = 6610083281801529147L; + + public IdempotencyException(String message) { + super(message); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/LockException.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/LockException.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/LockException.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/LockException.java index 68166d8b..6aa5ceda 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/exception/LockException.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/exception/LockException.java @@ -1,14 +1,14 @@ -package com.central.common.exception; - -/** - * 分布式锁异常 - * - * @author zlt - */ -public class LockException extends RuntimeException { - private static final long serialVersionUID = 6610083281801529147L; - - public LockException(String message) { - super(message); - } -} +package com.central.common.exception; + +/** + * 分布式锁异常 + * + * @author zlt + */ +public class LockException extends RuntimeException { + private static final long serialVersionUID = 6610083281801529147L; + + public LockException(String message) { + super(message); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/feign/UserService.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java similarity index 97% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/feign/UserService.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java index a75c3d5c..427387ad 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/feign/UserService.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/UserService.java @@ -1,51 +1,51 @@ -package com.central.common.feign; - -import com.central.common.constant.ServiceNameConstants; -import com.central.common.feign.fallback.UserServiceFallbackFactory; -import com.central.common.model.LoginAppUser; -import com.central.common.model.SysUser; -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestParam; - -/** - * @author zlt - */ -@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserServiceFallbackFactory.class, decode404 = true) -public interface UserService { - /** - * feign rpc访问远程/users/{username}接口 - * 查询用户实体对象SysUser - * - * @param username - * @return - */ - @GetMapping(value = "/users/name/{username}") - SysUser selectByUsername(@PathVariable("username") String username); - - /** - * feign rpc访问远程/users-anon/login接口 - * - * @param username - * @return - */ - @GetMapping(value = "/users-anon/login", params = "username") - LoginAppUser findByUsername(@RequestParam("username") String username); - - /** - * 通过手机号查询用户、角色信息 - * - * @param mobile 手机号 - */ - @GetMapping(value = "/users-anon/mobile", params = "mobile") - LoginAppUser findByMobile(@RequestParam("mobile") String mobile); - - /** - * 根据OpenId查询用户信息 - * - * @param openId openId - */ - @GetMapping(value = "/users-anon/openId", params = "openId") - LoginAppUser findByOpenId(@RequestParam("openId") String openId); -} +package com.central.common.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.common.feign.fallback.UserServiceFallbackFactory; +import com.central.common.model.LoginAppUser; +import com.central.common.model.SysUser; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; + +/** + * @author zlt + */ +@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = UserServiceFallbackFactory.class, decode404 = true) +public interface UserService { + /** + * feign rpc访问远程/users/{username}接口 + * 查询用户实体对象SysUser + * + * @param username + * @return + */ + @GetMapping(value = "/users/name/{username}") + SysUser selectByUsername(@PathVariable("username") String username); + + /** + * feign rpc访问远程/users-anon/login接口 + * + * @param username + * @return + */ + @GetMapping(value = "/users-anon/login", params = "username") + LoginAppUser findByUsername(@RequestParam("username") String username); + + /** + * 通过手机号查询用户、角色信息 + * + * @param mobile 手机号 + */ + @GetMapping(value = "/users-anon/mobile", params = "mobile") + LoginAppUser findByMobile(@RequestParam("mobile") String mobile); + + /** + * 根据OpenId查询用户信息 + * + * @param openId openId + */ + @GetMapping(value = "/users-anon/openId", params = "openId") + LoginAppUser findByOpenId(@RequestParam("openId") String openId); +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java index 5d5bb62d..aea588d9 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/feign/fallback/UserServiceFallbackFactory.java @@ -1,47 +1,47 @@ -package com.central.common.feign.fallback; - -import com.central.common.feign.UserService; -import com.central.common.model.LoginAppUser; -import com.central.common.model.SysUser; -import feign.hystrix.FallbackFactory; -import lombok.extern.slf4j.Slf4j; -import org.springframework.stereotype.Component; - -/** - * userService降级工场 - * - * @author zlt - * @date 2019/1/18 - */ -@Slf4j -@Component -public class UserServiceFallbackFactory implements FallbackFactory { - @Override - public UserService create(Throwable throwable) { - return new UserService() { - @Override - public SysUser selectByUsername(String username) { - log.error("通过用户名查询用户异常:{}", username, throwable); - return new SysUser(); - } - - @Override - public LoginAppUser findByUsername(String username) { - log.error("通过用户名查询用户异常:{}", username, throwable); - return new LoginAppUser(); - } - - @Override - public LoginAppUser findByMobile(String mobile) { - log.error("通过手机号查询用户异常:{}", mobile, throwable); - return new LoginAppUser(); - } - - @Override - public LoginAppUser findByOpenId(String openId) { - log.error("通过openId查询用户异常:{}", openId, throwable); - return new LoginAppUser(); - } - }; - } -} +package com.central.common.feign.fallback; + +import com.central.common.feign.UserService; +import com.central.common.model.LoginAppUser; +import com.central.common.model.SysUser; +import feign.hystrix.FallbackFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * userService降级工场 + * + * @author zlt + * @date 2019/1/18 + */ +@Slf4j +@Component +public class UserServiceFallbackFactory implements FallbackFactory { + @Override + public UserService create(Throwable throwable) { + return new UserService() { + @Override + public SysUser selectByUsername(String username) { + log.error("通过用户名查询用户异常:{}", username, throwable); + return new SysUser(); + } + + @Override + public LoginAppUser findByUsername(String username) { + log.error("通过用户名查询用户异常:{}", username, throwable); + return new LoginAppUser(); + } + + @Override + public LoginAppUser findByMobile(String mobile) { + log.error("通过手机号查询用户异常:{}", mobile, throwable); + return new LoginAppUser(); + } + + @Override + public LoginAppUser findByOpenId(String openId) { + log.error("通过openId查询用户异常:{}", openId, throwable); + return new LoginAppUser(); + } + }; + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/lock/AbstractDistributedLock.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/lock/AbstractDistributedLock.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/lock/AbstractDistributedLock.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/lock/AbstractDistributedLock.java index 5530b526..f2863f9c 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/lock/AbstractDistributedLock.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/lock/AbstractDistributedLock.java @@ -1,35 +1,35 @@ -package com.central.common.lock; - -/** - * 分布式锁抽象类 - * - * @author zlt - * @date 2018/5/29 14:14 - */ -public abstract class AbstractDistributedLock implements DistributedLock{ - - @Override - public boolean lock(String key) { - return lock(key, TIMEOUT_MILLIS, RETRY_TIMES, SLEEP_MILLIS); - } - - @Override - public boolean lock(String key, int retryTimes) { - return lock(key, TIMEOUT_MILLIS, retryTimes, SLEEP_MILLIS); - } - - @Override - public boolean lock(String key, int retryTimes, long sleepMillis) { - return lock(key, TIMEOUT_MILLIS, retryTimes, sleepMillis); - } - - @Override - public boolean lock(String key, long expire) { - return lock(key, expire, RETRY_TIMES, SLEEP_MILLIS); - } - - @Override - public boolean lock(String key, long expire, int retryTimes) { - return lock(key, expire, retryTimes, SLEEP_MILLIS); - } -} +package com.central.common.lock; + +/** + * 分布式锁抽象类 + * + * @author zlt + * @date 2018/5/29 14:14 + */ +public abstract class AbstractDistributedLock implements DistributedLock{ + + @Override + public boolean lock(String key) { + return lock(key, TIMEOUT_MILLIS, RETRY_TIMES, SLEEP_MILLIS); + } + + @Override + public boolean lock(String key, int retryTimes) { + return lock(key, TIMEOUT_MILLIS, retryTimes, SLEEP_MILLIS); + } + + @Override + public boolean lock(String key, int retryTimes, long sleepMillis) { + return lock(key, TIMEOUT_MILLIS, retryTimes, sleepMillis); + } + + @Override + public boolean lock(String key, long expire) { + return lock(key, expire, RETRY_TIMES, SLEEP_MILLIS); + } + + @Override + public boolean lock(String key, long expire, int retryTimes) { + return lock(key, expire, retryTimes, SLEEP_MILLIS); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/lock/DistributedLock.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/lock/DistributedLock.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/lock/DistributedLock.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/lock/DistributedLock.java index 51266bad..b44043a5 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/lock/DistributedLock.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/lock/DistributedLock.java @@ -1,93 +1,93 @@ -package com.central.common.lock; - -/** - * 分布式锁顶级接口 - * 例如: - * RETRY_TIMES=100,SLEEP_MILLIS=100 - * RETRY_TIMES * SLEEP_MILLIS = 10000 意味着如果一直获取不了锁,最长会等待10秒后抛超时异常 - * - * @author zlt - * @date 2018/5/29 14:12 - */ -public interface DistributedLock { - - /** - * 默认超时时间 - */ - long TIMEOUT_MILLIS = 5000; - - /** - * 重试次数 - */ - int RETRY_TIMES = 100; - - /** - * 每次重试后等待的时间 - */ - long SLEEP_MILLIS = 100; - - /** - * 获取锁 - * - * @param key key - * @return 成功/失败 - */ - boolean lock(String key); - - /** - * 获取锁 - * - * @param key key - * @param retryTimes 重试次数 - * @return 成功/失败 - */ - boolean lock(String key, int retryTimes); - - /** - * 获取锁 - * - * @param key key - * @param retryTimes 重试次数 - * @param sleepMillis 获取锁失败的重试间隔 - * @return 成功/失败 - */ - boolean lock(String key, int retryTimes, long sleepMillis); - - /** - * 获取锁 - * - * @param key key - * @param expire 获取锁超时时间 - * @return 成功/失败 - */ - boolean lock(String key, long expire); - - /** - * 获取锁 - * - * @param key key - * @param expire 获取锁超时时间 - * @param retryTimes 重试次数 - * @return 成功/失败 - */ - boolean lock(String key, long expire, int retryTimes); - - /** - * 获取锁 - * - * @param key key - * @param expire 获取锁超时时间 - * @param retryTimes 重试次数 - * @param sleepMillis 获取锁失败的重试间隔 - * @return 成功/失败 - */ - boolean lock(String key, long expire, int retryTimes, long sleepMillis); - - /** - * 释放锁 - * - * @param key key值 - * @return 释放结果 - */ - boolean releaseLock(String key); -} +package com.central.common.lock; + +/** + * 分布式锁顶级接口 + * 例如: + * RETRY_TIMES=100,SLEEP_MILLIS=100 + * RETRY_TIMES * SLEEP_MILLIS = 10000 意味着如果一直获取不了锁,最长会等待10秒后抛超时异常 + * + * @author zlt + * @date 2018/5/29 14:12 + */ +public interface DistributedLock { + + /** + * 默认超时时间 + */ + long TIMEOUT_MILLIS = 5000; + + /** + * 重试次数 + */ + int RETRY_TIMES = 100; + + /** + * 每次重试后等待的时间 + */ + long SLEEP_MILLIS = 100; + + /** + * 获取锁 + * + * @param key key + * @return 成功/失败 + */ + boolean lock(String key); + + /** + * 获取锁 + * + * @param key key + * @param retryTimes 重试次数 + * @return 成功/失败 + */ + boolean lock(String key, int retryTimes); + + /** + * 获取锁 + * + * @param key key + * @param retryTimes 重试次数 + * @param sleepMillis 获取锁失败的重试间隔 + * @return 成功/失败 + */ + boolean lock(String key, int retryTimes, long sleepMillis); + + /** + * 获取锁 + * + * @param key key + * @param expire 获取锁超时时间 + * @return 成功/失败 + */ + boolean lock(String key, long expire); + + /** + * 获取锁 + * + * @param key key + * @param expire 获取锁超时时间 + * @param retryTimes 重试次数 + * @return 成功/失败 + */ + boolean lock(String key, long expire, int retryTimes); + + /** + * 获取锁 + * + * @param key key + * @param expire 获取锁超时时间 + * @param retryTimes 重试次数 + * @param sleepMillis 获取锁失败的重试间隔 + * @return 成功/失败 + */ + boolean lock(String key, long expire, int retryTimes, long sleepMillis); + + /** + * 释放锁 + * + * @param key key值 + * @return 释放结果 + */ + boolean releaseLock(String key); +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/CodeEnum.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/CodeEnum.java similarity index 93% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/CodeEnum.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/CodeEnum.java index 3c80502d..cd39bd9c 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/CodeEnum.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/CodeEnum.java @@ -1,18 +1,18 @@ -package com.central.common.model; - -/** - * @Author: zlt - */ -public enum CodeEnum { - SUCCESS(0), - ERROR(1); - - private Integer code; - CodeEnum(Integer code){ - this.code = code; - } - - public Integer getCode() { - return code; - } -} +package com.central.common.model; + +/** + * @Author: zlt + */ +public enum CodeEnum { + SUCCESS(0), + ERROR(1); + + private Integer code; + CodeEnum(Integer code){ + this.code = code; + } + + public Integer getCode() { + return code; + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/LoginAppUser.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/LoginAppUser.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/LoginAppUser.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/LoginAppUser.java index d2bd58c0..2001764b 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/LoginAppUser.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/LoginAppUser.java @@ -1,65 +1,65 @@ -package com.central.common.model; - -import java.util.Collection; -import java.util.HashSet; -import java.util.Set; - -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.authority.SimpleGrantedAuthority; -import org.springframework.social.security.SocialUserDetails; -import org.springframework.util.CollectionUtils; - -import com.fasterxml.jackson.annotation.JsonIgnore; - -import lombok.Getter; -import lombok.Setter; - -/** - * @author zlt - * 用户实体绑定spring security - */ -@Getter -@Setter -public class LoginAppUser extends SysUser implements SocialUserDetails { - private static final long serialVersionUID = -3685249101751401211L; - - private Set permissions; - - /*** - * 权限重写 - */ - @JsonIgnore - @Override - public Collection getAuthorities() { - Collection collection = new HashSet<>(); - if (!CollectionUtils.isEmpty(super.getRoles())) { - super.getRoles().parallelStream().forEach(role -> collection.add(new SimpleGrantedAuthority(role.getCode()))); - } - return collection; - } - - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - - @Override - public boolean isEnabled() { - return getEnabled(); - } - - @Override - public String getUserId() { - return getOpenId(); - } -} +package com.central.common.model; + +import java.util.Collection; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.authority.SimpleGrantedAuthority; +import org.springframework.social.security.SocialUserDetails; +import org.springframework.util.CollectionUtils; + +import com.fasterxml.jackson.annotation.JsonIgnore; + +import lombok.Getter; +import lombok.Setter; + +/** + * @author zlt + * 用户实体绑定spring security + */ +@Getter +@Setter +public class LoginAppUser extends SysUser implements SocialUserDetails { + private static final long serialVersionUID = -3685249101751401211L; + + private Set permissions; + + /*** + * 权限重写 + */ + @JsonIgnore + @Override + public Collection getAuthorities() { + Collection collection = new HashSet<>(); + if (!CollectionUtils.isEmpty(super.getRoles())) { + super.getRoles().parallelStream().forEach(role -> collection.add(new SimpleGrantedAuthority(role.getCode()))); + } + return collection; + } + + @Override + public boolean isAccountNonExpired() { + return true; + } + + @Override + public boolean isAccountNonLocked() { + return true; + } + + @Override + public boolean isCredentialsNonExpired() { + return true; + } + + @Override + public boolean isEnabled() { + return getEnabled(); + } + + @Override + public String getUserId() { + return getOpenId(); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/PageResult.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/PageResult.java similarity index 94% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/PageResult.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/PageResult.java index e8851739..5404fc23 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/PageResult.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/PageResult.java @@ -1,34 +1,34 @@ -package com.central.common.model; - -import java.io.Serializable; -import java.util.List; - -import lombok.AllArgsConstructor; -import lombok.Builder; -import lombok.Data; -import lombok.NoArgsConstructor; - -/** - * 分页实体类 - * - * @author zlt - */ -@Data -@Builder -@NoArgsConstructor -@AllArgsConstructor -public class PageResult implements Serializable { - private static final long serialVersionUID = -275582248840137389L; - /** - * 总数 - */ - private Long count; - /** - * 是否成功:0 成功、1 失败 - */ - private int code; - /** - * 当前页结果集 - */ - private List data; -} +package com.central.common.model; + +import java.io.Serializable; +import java.util.List; + +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; + +/** + * 分页实体类 + * + * @author zlt + */ +@Data +@Builder +@NoArgsConstructor +@AllArgsConstructor +public class PageResult implements Serializable { + private static final long serialVersionUID = -275582248840137389L; + /** + * 总数 + */ + private Long count; + /** + * 是否成功:0 成功、1 失败 + */ + private int code; + /** + * 当前页结果集 + */ + private List data; +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/Result.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/Result.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/Result.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/Result.java index cbc694bc..e6ae5915 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/Result.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/Result.java @@ -1,49 +1,49 @@ -package com.central.common.model; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.io.Serializable; - -/** - * @Author: zlt - */ -@Data -@NoArgsConstructor -@AllArgsConstructor -public class Result implements Serializable { - - private T datas; - private Integer resp_code; - private String resp_msg; - - public static Result succeed(String msg) { - return succeedWith(null, CodeEnum.SUCCESS.getCode(), msg); - } - - public static Result succeed(T model, String msg) { - return succeedWith(model, CodeEnum.SUCCESS.getCode(), msg); - } - - public static Result succeed(T model) { - return succeedWith(model, CodeEnum.SUCCESS.getCode(), ""); - } - - public static Result succeedWith(T datas, Integer code, String msg) { - return new Result<>(datas, code, msg); - } - - public static Result failed(String msg) { - return failedWith(null, CodeEnum.ERROR.getCode(), msg); - } - - public static Result failed(T model, String msg) { - return failedWith(model, CodeEnum.ERROR.getCode(), msg); - } - - public static Result failedWith(T datas, Integer code, String msg) { - return new Result<>(datas, code, msg); - } - -} +package com.central.common.model; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.io.Serializable; + +/** + * @Author: zlt + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class Result implements Serializable { + + private T datas; + private Integer resp_code; + private String resp_msg; + + public static Result succeed(String msg) { + return succeedWith(null, CodeEnum.SUCCESS.getCode(), msg); + } + + public static Result succeed(T model, String msg) { + return succeedWith(model, CodeEnum.SUCCESS.getCode(), msg); + } + + public static Result succeed(T model) { + return succeedWith(model, CodeEnum.SUCCESS.getCode(), ""); + } + + public static Result succeedWith(T datas, Integer code, String msg) { + return new Result<>(datas, code, msg); + } + + public static Result failed(String msg) { + return failedWith(null, CodeEnum.ERROR.getCode(), msg); + } + + public static Result failed(T model, String msg) { + return failedWith(model, CodeEnum.ERROR.getCode(), msg); + } + + public static Result failedWith(T datas, Integer code, String msg) { + return new Result<>(datas, code, msg); + } + +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SuperEntity.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SuperEntity.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SuperEntity.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SuperEntity.java index d1de0c2f..f7778346 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SuperEntity.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SuperEntity.java @@ -1,35 +1,35 @@ -package com.central.common.model; - -import com.baomidou.mybatisplus.annotation.FieldFill; -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableId; -import com.baomidou.mybatisplus.extension.activerecord.Model; -import lombok.Getter; -import lombok.Setter; - -import java.io.Serializable; -import java.util.Date; - -/** - * 实体父类 - * - * @author zlt - */ -@Setter -@Getter -public class SuperEntity> extends Model { - /** - * 主键ID - */ - @TableId - private Long id; - @TableField(fill = FieldFill.INSERT) - private Date createTime; - @TableField(fill = FieldFill.INSERT_UPDATE) - private Date updateTime; - - @Override - protected Serializable pkVal() { - return this.id; - } -} +package com.central.common.model; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.extension.activerecord.Model; +import lombok.Getter; +import lombok.Setter; + +import java.io.Serializable; +import java.util.Date; + +/** + * 实体父类 + * + * @author zlt + */ +@Setter +@Getter +public class SuperEntity> extends Model { + /** + * 主键ID + */ + @TableId + private Long id; + @TableField(fill = FieldFill.INSERT) + private Date createTime; + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateTime; + + @Override + protected Serializable pkVal() { + return this.id; + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysMenu.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysMenu.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysMenu.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysMenu.java index ca525730..bd3de705 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysMenu.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysMenu.java @@ -1,39 +1,39 @@ -package com.central.common.model; - -import java.util.List; -import java.util.Set; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - * @author zlt - */ -@Data -@EqualsAndHashCode(callSuper = false) -@TableName("sys_menu") -public class SysMenu extends SuperEntity { - private static final long serialVersionUID = 749360940290141180L; - - private Long parentId; - private String name; - private String css; - private String url; - private String path; - private Integer sort; - private Integer type; - private Boolean hidden; - /** - * 请求的类型 - */ - private String pathMethod; - - @TableField(exist = false) - private List subMenus; - @TableField(exist = false) - private Long roleId; - @TableField(exist = false) - private Set menuIds; -} +package com.central.common.model; + +import java.util.List; +import java.util.Set; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @author zlt + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("sys_menu") +public class SysMenu extends SuperEntity { + private static final long serialVersionUID = 749360940290141180L; + + private Long parentId; + private String name; + private String css; + private String url; + private String path; + private Integer sort; + private Integer type; + private Boolean hidden; + /** + * 请求的类型 + */ + private String pathMethod; + + @TableField(exist = false) + private List subMenus; + @TableField(exist = false) + private Long roleId; + @TableField(exist = false) + private Set menuIds; +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysRole.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysRole.java similarity index 95% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysRole.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysRole.java index f71e251f..303071b4 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysRole.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysRole.java @@ -1,19 +1,19 @@ -package com.central.common.model; - -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - * @author zlt - * 角色 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@TableName("sys_role") -public class SysRole extends SuperEntity { - private static final long serialVersionUID = 4497149010220586111L; - private String code; - private String name; - private Long userId; -} +package com.central.common.model; + +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @author zlt + * 角色 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("sys_role") +public class SysRole extends SuperEntity { + private static final long serialVersionUID = 4497149010220586111L; + private String code; + private String name; + private Long userId; +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysUser.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysUser.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java index 1f065b9a..8a3b4185 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/SysUser.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/SysUser.java @@ -1,41 +1,41 @@ -package com.central.common.model; - -import java.util.List; - -import com.baomidou.mybatisplus.annotation.TableField; -import com.baomidou.mybatisplus.annotation.TableLogic; -import com.baomidou.mybatisplus.annotation.TableName; -import lombok.Data; -import lombok.EqualsAndHashCode; - -/** - * @author zlt - * 用户实体 - */ -@Data -@EqualsAndHashCode(callSuper = false) -@TableName("sys_user") -public class SysUser extends SuperEntity { - private static final long serialVersionUID = -5886012896705137070L; - - private String username; - private String password; - private String nickname; - private String headImgUrl; - private String mobile; - private Integer sex; - private Boolean enabled; - private String type; - private String openId; - @TableLogic - private boolean isDel; - - @TableField(exist = false) - private List roles; - @TableField(exist = false) - private String roleId; - @TableField(exist = false) - private String oldPassword; - @TableField(exist = false) - private String newPassword; -} +package com.central.common.model; + +import java.util.List; + +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableLogic; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * @author zlt + * 用户实体 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("sys_user") +public class SysUser extends SuperEntity { + private static final long serialVersionUID = -5886012896705137070L; + + private String username; + private String password; + private String nickname; + private String headImgUrl; + private String mobile; + private Integer sex; + private Boolean enabled; + private String type; + private String openId; + @TableLogic + private boolean isDel; + + @TableField(exist = false) + private List roles; + @TableField(exist = false) + private String roleId; + @TableField(exist = false) + private String oldPassword; + @TableField(exist = false) + private String newPassword; +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/UserType.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/UserType.java similarity index 90% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/UserType.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/model/UserType.java index 2375c8c7..e7953064 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/model/UserType.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/model/UserType.java @@ -1,18 +1,18 @@ -package com.central.common.model; - - -/** - * @author zlt - * 用户类型 - */ -public enum UserType { - - /** - * 前端app用户 - */ - APP, - /** - * 后端管理用户 - */ - BACKEND -} +package com.central.common.model; + + +/** + * @author zlt + * 用户类型 + */ +public enum UserType { + + /** + * 前端app用户 + */ + APP, + /** + * 后端管理用户 + */ + BACKEND +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/properties/TenantProperties.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/properties/TenantProperties.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/properties/TenantProperties.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/properties/TenantProperties.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/resolver/ClientArgumentResolver.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/ClientArgumentResolver.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/resolver/ClientArgumentResolver.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/ClientArgumentResolver.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/resolver/TokenArgumentResolver.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/TokenArgumentResolver.java similarity index 97% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/resolver/TokenArgumentResolver.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/TokenArgumentResolver.java index acd59e2e..19a1183f 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/resolver/TokenArgumentResolver.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/resolver/TokenArgumentResolver.java @@ -1,85 +1,85 @@ -package com.central.common.resolver; - -import cn.hutool.core.util.StrUtil; -import com.central.common.annotation.LoginUser; -import com.central.common.constant.SecurityConstants; -import com.central.common.feign.UserService; -import com.central.common.model.SysRole; -import com.central.common.model.SysUser; -import lombok.extern.slf4j.Slf4j; -import org.springframework.core.MethodParameter; -import org.springframework.web.bind.support.WebDataBinderFactory; -import org.springframework.web.context.request.NativeWebRequest; -import org.springframework.web.method.support.HandlerMethodArgumentResolver; -import org.springframework.web.method.support.ModelAndViewContainer; - -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Token转化SysUser - * - * @author zlt - * @date 2018/12/21 - */ -@Slf4j -public class TokenArgumentResolver implements HandlerMethodArgumentResolver { - private UserService userService; - - public TokenArgumentResolver(UserService userService) { - this.userService = userService; - } - - /** - * 入参筛选 - * - * @param methodParameter 参数集合 - * @return 格式化后的参数 - */ - @Override - public boolean supportsParameter(MethodParameter methodParameter) { - return methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().equals(SysUser.class); - } - - /** - * @param methodParameter 入参集合 - * @param modelAndViewContainer model 和 view - * @param nativeWebRequest web相关 - * @param webDataBinderFactory 入参解析 - * @return 包装对象 - */ - @Override - public Object resolveArgument(MethodParameter methodParameter, - ModelAndViewContainer modelAndViewContainer, - NativeWebRequest nativeWebRequest, - WebDataBinderFactory webDataBinderFactory) { - LoginUser loginUser = methodParameter.getParameterAnnotation(LoginUser.class); - boolean isFull = loginUser.isFull(); - HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class); - String userId = request.getHeader(SecurityConstants.USER_ID_HEADER); - String username = request.getHeader(SecurityConstants.USER_HEADER); - String roles = request.getHeader(SecurityConstants.ROLE_HEADER); - if (StrUtil.isBlank(username)) { - log.warn("resolveArgument error username is empty"); - return null; - } - SysUser user; - if (isFull) { - user = userService.selectByUsername(username); - } else { - user = new SysUser(); - user.setId(Long.valueOf(userId)); - user.setUsername(username); - } - List sysRoleList = new ArrayList<>(); - Arrays.stream(roles.split(",")).forEach(role -> { - SysRole sysRole = new SysRole(); - sysRole.setCode(role); - sysRoleList.add(sysRole); - }); - user.setRoles(sysRoleList); - return user; - } -} +package com.central.common.resolver; + +import cn.hutool.core.util.StrUtil; +import com.central.common.annotation.LoginUser; +import com.central.common.constant.SecurityConstants; +import com.central.common.feign.UserService; +import com.central.common.model.SysRole; +import com.central.common.model.SysUser; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.MethodParameter; +import org.springframework.web.bind.support.WebDataBinderFactory; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.method.support.HandlerMethodArgumentResolver; +import org.springframework.web.method.support.ModelAndViewContainer; + +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Token转化SysUser + * + * @author zlt + * @date 2018/12/21 + */ +@Slf4j +public class TokenArgumentResolver implements HandlerMethodArgumentResolver { + private UserService userService; + + public TokenArgumentResolver(UserService userService) { + this.userService = userService; + } + + /** + * 入参筛选 + * + * @param methodParameter 参数集合 + * @return 格式化后的参数 + */ + @Override + public boolean supportsParameter(MethodParameter methodParameter) { + return methodParameter.hasParameterAnnotation(LoginUser.class) && methodParameter.getParameterType().equals(SysUser.class); + } + + /** + * @param methodParameter 入参集合 + * @param modelAndViewContainer model 和 view + * @param nativeWebRequest web相关 + * @param webDataBinderFactory 入参解析 + * @return 包装对象 + */ + @Override + public Object resolveArgument(MethodParameter methodParameter, + ModelAndViewContainer modelAndViewContainer, + NativeWebRequest nativeWebRequest, + WebDataBinderFactory webDataBinderFactory) { + LoginUser loginUser = methodParameter.getParameterAnnotation(LoginUser.class); + boolean isFull = loginUser.isFull(); + HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class); + String userId = request.getHeader(SecurityConstants.USER_ID_HEADER); + String username = request.getHeader(SecurityConstants.USER_HEADER); + String roles = request.getHeader(SecurityConstants.ROLE_HEADER); + if (StrUtil.isBlank(username)) { + log.warn("resolveArgument error username is empty"); + return null; + } + SysUser user; + if (isFull) { + user = userService.selectByUsername(username); + } else { + user = new SysUser(); + user.setId(Long.valueOf(userId)); + user.setUsername(username); + } + List sysRoleList = new ArrayList<>(); + Arrays.stream(roles.split(",")).forEach(role -> { + SysRole sysRole = new SysRole(); + sysRole.setCode(role); + sysRoleList.add(sysRole); + }); + user.setRoles(sysRoleList); + return user; + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/service/ISuperService.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/service/ISuperService.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/service/ISuperService.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/service/ISuperService.java index b4f5bfef..95e258bb 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/service/ISuperService.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/service/ISuperService.java @@ -1,59 +1,59 @@ -package com.central.common.service; - -import com.baomidou.mybatisplus.core.conditions.Wrapper; -import com.baomidou.mybatisplus.extension.service.IService; -import com.central.common.lock.DistributedLock; - -/** - * service接口父类 - * - * @author zlt - * @date 2019/1/10 - */ -public interface ISuperService extends IService { - /** - * 幂等性新增记录 - * - * @param entity 实体对象 - * @param lock 锁实例 - * @param lockKey 锁的key - * @param countWrapper 判断是否存在的条件 - * @param msg 对象已存在提示信息 - * @return - */ - boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper, String msg); - - /** - * 幂等性新增记录 - * - * @param entity 实体对象 - * @param lock 锁实例 - * @param lockKey 锁的key - * @param countWrapper 判断是否存在的条件 - * @return - */ - boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper); - - /** - * 幂等性新增或更新记录 - * - * @param entity 实体对象 - * @param lock 锁实例 - * @param lockKey 锁的key - * @param countWrapper 判断是否存在的条件 - * @param msg 对象已存在提示信息 - * @return - */ - boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper, String msg); - - /** - * 幂等性新增或更新记录 - * - * @param entity 实体对象 - * @param lock 锁实例 - * @param lockKey 锁的key - * @param countWrapper 判断是否存在的条件 - * @return - */ - boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper); -} +package com.central.common.service; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.extension.service.IService; +import com.central.common.lock.DistributedLock; + +/** + * service接口父类 + * + * @author zlt + * @date 2019/1/10 + */ +public interface ISuperService extends IService { + /** + * 幂等性新增记录 + * + * @param entity 实体对象 + * @param lock 锁实例 + * @param lockKey 锁的key + * @param countWrapper 判断是否存在的条件 + * @param msg 对象已存在提示信息 + * @return + */ + boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper, String msg); + + /** + * 幂等性新增记录 + * + * @param entity 实体对象 + * @param lock 锁实例 + * @param lockKey 锁的key + * @param countWrapper 判断是否存在的条件 + * @return + */ + boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper); + + /** + * 幂等性新增或更新记录 + * + * @param entity 实体对象 + * @param lock 锁实例 + * @param lockKey 锁的key + * @param countWrapper 判断是否存在的条件 + * @param msg 对象已存在提示信息 + * @return + */ + boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper, String msg); + + /** + * 幂等性新增或更新记录 + * + * @param entity 实体对象 + * @param lock 锁实例 + * @param lockKey 锁的key + * @param countWrapper 判断是否存在的条件 + * @return + */ + boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper); +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/service/impl/SuperServiceImpl.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/service/impl/SuperServiceImpl.java similarity index 97% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/service/impl/SuperServiceImpl.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/service/impl/SuperServiceImpl.java index 1ad366c7..a29a2292 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/service/impl/SuperServiceImpl.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/service/impl/SuperServiceImpl.java @@ -1,141 +1,141 @@ -package com.central.common.service.impl; - -import cn.hutool.core.util.StrUtil; -import com.baomidou.mybatisplus.core.conditions.Wrapper; -import com.baomidou.mybatisplus.core.mapper.BaseMapper; -import com.baomidou.mybatisplus.core.metadata.TableInfo; -import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; -import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils; -import com.baomidou.mybatisplus.core.toolkit.ReflectionKit; -import com.baomidou.mybatisplus.core.toolkit.StringUtils; -import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.central.common.exception.IdempotencyException; -import com.central.common.exception.LockException; -import com.central.common.lock.DistributedLock; -import com.central.common.service.ISuperService; - -import java.io.Serializable; -import java.util.Objects; - -/** - * service实现父类 - * - * @author zlt - * @date 2019/1/10 - */ -public class SuperServiceImpl, T> extends ServiceImpl implements ISuperService { - /** - * 幂等性新增记录 - * 例子如下: - * String username = sysUser.getUsername(); - * boolean result = super.saveIdempotency(sysUser, lock - * , LOCK_KEY_USERNAME+username - * , new QueryWrapper().eq("username", username)); - * - * @param entity 实体对象 - * @param lock 锁实例 - * @param lockKey 锁的key - * @param countWrapper 判断是否存在的条件 - * @param msg 对象已存在提示信息 - * @return - */ - @Override - public boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper, String msg) { - if (lock == null) { - throw new LockException("DistributedLock is null"); - } - if (StrUtil.isEmpty(lockKey)) { - throw new LockException("lockKey is null"); - } - try { - //加锁 - boolean isLock = lock.lock(lockKey); - if (isLock) { - //判断记录是否已存在 - int count = super.count(countWrapper); - if (count == 0) { - return super.save(entity); - } else { - if (StrUtil.isEmpty(msg)) { - msg = "已存在"; - } - throw new IdempotencyException(msg); - } - } else { - throw new LockException("锁等待超时"); - } - } finally { - lock.releaseLock(lockKey); - } - } - - /** - * 幂等性新增记录 - * - * @param entity 实体对象 - * @param lock 锁实例 - * @param lockKey 锁的key - * @param countWrapper 判断是否存在的条件 - * @return - */ - @Override - public boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper) { - return saveIdempotency(entity, lock, lockKey, countWrapper, null); - } - - /** - * 幂等性新增或更新记录 - * 例子如下: - * String username = sysUser.getUsername(); - * boolean result = super.saveOrUpdateIdempotency(sysUser, lock - * , LOCK_KEY_USERNAME+username - * , new QueryWrapper().eq("username", username)); - * - * @param entity 实体对象 - * @param lock 锁实例 - * @param lockKey 锁的key - * @param countWrapper 判断是否存在的条件 - * @param msg 对象已存在提示信息 - * @return - */ - @Override - public boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper, String msg) { - if (null != entity) { - Class cls = entity.getClass(); - TableInfo tableInfo = TableInfoHelper.getTableInfo(cls); - if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) { - Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty()); - if (StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal))) { - if (StrUtil.isEmpty(msg)) { - msg = "已存在"; - } - return this.saveIdempotency(entity, lock, lockKey, countWrapper, msg); - } else { - return updateById(entity); - } - } else { - throw ExceptionUtils.mpe("Error: Can not execute. Could not find @TableId."); - } - } - return false; - } - - /** - * 幂等性新增或更新记录 - * 例子如下: - * String username = sysUser.getUsername(); - * boolean result = super.saveOrUpdateIdempotency(sysUser, lock - * , LOCK_KEY_USERNAME+username - * , new QueryWrapper().eq("username", username)); - * - * @param entity 实体对象 - * @param lock 锁实例 - * @param lockKey 锁的key - * @param countWrapper 判断是否存在的条件 - * @return - */ - @Override - public boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper) { - return this.saveOrUpdateIdempotency(entity, lock, lockKey, countWrapper, null); - } -} +package com.central.common.service.impl; + +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.TableInfo; +import com.baomidou.mybatisplus.core.metadata.TableInfoHelper; +import com.baomidou.mybatisplus.core.toolkit.ExceptionUtils; +import com.baomidou.mybatisplus.core.toolkit.ReflectionKit; +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.central.common.exception.IdempotencyException; +import com.central.common.exception.LockException; +import com.central.common.lock.DistributedLock; +import com.central.common.service.ISuperService; + +import java.io.Serializable; +import java.util.Objects; + +/** + * service实现父类 + * + * @author zlt + * @date 2019/1/10 + */ +public class SuperServiceImpl, T> extends ServiceImpl implements ISuperService { + /** + * 幂等性新增记录 + * 例子如下: + * String username = sysUser.getUsername(); + * boolean result = super.saveIdempotency(sysUser, lock + * , LOCK_KEY_USERNAME+username + * , new QueryWrapper().eq("username", username)); + * + * @param entity 实体对象 + * @param lock 锁实例 + * @param lockKey 锁的key + * @param countWrapper 判断是否存在的条件 + * @param msg 对象已存在提示信息 + * @return + */ + @Override + public boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper, String msg) { + if (lock == null) { + throw new LockException("DistributedLock is null"); + } + if (StrUtil.isEmpty(lockKey)) { + throw new LockException("lockKey is null"); + } + try { + //加锁 + boolean isLock = lock.lock(lockKey); + if (isLock) { + //判断记录是否已存在 + int count = super.count(countWrapper); + if (count == 0) { + return super.save(entity); + } else { + if (StrUtil.isEmpty(msg)) { + msg = "已存在"; + } + throw new IdempotencyException(msg); + } + } else { + throw new LockException("锁等待超时"); + } + } finally { + lock.releaseLock(lockKey); + } + } + + /** + * 幂等性新增记录 + * + * @param entity 实体对象 + * @param lock 锁实例 + * @param lockKey 锁的key + * @param countWrapper 判断是否存在的条件 + * @return + */ + @Override + public boolean saveIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper) { + return saveIdempotency(entity, lock, lockKey, countWrapper, null); + } + + /** + * 幂等性新增或更新记录 + * 例子如下: + * String username = sysUser.getUsername(); + * boolean result = super.saveOrUpdateIdempotency(sysUser, lock + * , LOCK_KEY_USERNAME+username + * , new QueryWrapper().eq("username", username)); + * + * @param entity 实体对象 + * @param lock 锁实例 + * @param lockKey 锁的key + * @param countWrapper 判断是否存在的条件 + * @param msg 对象已存在提示信息 + * @return + */ + @Override + public boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper, String msg) { + if (null != entity) { + Class cls = entity.getClass(); + TableInfo tableInfo = TableInfoHelper.getTableInfo(cls); + if (null != tableInfo && StringUtils.isNotEmpty(tableInfo.getKeyProperty())) { + Object idVal = ReflectionKit.getMethodValue(cls, entity, tableInfo.getKeyProperty()); + if (StringUtils.checkValNull(idVal) || Objects.isNull(getById((Serializable) idVal))) { + if (StrUtil.isEmpty(msg)) { + msg = "已存在"; + } + return this.saveIdempotency(entity, lock, lockKey, countWrapper, msg); + } else { + return updateById(entity); + } + } else { + throw ExceptionUtils.mpe("Error: Can not execute. Could not find @TableId."); + } + } + return false; + } + + /** + * 幂等性新增或更新记录 + * 例子如下: + * String username = sysUser.getUsername(); + * boolean result = super.saveOrUpdateIdempotency(sysUser, lock + * , LOCK_KEY_USERNAME+username + * , new QueryWrapper().eq("username", username)); + * + * @param entity 实体对象 + * @param lock 锁实例 + * @param lockKey 锁的key + * @param countWrapper 判断是否存在的条件 + * @return + */ + @Override + public boolean saveOrUpdateIdempotency(T entity, DistributedLock lock, String lockKey, Wrapper countWrapper) { + return this.saveOrUpdateIdempotency(entity, lock, lockKey, countWrapper, null); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/AddrUtil.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/AddrUtil.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/AddrUtil.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/AddrUtil.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/CustomBanner.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/CustomBanner.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/CustomBanner.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/CustomBanner.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/CustomThreadPoolTaskExecutor.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/ExcelUtil.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/ExcelUtil.java similarity index 97% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/ExcelUtil.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/ExcelUtil.java index 6c89841a..fa4d2741 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/ExcelUtil.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/ExcelUtil.java @@ -1,120 +1,120 @@ -package com.central.common.utils; - -import cn.afterturn.easypoi.excel.ExcelExportUtil; -import cn.afterturn.easypoi.excel.ExcelImportUtil; -import cn.afterturn.easypoi.excel.entity.ExportParams; -import cn.afterturn.easypoi.excel.entity.ImportParams; -import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; -import org.apache.commons.lang3.StringUtils; -import org.apache.poi.ss.usermodel.Workbook; -import org.springframework.web.multipart.MultipartFile; - -import javax.servlet.http.HttpServletResponse; -import java.io.File; -import java.io.IOException; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -/** - * Excel工具类 - * - * @author zlt - * @date 2019/1/6 - */ -public class ExcelUtil { - private ExcelUtil() { - throw new IllegalStateException("Utility class"); - } - - /** - * 导出 - * - * @param list 数据列表 - * @param title 标题 - * @param sheetName sheet名称 - * @param pojoClass 元素类型 - * @param fileName 文件名 - * @param isCreateHeader 是否创建列头 - * @param response - * @throws IOException - */ - public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName - , boolean isCreateHeader, HttpServletResponse response) throws IOException { - ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF); - exportParams.setCreateHeadRows(isCreateHeader); - defaultExport(list, pojoClass, fileName, response, exportParams); - - } - - /** - * 导出 - * - * @param list 数据列表 - * @param title 标题 - * @param sheetName sheet名称 - * @param pojoClass 元素类型 - * @param fileName 文件名 - * @param response - * @throws IOException - */ - public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName - , HttpServletResponse response) throws IOException { - defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF)); - } - - /** - * 导出 - * - * @param list 数据列表(元素是Map) - * @param fileName 文件名 - * @param response - * @throws IOException - */ - public static void exportExcel(List> list, String fileName, HttpServletResponse response) throws IOException { - defaultExport(list, fileName, response); - } - - private static void defaultExport(List list, Class pojoClass, String fileName - , HttpServletResponse response, ExportParams exportParams) throws IOException { - Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); - if (workbook != null) { - downLoadExcel(fileName, response, workbook); - } - } - - private static void defaultExport(List> list, String fileName, HttpServletResponse response) throws IOException { - Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.XSSF); - if (workbook != null) { - downLoadExcel(fileName, response, workbook); - } - } - - private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException { - response.setCharacterEncoding("UTF-8"); - response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); - response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); - workbook.write(response.getOutputStream()); - } - - public static List importExcel(String filePath, Integer titleRows, Integer headerRows, Class pojoClass) { - if (StringUtils.isBlank(filePath)) { - return Collections.emptyList(); - } - ImportParams params = new ImportParams(); - params.setTitleRows(titleRows); - params.setHeadRows(headerRows); - return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); - } - - public static List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass) throws Exception { - if (file == null) { - return Collections.emptyList(); - } - ImportParams params = new ImportParams(); - params.setTitleRows(titleRows); - params.setHeadRows(headerRows); - return ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); - } -} +package com.central.common.utils; + +import cn.afterturn.easypoi.excel.ExcelExportUtil; +import cn.afterturn.easypoi.excel.ExcelImportUtil; +import cn.afterturn.easypoi.excel.entity.ExportParams; +import cn.afterturn.easypoi.excel.entity.ImportParams; +import cn.afterturn.easypoi.excel.entity.enmus.ExcelType; +import org.apache.commons.lang3.StringUtils; +import org.apache.poi.ss.usermodel.Workbook; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.net.URLEncoder; +import java.util.Collections; +import java.util.List; +import java.util.Map; + +/** + * Excel工具类 + * + * @author zlt + * @date 2019/1/6 + */ +public class ExcelUtil { + private ExcelUtil() { + throw new IllegalStateException("Utility class"); + } + + /** + * 导出 + * + * @param list 数据列表 + * @param title 标题 + * @param sheetName sheet名称 + * @param pojoClass 元素类型 + * @param fileName 文件名 + * @param isCreateHeader 是否创建列头 + * @param response + * @throws IOException + */ + public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName + , boolean isCreateHeader, HttpServletResponse response) throws IOException { + ExportParams exportParams = new ExportParams(title, sheetName, ExcelType.XSSF); + exportParams.setCreateHeadRows(isCreateHeader); + defaultExport(list, pojoClass, fileName, response, exportParams); + + } + + /** + * 导出 + * + * @param list 数据列表 + * @param title 标题 + * @param sheetName sheet名称 + * @param pojoClass 元素类型 + * @param fileName 文件名 + * @param response + * @throws IOException + */ + public static void exportExcel(List list, String title, String sheetName, Class pojoClass, String fileName + , HttpServletResponse response) throws IOException { + defaultExport(list, pojoClass, fileName, response, new ExportParams(title, sheetName, ExcelType.XSSF)); + } + + /** + * 导出 + * + * @param list 数据列表(元素是Map) + * @param fileName 文件名 + * @param response + * @throws IOException + */ + public static void exportExcel(List> list, String fileName, HttpServletResponse response) throws IOException { + defaultExport(list, fileName, response); + } + + private static void defaultExport(List list, Class pojoClass, String fileName + , HttpServletResponse response, ExportParams exportParams) throws IOException { + Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, list); + if (workbook != null) { + downLoadExcel(fileName, response, workbook); + } + } + + private static void defaultExport(List> list, String fileName, HttpServletResponse response) throws IOException { + Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.XSSF); + if (workbook != null) { + downLoadExcel(fileName, response, workbook); + } + } + + private static void downLoadExcel(String fileName, HttpServletResponse response, Workbook workbook) throws IOException { + response.setCharacterEncoding("UTF-8"); + response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); + response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); + workbook.write(response.getOutputStream()); + } + + public static List importExcel(String filePath, Integer titleRows, Integer headerRows, Class pojoClass) { + if (StringUtils.isBlank(filePath)) { + return Collections.emptyList(); + } + ImportParams params = new ImportParams(); + params.setTitleRows(titleRows); + params.setHeadRows(headerRows); + return ExcelImportUtil.importExcel(new File(filePath), pojoClass, params); + } + + public static List importExcel(MultipartFile file, Integer titleRows, Integer headerRows, Class pojoClass) throws Exception { + if (file == null) { + return Collections.emptyList(); + } + ImportParams params = new ImportParams(); + params.setTitleRows(titleRows); + params.setHeadRows(headerRows); + return ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/IdGenerator.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/IdGenerator.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/IdGenerator.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/IdGenerator.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/ResponseUtil.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/ResponseUtil.java similarity index 62% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/ResponseUtil.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/ResponseUtil.java index e67e766f..39e7df9b 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/ResponseUtil.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/ResponseUtil.java @@ -1,65 +1,89 @@ -package com.central.common.utils; - -import com.central.common.model.Result; -import com.fasterxml.jackson.databind.ObjectMapper; -import org.springframework.http.MediaType; - -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.io.Writer; - -/** - * @author zlt - * @date 2018/12/20 - */ -public class ResponseUtil { - private ResponseUtil() { - throw new IllegalStateException("Utility class"); - } - /** - * 通过流写到前端 - * - * @param objectMapper 对象序列化 - * @param response - * @param msg 返回信息 - * @param httpStatus 返回状态码 - * @throws IOException - */ - public static void responseWriter(ObjectMapper objectMapper, HttpServletResponse response, String msg, int httpStatus) throws IOException { - Result result = Result.succeedWith(null, httpStatus, msg); - responseWrite(objectMapper, response, result); - } - - /** - * 通过流写到前端 - * @param objectMapper 对象序列化 - * @param response - * @param obj - */ - public static void responseSucceed(ObjectMapper objectMapper, HttpServletResponse response, Object obj) throws IOException { - Result result = Result.succeed(obj); - responseWrite(objectMapper, response, result); - } - - /** - * 通过流写到前端 - * @param objectMapper - * @param response - * @param msg - * @throws IOException - */ - public static void responseFailed(ObjectMapper objectMapper, HttpServletResponse response, String msg) throws IOException { - Result result = Result.failed(msg); - responseWrite(objectMapper, response, result); - } - - private static void responseWrite(ObjectMapper objectMapper, HttpServletResponse response, Result result) throws IOException { - response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); - try ( - Writer writer = response.getWriter() - ) { - writer.write(objectMapper.writeValueAsString(result)); - writer.flush(); - } - } -} +package com.central.common.utils; + +import com.alibaba.fastjson.JSONObject; +import com.central.common.model.Result; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.core.io.buffer.DataBuffer; +import org.springframework.core.io.buffer.DataBufferFactory; +import org.springframework.core.io.buffer.DataBufferUtils; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.server.reactive.ServerHttpResponse; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import javax.servlet.http.HttpServletResponse; +import java.io.IOException; +import java.io.Writer; +import java.nio.charset.Charset; + +/** + * @author zlt + * @date 2018/12/20 + */ +public class ResponseUtil { + private ResponseUtil() { + throw new IllegalStateException("Utility class"); + } + /** + * 通过流写到前端 + * + * @param objectMapper 对象序列化 + * @param response + * @param msg 返回信息 + * @param httpStatus 返回状态码 + * @throws IOException + */ + public static void responseWriter(ObjectMapper objectMapper, HttpServletResponse response, String msg, int httpStatus) throws IOException { + Result result = Result.succeedWith(null, httpStatus, msg); + responseWrite(objectMapper, response, result); + } + + /** + * 通过流写到前端 + * @param objectMapper 对象序列化 + * @param response + * @param obj + */ + public static void responseSucceed(ObjectMapper objectMapper, HttpServletResponse response, Object obj) throws IOException { + Result result = Result.succeed(obj); + responseWrite(objectMapper, response, result); + } + + /** + * 通过流写到前端 + * @param objectMapper + * @param response + * @param msg + * @throws IOException + */ + public static void responseFailed(ObjectMapper objectMapper, HttpServletResponse response, String msg) throws IOException { + Result result = Result.failed(msg); + responseWrite(objectMapper, response, result); + } + + private static void responseWrite(ObjectMapper objectMapper, HttpServletResponse response, Result result) throws IOException { + response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE); + try ( + Writer writer = response.getWriter() + ) { + writer.write(objectMapper.writeValueAsString(result)); + writer.flush(); + } + } + + /** + * webflux的response返回json对象 + */ + public static Mono responseWriter(ServerWebExchange exchange, int httpStatus, String msg) { + Result result = Result.succeedWith(null, httpStatus, msg); + ServerHttpResponse response = exchange.getResponse(); + response.setStatusCode(HttpStatus.valueOf(result.getResp_code())); + response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8); + DataBufferFactory dataBufferFactory = response.bufferFactory(); + DataBuffer buffer = dataBufferFactory.wrap(JSONObject.toJSONString(result).getBytes(Charset.defaultCharset())); + return response.writeWith(Mono.just(buffer)).doOnError((error) -> { + DataBufferUtils.release(buffer); + }); + } +} diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/RsaUtils.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/RsaUtils.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/RsaUtils.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/RsaUtils.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/Sequence.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/Sequence.java similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/Sequence.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/Sequence.java diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/SpringUtil.java b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/SpringUtil.java similarity index 96% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/SpringUtil.java rename to zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/SpringUtil.java index 03eaab3c..687b6bab 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/utils/SpringUtil.java +++ b/zlt-commons/zlt-common-core/src/main/java/com/central/common/utils/SpringUtil.java @@ -1,34 +1,34 @@ -package com.central.common.utils; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -/** - * spring获取bean工具类 - * - * @author 作者 owen E-mail: 624191343@qq.com - */ -@Component -public class SpringUtil implements ApplicationContextAware { - - private static ApplicationContext applicationContext = null; - - public static T getBean(Class cla) { - return applicationContext.getBean(cla); - } - - public static T getBean(String name, Class cal) { - return applicationContext.getBean(name, cal); - } - - public static String getProperty(String key) { - return applicationContext.getBean(Environment.class).getProperty(key); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - SpringUtil.applicationContext = applicationContext; - } -} +package com.central.common.utils; + +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +/** + * spring获取bean工具类 + * + * @author 作者 owen E-mail: 624191343@qq.com + */ +@Component +public class SpringUtil implements ApplicationContextAware { + + private static ApplicationContext applicationContext = null; + + public static T getBean(Class cla) { + return applicationContext.getBean(cla); + } + + public static T getBean(String name, Class cal) { + return applicationContext.getBean(name, cal); + } + + public static String getProperty(String key) { + return applicationContext.getBean(Environment.class).getProperty(key); + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + SpringUtil.applicationContext = applicationContext; + } +} diff --git a/zlt-commons/zlt-common-core/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-common-core/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..7c72414b --- /dev/null +++ b/zlt-commons/zlt-common-core/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.context.ApplicationContextInitializer=\ +com.central.common.config.BannerInitializer \ No newline at end of file diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/zltmp/logo.txt b/zlt-commons/zlt-common-core/src/main/resources/zltmp/logo.txt similarity index 100% rename from zlt-commons/zlt-common-spring-boot-starter/src/main/resources/zltmp/logo.txt rename to zlt-commons/zlt-common-core/src/main/resources/zltmp/logo.txt diff --git a/zlt-commons/zlt-common-spring-boot-starter/pom.xml b/zlt-commons/zlt-common-spring-boot-starter/pom.xml index 002978e4..ed1470eb 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-common-spring-boot-starter/pom.xml @@ -12,81 +12,13 @@ com.zlt - zlt-log-spring-boot-starter - - - org.springframework.boot - spring-boot-starter-aop - - - com.baomidou - mybatis-plus - true - - - org.apache.commons - commons-lang3 - - - org.springframework.social - spring-social-security - - - org.springframework.security.oauth - spring-security-oauth2 - true - - - com.fasterxml.jackson.core - jackson-annotations - - - cn.hutool - hutool-all - - - org.springframework.boot - spring-boot-starter-web - provided - - - org.springframework.cloud - spring-cloud-starter-openfeign - true - - - org.apache.poi - poi - - - org.apache.poi - poi-ooxml - - - - cn.afterturn - easypoi-base - - - com.google.guava - guava - - - - - com.fasterxml.jackson.core - jackson-databind + zlt-common-core - org.springframework.boot - spring-boot-configuration-processor + javax.servlet + javax.servlet-api true - - - com.nepxion - banner - \ No newline at end of file diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java index b279fe09..506faa24 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java +++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TenantFilter.java @@ -4,8 +4,10 @@ import cn.hutool.core.util.StrUtil; import com.central.common.constant.CommonConstant; import com.central.common.constant.SecurityConstants; import com.central.common.context.TenantContextHolder; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.web.filter.OncePerRequestFilter; +import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -18,6 +20,7 @@ import java.io.IOException; * @author zlt * @date 2019/9/15 */ +@ConditionalOnClass(Filter.class) public class TenantFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TraceFilter.java b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TraceFilter.java index 7b2781b0..d07fe343 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TraceFilter.java +++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/java/com/central/common/filter/TraceFilter.java @@ -4,9 +4,11 @@ import cn.hutool.core.util.StrUtil; import com.central.common.constant.CommonConstant; import com.central.log.properties.TraceProperties; import org.slf4j.MDC; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.web.filter.OncePerRequestFilter; import javax.annotation.Resource; +import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -19,6 +21,7 @@ import java.io.IOException; * @author zlt * @date 2019/9/15 */ +@ConditionalOnClass(Filter.class) public class TraceFilter extends OncePerRequestFilter { @Resource private TraceProperties traceProperties; diff --git a/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring.factories index 70270f22..a277125f 100644 --- a/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring.factories +++ b/zlt-commons/zlt-common-spring-boot-starter/src/main/resources/META-INF/spring.factories @@ -1,6 +1,3 @@ -org.springframework.context.ApplicationContextInitializer=\ -com.central.common.config.BannerInitializer - org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.central.common.filter.TenantFilter,\ com.central.common.filter.TraceFilter \ No newline at end of file diff --git a/zlt-commons/zlt-db-spring-boot-starter/pom.xml b/zlt-commons/zlt-db-spring-boot-starter/pom.xml index bc6195b4..5107368f 100644 --- a/zlt-commons/zlt-db-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-db-spring-boot-starter/pom.xml @@ -14,7 +14,7 @@ com.zlt - zlt-common-spring-boot-starter + zlt-common-core diff --git a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml index a6c64989..bec19206 100644 --- a/zlt-commons/zlt-redis-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-redis-spring-boot-starter/pom.xml @@ -14,7 +14,7 @@ com.zlt - zlt-common-spring-boot-starter + zlt-common-core org.springframework.boot diff --git a/zlt-commons/zlt-ribbon-spring-boot-starter/pom.xml b/zlt-commons/zlt-ribbon-spring-boot-starter/pom.xml index e7981903..30fc594f 100644 --- a/zlt-commons/zlt-ribbon-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-ribbon-spring-boot-starter/pom.xml @@ -14,7 +14,7 @@ com.zlt - zlt-common-spring-boot-starter + zlt-common-core org.springframework.cloud @@ -36,6 +36,7 @@ javax.servlet javax.servlet-api + true diff --git a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/LbIsolationAutoConfigure.java b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/LbIsolationAutoConfigure.java new file mode 100644 index 00000000..70bb8e21 --- /dev/null +++ b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/LbIsolationAutoConfigure.java @@ -0,0 +1,18 @@ +package com.central.common.ribbon; + +import com.central.common.constant.ConfigConstants; +import com.central.common.ribbon.config.RuleConfigure; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.netflix.ribbon.RibbonClients; + +/** + * Ribbon扩展配置类 + * + * @author zlt + * @date 2018/11/17 9:24 + */ +@ConditionalOnProperty(value = ConfigConstants.CONFIG_RIBBON_ISOLATION_ENABLED, havingValue = "true") +@RibbonClients(defaultConfiguration = {RuleConfigure.class}) +public class LbIsolationAutoConfigure { + +} diff --git a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/RibbonAutoConfigure.java b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/RibbonAutoConfigure.java index 68e2b1ce..df4983c8 100644 --- a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/RibbonAutoConfigure.java +++ b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/RibbonAutoConfigure.java @@ -1,14 +1,9 @@ package com.central.common.ribbon; -import com.central.common.constant.ConfigConstants; import com.central.common.ribbon.config.RestTemplateProperties; -import com.central.common.ribbon.config.RuleConfigure; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.cloud.netflix.ribbon.DefaultPropertiesFactory; -import org.springframework.cloud.netflix.ribbon.RibbonClients; import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; /** * Ribbon扩展配置类 @@ -22,10 +17,4 @@ public class RibbonAutoConfigure { public DefaultPropertiesFactory defaultPropertiesFactory() { return new DefaultPropertiesFactory(); } - - @Configuration - @ConditionalOnProperty(value = ConfigConstants.CONFIG_RIBBON_ISOLATION_ENABLED, havingValue = "true") - @RibbonClients(defaultConfiguration = {RuleConfigure.class}) - public class LbIsolationConfig { - } } diff --git a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/config/FeignInterceptorConfig.java b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/config/FeignInterceptorConfig.java index 02d839a8..4e7f5918 100644 --- a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/config/FeignInterceptorConfig.java +++ b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/config/FeignInterceptorConfig.java @@ -87,7 +87,7 @@ public class FeignInterceptorConfig { Enumeration headers = request.getHeaders(CommonConstant.TOKEN_HEADER); while (headers.hasMoreElements()) { String value = headers.nextElement(); - if ((value.toLowerCase().startsWith(CommonConstant.BEARER_TYPE.toLowerCase()))) { + if ((value.toLowerCase().startsWith(CommonConstant.BEARER_TYPE))) { String authHeaderValue = value.substring(CommonConstant.BEARER_TYPE.length()).trim(); int commaIndex = authHeaderValue.indexOf(','); if (commaIndex > 0) { diff --git a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/filter/LbIsolationFilter.java b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/filter/LbIsolationFilter.java index fdd33fdf..22c5e4ff 100644 --- a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/filter/LbIsolationFilter.java +++ b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/filter/LbIsolationFilter.java @@ -5,8 +5,12 @@ import com.central.common.constant.CommonConstant; import com.central.common.constant.ConfigConstants; import com.central.common.context.LbIsolationContextHolder; import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass; import org.springframework.web.filter.OncePerRequestFilter; +import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; @@ -19,6 +23,7 @@ import java.io.IOException; * @author zlt * @date 2019/9/15 */ +@ConditionalOnClass(Filter.class) public class LbIsolationFilter extends OncePerRequestFilter { @Value("${" + ConfigConstants.CONFIG_RIBBON_ISOLATION_ENABLED + ":false}") private boolean enableIsolation; diff --git a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/rule/CustomIsolationRule.java b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/rule/CustomIsolationRule.java index 5f17057b..22ae038a 100644 --- a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/rule/CustomIsolationRule.java +++ b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/java/com/central/common/ribbon/rule/CustomIsolationRule.java @@ -18,6 +18,7 @@ import java.util.stream.Collectors; * @date 2019/9/3 */ public class CustomIsolationRule extends RoundRobinRule { + private final static String KEY_DEFAULT = "default"; /** * 优先根据版本号取实例 */ @@ -26,7 +27,13 @@ public class CustomIsolationRule extends RoundRobinRule { if (lb == null) { return null; } - String version = LbIsolationContextHolder.getVersion(); + String version; + if (key != null && !KEY_DEFAULT.equals(key)) { + version = key.toString(); + } else { + version = LbIsolationContextHolder.getVersion(); + } + List targetList = null; List upList = lb.getReachableServers(); if (StrUtil.isNotEmpty(version)) { diff --git a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/resources/META-INF/spring.factories b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/resources/META-INF/spring.factories index d198a8d6..16f3fb91 100644 --- a/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/resources/META-INF/spring.factories +++ b/zlt-commons/zlt-ribbon-spring-boot-starter/src/main/resources/META-INF/spring.factories @@ -2,4 +2,5 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.central.common.ribbon.RibbonAutoConfigure,\ com.central.common.ribbon.FeignAutoConfigure,\ com.central.common.ribbon.RestTemplateAutoConfigure,\ -com.central.common.ribbon.filter.LbIsolationFilter +com.central.common.ribbon.filter.LbIsolationFilter,\ +com.central.common.ribbon.LbIsolationAutoConfigure diff --git a/zlt-commons/zlt-sentinel-spring-boot-starter/pom.xml b/zlt-commons/zlt-sentinel-spring-boot-starter/pom.xml index 364a0524..43c6c315 100644 --- a/zlt-commons/zlt-sentinel-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-sentinel-spring-boot-starter/pom.xml @@ -14,7 +14,7 @@ com.zlt - zlt-common-spring-boot-starter + zlt-common-core com.alibaba.cloud diff --git a/zlt-commons/zlt-swagger2-spring-boot-starter/pom.xml b/zlt-commons/zlt-swagger2-spring-boot-starter/pom.xml index 9e725410..d4b23084 100644 --- a/zlt-commons/zlt-swagger2-spring-boot-starter/pom.xml +++ b/zlt-commons/zlt-swagger2-spring-boot-starter/pom.xml @@ -14,7 +14,7 @@ org.springframework.boot - spring-boot-starter-web + spring-boot-starter io.springfox diff --git a/zlt-config/src/main/resources/application-dev.properties b/zlt-config/src/main/resources/application-dev.properties index 2fafecfb..574760ef 100644 --- a/zlt-config/src/main/resources/application-dev.properties +++ b/zlt-config/src/main/resources/application-dev.properties @@ -11,7 +11,7 @@ spring.redis.timeout=5000 ##### elasticsearch配置 zlt.elasticsearch.cluster-name=my-es -zlt.elasticsearch.cluster-nodes=119.3.105.180 +zlt.elasticsearch.cluster-nodes=192.168.28.130 ##### sentinel配置 zlt.sentinel.dashboard=192.168.28.130:6999 diff --git a/zlt-gateway/pom.xml b/zlt-gateway/pom.xml index 9862f206..ecbb181e 100644 --- a/zlt-gateway/pom.xml +++ b/zlt-gateway/pom.xml @@ -9,6 +9,9 @@ zlt-gateway pom + zuul-gateway + + sc-gateway \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/pom.xml b/zlt-gateway/sc-gateway/pom.xml new file mode 100644 index 00000000..66960287 --- /dev/null +++ b/zlt-gateway/sc-gateway/pom.xml @@ -0,0 +1,134 @@ + + 4.0.0 + + com.zlt + zlt-gateway + 2.7.2 + + sc-gateway + spring cloud gateway网关 + + + + com.zlt + zlt-config + + + com.zlt + zlt-ribbon-spring-boot-starter + + + com.zlt + zlt-sentinel-spring-boot-starter + + + + com.zlt + zlt-auth-client-spring-boot-starter + + + org.springframework.cloud + spring-cloud-starter-gateway + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + io.springfox + springfox-swagger2 + + + io.springfox + springfox-swagger-ui + + + org.springframework.cloud + spring-cloud-starter-oauth2 + + + com.zlt + zlt-redis-spring-boot-starter + + + org.springframework.security + spring-security-oauth2-resource-server + + + com.baomidou + mybatis-plus-extension + + + io.micrometer + micrometer-registry-prometheus + + + eu.bitwalker + UserAgentUtils + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + repackage + + + + + + com.spotify + docker-maven-plugin + + ${docker.image.prefix}/${project.artifactId} + + ${project.version} + latest + + true + ${docker.baseImage} + ${docker.volumes} + + ${docker.java.opts} + + ["sh","-c","java $JAVA_OPTS ${docker.java.security.egd} -jar /${project.build.finalName}.jar"] + + + / + ${project.build.directory} + ${project.build.finalName}.jar + + + + + + ${project.artifactId} + + \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/SCGatewayApp.java b/zlt-gateway/sc-gateway/src/main/java/com/central/SCGatewayApp.java new file mode 100644 index 00000000..5aa7e856 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/SCGatewayApp.java @@ -0,0 +1,22 @@ +package com.central; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.openfeign.EnableFeignClients; + +/** + * @author zlt + * @date 2019/10/5 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@EnableFeignClients +@EnableDiscoveryClient +@SpringBootApplication +public class SCGatewayApp { + public static void main(String[] args) { + SpringApplication.run(SCGatewayApp.class, args); + } +} \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomAuthenticationManager.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomAuthenticationManager.java new file mode 100644 index 00000000..b3f30a07 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/CustomAuthenticationManager.java @@ -0,0 +1,49 @@ +package com.central.gateway.auth; + +import org.springframework.security.authentication.ReactiveAuthenticationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.common.OAuth2AccessToken; +import org.springframework.security.oauth2.common.exceptions.InvalidTokenException; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken; +import reactor.core.publisher.Mono; + +/** + * @author zlt + * @date 2019/10/6 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +public class CustomAuthenticationManager implements ReactiveAuthenticationManager { + private TokenStore tokenStore; + + public CustomAuthenticationManager(TokenStore tokenStore) { + this.tokenStore = tokenStore; + } + + @Override + public Mono authenticate(Authentication authentication) { + return Mono.justOrEmpty(authentication) + .filter(a -> a instanceof BearerTokenAuthenticationToken) + .cast(BearerTokenAuthenticationToken.class) + .map(BearerTokenAuthenticationToken::getToken) + .flatMap((accessTokenValue -> { + OAuth2AccessToken accessToken = tokenStore.readAccessToken(accessTokenValue); + if (accessToken == null) { + return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue)); + } else if (accessToken.isExpired()) { + tokenStore.removeAccessToken(accessToken); + return Mono.error(new InvalidTokenException("Access token expired: " + accessTokenValue)); + } + + OAuth2Authentication result = tokenStore.readAuthentication(accessToken); + if (result == null) { + return Mono.error(new InvalidTokenException("Invalid access token: " + accessTokenValue)); + } + return Mono.just(result); + })) + .cast(Authentication.class); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAccessDeniedHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAccessDeniedHandler.java new file mode 100644 index 00000000..c2ba9ce5 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAccessDeniedHandler.java @@ -0,0 +1,26 @@ +package com.central.gateway.auth; + +import com.central.common.utils.ResponseUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +/** + * 403拒绝访问异常处理,转换为JSON + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Slf4j +public class JsonAccessDeniedHandler implements ServerAccessDeniedHandler { + @Override + public Mono handle(ServerWebExchange exchange, AccessDeniedException e) { + return ResponseUtil.responseWriter(exchange, HttpStatus.FORBIDDEN.value(), e.getMessage()); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAuthenticationEntryPoint.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAuthenticationEntryPoint.java new file mode 100644 index 00000000..05fac976 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/JsonAuthenticationEntryPoint.java @@ -0,0 +1,26 @@ +package com.central.gateway.auth; + +import com.central.common.utils.ResponseUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.HttpStatus; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.server.ServerAuthenticationEntryPoint; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +/** + * 401未授权异常处理,转换为JSON + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Slf4j +public class JsonAuthenticationEntryPoint implements ServerAuthenticationEntryPoint { + @Override + public Mono commence(ServerWebExchange exchange, AuthenticationException e) { + return ResponseUtil.responseWriter(exchange, HttpStatus.UNAUTHORIZED.value(), e.getMessage()); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java new file mode 100644 index 00000000..162829b5 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/Oauth2AuthSuccessHandler.java @@ -0,0 +1,45 @@ +package com.central.gateway.auth; + +import cn.hutool.core.collection.CollectionUtil; +import com.central.common.constant.SecurityConstants; +import com.central.common.model.SysUser; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.provider.OAuth2Authentication; +import org.springframework.security.web.server.WebFilterExchange; +import org.springframework.security.web.server.authentication.ServerAuthenticationSuccessHandler; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +/** + * 认证成功处理类 + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +public class Oauth2AuthSuccessHandler implements ServerAuthenticationSuccessHandler { + @Override + public Mono onAuthenticationSuccess(WebFilterExchange webFilterExchange, Authentication authentication) { + SysUser user = (SysUser)authentication.getPrincipal(); + Long userId = user.getId(); + String username = user.getUsername(); + OAuth2Authentication oauth2Authentication = (OAuth2Authentication)authentication; + String clientId = oauth2Authentication.getOAuth2Request().getClientId(); + + ServerWebExchange exchange = webFilterExchange.getExchange(); + ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate() + .headers(h -> { + h.add(SecurityConstants.USER_ID_HEADER, String.valueOf(userId)); + h.add(SecurityConstants.USER_HEADER, username); + h.add(SecurityConstants.TENANT_HEADER, clientId); + h.add(SecurityConstants.ROLE_HEADER, CollectionUtil.join(authentication.getAuthorities(), ",")); + }) + .build(); + + ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build(); + return webFilterExchange.getChain().filter(build); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java new file mode 100644 index 00000000..da4619c2 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/auth/PermissionAuthManager.java @@ -0,0 +1,48 @@ +package com.central.gateway.auth; + +import com.central.common.model.SysMenu; +import com.central.gateway.feign.MenuService; +import com.central.oauth2.common.service.impl.DefaultPermissionServiceImpl; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.security.authorization.AuthorizationDecision; +import org.springframework.security.authorization.ReactiveAuthorizationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.web.server.authorization.AuthorizationContext; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import javax.annotation.Resource; +import java.util.List; + +/** + * url权限认证 + * + * @author zlt + * @date 2019/10/6 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Slf4j +@Component +public class PermissionAuthManager extends DefaultPermissionServiceImpl implements ReactiveAuthorizationManager { + @Resource + private MenuService menuService; + + @Override + public Mono check(Mono authentication, AuthorizationContext authorizationContext) { + return authentication.map(auth -> { + ServerWebExchange exchange = authorizationContext.getExchange(); + ServerHttpRequest request = exchange.getRequest(); + boolean isPermission = super.hasPermission(auth, request.getMethodValue(), request.getURI().getPath()); + return new AuthorizationDecision(isPermission); + }).defaultIfEmpty(new AuthorizationDecision(false)); + } + + @Override + public List findMenuByRoleCodes(String roleCodes) { + return menuService.findByRoleCodes(roleCodes); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java new file mode 100644 index 00000000..ed033cdc --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/CorsConfig.java @@ -0,0 +1,39 @@ +package com.central.gateway.config; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.reactive.CorsWebFilter; +import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; +import org.springframework.web.util.pattern.PathPatternParser; + +/** + * 跨域配置 + * + * @author zlt + * @date 2019/10/5 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Configuration +public class CorsConfig { + private static final String ALL = "*"; + + @Bean + public CorsWebFilter corsFilter() { + CorsConfiguration config = new CorsConfiguration(); + // cookie跨域 + config.setAllowCredentials(Boolean.TRUE); + config.addAllowedMethod(ALL); + config.addAllowedOrigin(ALL); + config.addAllowedHeader(ALL); + // 配置前端js允许访问的自定义响应头 + config.addExposedHeader("setToken"); + + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); + source.registerCorsConfiguration("/**", config); + + return new CorsWebFilter(source); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/DynamicRouteConfig.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/DynamicRouteConfig.java new file mode 100644 index 00000000..66330d95 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/DynamicRouteConfig.java @@ -0,0 +1,40 @@ +package com.central.gateway.config; + +import com.alibaba.cloud.nacos.NacosConfigProperties; +import com.central.gateway.route.NacosRouteDefinitionRepository; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * 动态路由配置 + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Configuration +@ConditionalOnProperty(prefix = "zlt.gateway.dynamicRoute", name = "enabled", havingValue = "true") +public class DynamicRouteConfig { + @Autowired + private ApplicationEventPublisher publisher; + + /** + * Nacos实现方式 + */ + @Configuration + @ConditionalOnProperty(prefix = "zlt.gateway.dynamicRoute", name = "dataType", havingValue = "nacos", matchIfMissing = true) + public class NacosDynRoute { + @Autowired + private NacosConfigProperties nacosConfigProperties; + + @Bean + public NacosRouteDefinitionRepository nacosRouteDefinitionRepository() { + return new NacosRouteDefinitionRepository(publisher, nacosConfigProperties); + } + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java new file mode 100644 index 00000000..a6792804 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java @@ -0,0 +1,77 @@ +package com.central.gateway.config; + +import com.central.gateway.auth.*; +import com.central.oauth2.common.properties.SecurityProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.ReactiveAuthenticationManager; +import org.springframework.security.config.web.server.SecurityWebFiltersOrder; +import org.springframework.security.config.web.server.ServerHttpSecurity; +import org.springframework.security.oauth2.provider.token.TokenStore; +import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter; +import org.springframework.security.web.server.SecurityWebFilterChain; +import org.springframework.security.web.server.authentication.AuthenticationWebFilter; +import org.springframework.security.web.server.authentication.ServerAuthenticationEntryPointFailureHandler; + +/** + * 资源服务器配置 + * + * @author zlt + * @date 2019/10/5 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Configuration +public class ResourceServerConfiguration { + @Autowired + private SecurityProperties securityProperties; + + @Autowired + private TokenStore tokenStore; + + @Autowired + private PermissionAuthManager permissionAuthManager; + + @Bean + SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) { + //认证处理器 + ReactiveAuthenticationManager customAuthenticationManager = new CustomAuthenticationManager(tokenStore); + JsonAuthenticationEntryPoint entryPoint = new JsonAuthenticationEntryPoint(); + //token转换器 + ServerBearerTokenAuthenticationConverter tokenAuthenticationConverter = new ServerBearerTokenAuthenticationConverter(); + tokenAuthenticationConverter.setAllowUriQueryParameter(true); + //oauth2认证过滤器 + AuthenticationWebFilter oauth2Filter = new AuthenticationWebFilter(customAuthenticationManager); + oauth2Filter.setServerAuthenticationConverter(tokenAuthenticationConverter); + oauth2Filter.setAuthenticationFailureHandler(new ServerAuthenticationEntryPointFailureHandler(entryPoint)); + oauth2Filter.setAuthenticationSuccessHandler(new Oauth2AuthSuccessHandler()); + http.addFilterAt(oauth2Filter, SecurityWebFiltersOrder.AUTHENTICATION); + + ServerHttpSecurity.AuthorizeExchangeSpec authorizeExchange = http.authorizeExchange(); + if (securityProperties.getAuth().getHttpUrls().length > 0) { + authorizeExchange.pathMatchers(securityProperties.getAuth().getHttpUrls()).authenticated(); + } + if (securityProperties.getIgnore().getUrls().length > 0) { + authorizeExchange.pathMatchers(securityProperties.getIgnore().getUrls()).permitAll(); + } + authorizeExchange + .pathMatchers(HttpMethod.OPTIONS).permitAll() + .anyExchange() + .access(permissionAuthManager) + .and() + .exceptionHandling() + .accessDeniedHandler(new JsonAccessDeniedHandler()) + .authenticationEntryPoint(entryPoint) + .and() + .headers() + .frameOptions() + .disable() + .and() + .httpBasic().disable() + .csrf().disable(); + return http.build(); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/MenuService.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/MenuService.java new file mode 100644 index 00000000..59781589 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/MenuService.java @@ -0,0 +1,23 @@ +package com.central.gateway.feign; + +import com.central.common.constant.ServiceNameConstants; +import com.central.common.model.SysMenu; +import com.central.gateway.feign.fallback.MenuServiceFallbackFactory; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +import java.util.List; + +/** + * @author zlt + */ +@FeignClient(name = ServiceNameConstants.USER_SERVICE, fallbackFactory = MenuServiceFallbackFactory.class, decode404 = true) +public interface MenuService { + /** + * 角色菜单列表 + * @param roleCodes + */ + @GetMapping(value = "/menus/{roleCodes}") + List findByRoleCodes(@PathVariable("roleCodes") String roleCodes); +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/fallback/MenuServiceFallbackFactory.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/fallback/MenuServiceFallbackFactory.java new file mode 100644 index 00000000..90aaa50d --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/feign/fallback/MenuServiceFallbackFactory.java @@ -0,0 +1,25 @@ +package com.central.gateway.feign.fallback; + +import cn.hutool.core.collection.CollectionUtil; +import com.central.gateway.feign.MenuService; +import feign.hystrix.FallbackFactory; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * menuService降级工场 + * + * @author zlt + * @date 2019/1/18 + */ +@Slf4j +@Component +public class MenuServiceFallbackFactory implements FallbackFactory { + @Override + public MenuService create(Throwable throwable) { + return roleIds -> { + log.error("调用findByRoleCodes异常:{}", roleIds, throwable); + return CollectionUtil.newArrayList(); + }; + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/LbIsolationFilter.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/LbIsolationFilter.java new file mode 100644 index 00000000..41c201c4 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/LbIsolationFilter.java @@ -0,0 +1,47 @@ +package com.central.gateway.filter; + +import cn.hutool.core.util.StrUtil; +import com.central.common.constant.CommonConstant; +import com.central.common.constant.ConfigConstants; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.loadbalancer.LoadBalancerClient; +import org.springframework.cloud.gateway.config.LoadBalancerProperties; +import org.springframework.cloud.gateway.filter.LoadBalancerClientFilter; +import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; + +import java.net.URI; + +import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; + +/** + * 传递负载均衡隔离值 + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Component +@ConditionalOnProperty(name = ConfigConstants.CONFIG_RIBBON_ISOLATION_ENABLED, havingValue = "true") +public class LbIsolationFilter extends LoadBalancerClientFilter { + public LbIsolationFilter(LoadBalancerClient loadBalancer, LoadBalancerProperties properties) { + super(loadBalancer, properties); + } + + @Override + protected ServiceInstance choose(ServerWebExchange exchange) { + String vresion = exchange.getRequest().getHeaders().getFirst(CommonConstant.Z_L_T_VERSION); + if (StrUtil.isNotEmpty(vresion)) { + if (this.loadBalancer instanceof RibbonLoadBalancerClient) { + RibbonLoadBalancerClient client = (RibbonLoadBalancerClient) this.loadBalancer; + String serviceId = ((URI) exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR)).getHost(); + return client.choose(serviceId, vresion); + } + } + return super.choose(exchange); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java new file mode 100644 index 00000000..86cb7cae --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/RequestStatisticsFilter.java @@ -0,0 +1,45 @@ +package com.central.gateway.filter; + +import eu.bitwalker.useragentutils.UserAgent; +import com.central.gateway.utils.ReactiveAddrUtil; +import com.central.log.monitor.PointUtil; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.Ordered; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +import java.util.Map; + +/** + * 请求统计分析埋点过滤器 + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Component +public class RequestStatisticsFilter implements GlobalFilter, Ordered { + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + ServerHttpRequest request = exchange.getRequest(); + Map headers = request.getHeaders().toSingleValueMap(); + UserAgent userAgent = UserAgent.parseUserAgentString(headers.get("User-Agent")); + //埋点 + PointUtil.debug("1", "request-statistics", + "ip=" + ReactiveAddrUtil.getRemoteAddr(request) + + "&browser=" + userAgent.getBrowser() + + "&operatingSystem=" + userAgent.getOperatingSystem()); + + return chain.filter(exchange); + } + + @Override + public int getOrder() { + return 0; + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java new file mode 100644 index 00000000..e8048cfc --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/filter/TraceFilter.java @@ -0,0 +1,52 @@ +package com.central.gateway.filter; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.util.IdUtil; +import com.central.common.constant.CommonConstant; +import com.central.common.constant.SecurityConstants; +import com.central.log.properties.TraceProperties; +import org.slf4j.MDC; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.gateway.filter.GatewayFilterChain; +import org.springframework.cloud.gateway.filter.GlobalFilter; +import org.springframework.core.Ordered; +import org.springframework.http.server.reactive.ServerHttpRequest; +import org.springframework.stereotype.Component; +import org.springframework.web.server.ServerWebExchange; +import reactor.core.publisher.Mono; + +/** + * 生成日志链路追踪id,并传入header中 + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Component +public class TraceFilter implements GlobalFilter, Ordered { + @Autowired + private TraceProperties traceProperties; + + @Override + public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + if (traceProperties.getEnable()) { + //链路追踪id + String traceId = IdUtil.fastSimpleUUID(); + MDC.put(CommonConstant.LOG_TRACE_ID, traceId); + ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate() + .headers(h -> h.add(CommonConstant.TRACE_ID_HEADER, traceId)) + .build(); + + ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build(); + return chain.filter(build); + } + return chain.filter(exchange); + } + + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java new file mode 100644 index 00000000..1d3b536b --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/route/NacosRouteDefinitionRepository.java @@ -0,0 +1,94 @@ +package com.central.gateway.route; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.StrUtil; +import com.alibaba.cloud.nacos.NacosConfigProperties; +import com.alibaba.fastjson.JSONObject; +import com.alibaba.nacos.api.config.listener.Listener; +import com.alibaba.nacos.api.exception.NacosException; +import lombok.extern.slf4j.Slf4j; +import org.springframework.cloud.gateway.event.RefreshRoutesEvent; +import org.springframework.cloud.gateway.route.RouteDefinition; +import org.springframework.cloud.gateway.route.RouteDefinitionRepository; +import org.springframework.context.ApplicationEventPublisher; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executor; + +/** + * nacos路由数据源 + * + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Slf4j +public class NacosRouteDefinitionRepository implements RouteDefinitionRepository { + private static final String SCG_DATA_ID = "scg-routes"; + private static final String SCG_GROUP_ID = "SCG_GATEWAY"; + + private ApplicationEventPublisher publisher; + + private NacosConfigProperties nacosConfigProperties; + + public NacosRouteDefinitionRepository(ApplicationEventPublisher publisher, NacosConfigProperties nacosConfigProperties) { + this.publisher = publisher; + this.nacosConfigProperties = nacosConfigProperties; + addListener(); + } + + @Override + public Flux getRouteDefinitions() { + try { + String content = nacosConfigProperties.configServiceInstance().getConfig(SCG_DATA_ID, SCG_GROUP_ID,5000); + List routeDefinitions = getListByStr(content); + return Flux.fromIterable(routeDefinitions); + } catch (NacosException e) { + log.error("getRouteDefinitions by nacos error", e); + } + return Flux.fromIterable(CollUtil.newArrayList()); + } + + /** + * 添加Nacos监听 + */ + private void addListener() { + try { + nacosConfigProperties.configServiceInstance().addListener(SCG_DATA_ID, SCG_GROUP_ID, new Listener() { + @Override + public Executor getExecutor() { + return null; + } + + @Override + public void receiveConfigInfo(String configInfo) { + publisher.publishEvent(new RefreshRoutesEvent(this)); + } + }); + } catch (NacosException e) { + log.error("nacos-addListener-error", e); + } + } + + @Override + public Mono save(Mono route) { + return null; + } + + @Override + public Mono delete(Mono routeId) { + return null; + } + + private List getListByStr(String content) { + if (StrUtil.isNotEmpty(content)) { + return JSONObject.parseArray(content, RouteDefinition.class); + } + return new ArrayList<>(0); + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerAggProperties.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerAggProperties.java new file mode 100644 index 00000000..1e4c1084 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerAggProperties.java @@ -0,0 +1,62 @@ +package com.central.gateway.swagger; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.context.config.annotation.RefreshScope; + +import java.util.HashSet; +import java.util.Set; + +/** + * swagger聚合配置 + * + * @author zlt + * @date 2019/10/5 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Setter +@Getter +@ConfigurationProperties("zlt.swagger-agg") +@RefreshScope +public class SwaggerAggProperties { + /** + * Swagger返回JSON文档的接口路径(全局配置) + */ + private String apiDocsPath = "/v2/api-docs"; + + /** + * Swagger文档版本(全局配置) + */ + private String swaggerVersion = "2.0"; + + /** + * 自动生成文档的路由名称,设置了generateRoutes之后,ignoreRoutes不生效 + */ + private Set generateRoutes = new HashSet<>(); + + /** + * 不自动生成文档的路由名称,设置了generateRoutes之后,本配置不生效 + */ + private Set ignoreRoutes = new HashSet<>(); + + /** + * 是否显示该路由 + */ + public boolean isShow(String route) { + int generateRoutesSize = generateRoutes.size(); + int ignoreRoutesSize = ignoreRoutes.size(); + + if(generateRoutesSize > 0 && !generateRoutes.contains(route)) { + return false; + } + + if(ignoreRoutesSize > 0 && ignoreRoutes.contains(route)) { + return false; + } + + return true; + } +} diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerHandler.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerHandler.java new file mode 100644 index 00000000..34cec884 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerHandler.java @@ -0,0 +1,57 @@ +package com.central.gateway.swagger; + +import org.springframework.beans.factory.annotation.Autowired; + +import java.util.Optional; + +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import reactor.core.publisher.Mono; +import springfox.documentation.swagger.web.SecurityConfiguration; +import springfox.documentation.swagger.web.SecurityConfigurationBuilder; +import springfox.documentation.swagger.web.SwaggerResourcesProvider; +import springfox.documentation.swagger.web.UiConfiguration; +import springfox.documentation.swagger.web.UiConfigurationBuilder; + +/** + * @author zlt + * @date 2019/10/5 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@RestController +@RequestMapping("/swagger-resources" ) +public class SwaggerHandler { + private final SwaggerResourcesProvider swaggerResources; + @Autowired(required = false) + private SecurityConfiguration securityConfiguration; + @Autowired(required = false) + private UiConfiguration uiConfiguration; + + @Autowired + public SwaggerHandler(SwaggerResourcesProvider swaggerResources) { + this.swaggerResources = swaggerResources; + } + + @GetMapping("/configuration/security" ) + public Mono> securityConfiguration() { + return Mono.just(new ResponseEntity<>( + Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK)); + } + + @GetMapping("/configuration/ui" ) + public Mono> uiConfiguration() { + return Mono.just(new ResponseEntity<>( + Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK)); + } + + @GetMapping + public Mono swaggerResources() { + return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK))); + } +} \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerProvider.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerProvider.java new file mode 100644 index 00000000..04acef57 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/swagger/SwaggerProvider.java @@ -0,0 +1,73 @@ +package com.central.gateway.swagger; + +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.cloud.gateway.config.GatewayProperties; +import org.springframework.cloud.gateway.route.RouteLocator; +import org.springframework.cloud.gateway.support.NameUtils; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; +import springfox.documentation.swagger.web.SwaggerResource; +import springfox.documentation.swagger.web.SwaggerResourcesProvider; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * 跨域配置 + * + * @author zlt + * @date 2019/10/5 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Component +@EnableConfigurationProperties(SwaggerAggProperties.class) +@Primary +public class SwaggerProvider implements SwaggerResourcesProvider { + private final RouteLocator routeLocator; + private final GatewayProperties gatewayProperties; + + @Resource + private SwaggerAggProperties swaggerAggProperties; + + public SwaggerProvider(RouteLocator routeLocator, GatewayProperties gatewayProperties) { + this.routeLocator = routeLocator; + this.gatewayProperties = gatewayProperties; + } + + @Override + public List get() { + List resources = new ArrayList<>(); + Set routes = new HashSet<>(); + //取出Spring Cloud Gateway中的route + routeLocator.getRoutes().subscribe(route -> routes.add(route.getId())); + //结合application.yml中的路由配置,只获取有效的route节点 + gatewayProperties.getRoutes().stream().filter( + routeDefinition -> ( + routes.contains(routeDefinition.getId()) && swaggerAggProperties.isShow(routeDefinition.getId()) + ) + ).forEach(routeDefinition -> routeDefinition.getPredicates().stream() + .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName())) + .forEach(predicateDefinition -> resources.add( + swaggerResource( + routeDefinition.getId(), + predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0").replace("/**", swaggerAggProperties.getApiDocsPath()) + ) + ) + ) + ); + return resources; + } + + private SwaggerResource swaggerResource(String name, String location) { + SwaggerResource swaggerResource = new SwaggerResource(); + swaggerResource.setName(name); + swaggerResource.setLocation(location); + swaggerResource.setSwaggerVersion(swaggerAggProperties.getSwaggerVersion()); + return swaggerResource; + } +} \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java new file mode 100644 index 00000000..ca11fd96 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/java/com/central/gateway/utils/ReactiveAddrUtil.java @@ -0,0 +1,76 @@ +package com.central.gateway.utils; + +import cn.hutool.core.util.StrUtil; +import lombok.extern.slf4j.Slf4j; +import org.springframework.http.server.reactive.ServerHttpRequest; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.Map; + +/** + * @author zlt + * @date 2019/10/7 + *

+ * Blog: https://blog.csdn.net/zlt2000 + * Github: https://github.com/zlt2000 + */ +@Slf4j +public class ReactiveAddrUtil { + private final static String UNKNOWN_STR = "unknown"; + /** + * 获取客户端IP地址 + */ + public static String getRemoteAddr(ServerHttpRequest request) { + Map headers = request.getHeaders().toSingleValueMap(); + String ip = headers.get("X-Forwarded-For"); + if (isEmptyIP(ip)) { + ip = headers.get("Proxy-Client-IP"); + if (isEmptyIP(ip)) { + ip = headers.get("WL-Proxy-Client-IP"); + if (isEmptyIP(ip)) { + ip = headers.get("HTTP_CLIENT_IP"); + if (isEmptyIP(ip)) { + ip = headers.get("HTTP_X_FORWARDED_FOR"); + if (isEmptyIP(ip)) { + ip = request.getRemoteAddress().getAddress().getHostAddress(); + if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip)) { + // 根据网卡取本机配置的IP + ip = getLocalAddr(); + } + } + } + } + } + } else if (ip.length() > 15) { + String[] ips = ip.split(","); + for (int index = 0; index < ips.length; index++) { + String strIp = ips[index]; + if (!isEmptyIP(ip)) { + ip = strIp; + break; + } + } + } + return ip; + } + + private static boolean isEmptyIP(String ip) { + if (StrUtil.isEmpty(ip) || UNKNOWN_STR.equalsIgnoreCase(ip)) { + return true; + } + return false; + } + + /** + * 获取本机的IP地址 + */ + public static String getLocalAddr() { + try { + return InetAddress.getLocalHost().getHostAddress(); + } catch (UnknownHostException e) { + log.error("InetAddress.getLocalHost()-error", e); + } + return ""; + } +} diff --git a/zlt-gateway/sc-gateway/src/main/resources/application.yml b/zlt-gateway/sc-gateway/src/main/resources/application.yml new file mode 100644 index 00000000..28080a1d --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/resources/application.yml @@ -0,0 +1,133 @@ +spring: + cloud: + gateway: + discovery: + locator: + lowerCaseServiceId: true + enabled: true + routes: + - id: auth + uri: lb://uaa-server + predicates: + - Path=/api-uaa/** + filters: + - StripPrefix=1 + - PreserveHostHeader + - id: auth-login-page + uri: lb://uaa-server + predicates: + - Path=/login.html + filters: + - PreserveHostHeader + - id: auth-login-process + uri: lb://uaa-server + predicates: + - Path=/user/login + filters: + - PreserveHostHeader + - id: auth-login-token + uri: lb://uaa-server + predicates: + - Path=/oauth/token + filters: + - PreserveHostHeader + - id: auth-login-authorize + uri: lb://uaa-server + predicates: + - Path=/oauth/authorize + filters: + - PreserveHostHeader + - id: auth-check-process + uri: lb://uaa-server + predicates: + - Path=/oauth/check_token + filters: + - PreserveHostHeader + - id: user + uri: lb://user-center + predicates: + - Path=/api-user/** + filters: + - StripPrefix=1 + - id: file + uri: lb://file-center + predicates: + - Path=/api-file/** + filters: + - StripPrefix=1 + - id: log + uri: lb://log-center + predicates: + - Path=/api-log/** + filters: + - StripPrefix=1 + - id: generator + uri: lb://code-generator + predicates: + - Path=/api-generator/** + filters: + - StripPrefix=1 + - id: search + uri: lb://search-center + predicates: + - Path=/api-search/** + filters: + - StripPrefix=1 +# sentinel: +# datasource.ds1.nacos: +# server-addr: ${zlt.nacos.server-addr} +# data-id: ${spring.application.name}-sentinel-gw-flow +# group-id: DEFAULT_GROUP +# ruleType: gw-flow +# filter: +# enabled: true + +zlt: + swagger-agg: + generate-routes: user,file + oauth2: + token: + store: + type: redis + security: + ignore: + # 忽略认证的地址 + httpUrls: > + /api-uaa/oauth/**, + /api-uaa/validata/**, + /api-uaa/css/**, + /api-uaa/images/**, + /api-uaa/js/**, + /api-user/users-anon/**, + /login.html, + /user/login + auth: + urlPermission: + #是否开启url级别权限 + enable: false + #配置只进行登录认证,不进行url权限认证的api + ignoreUrls: > + /api-user/menus/current, + /api-user/users/current, + /api-log/requestStat + #白名单 + includeClientIds: + - webApp + renew: + #是否开启token自动续签(目前只有redis实现) + enable: true + #白名单 + includeClientIds: + - webApp + gateway: + #网关动态路由 + dynamicRoute: + enabled: true + +hystrix: + command: + default: + execution: + isolation: + thread: + timeoutInMilliseconds: 1000 \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/src/main/resources/bootstrap.yml b/zlt-gateway/sc-gateway/src/main/resources/bootstrap.yml new file mode 100644 index 00000000..02b4e227 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/resources/bootstrap.yml @@ -0,0 +1,19 @@ +server: + port: 9900 + +zlt: + nacos: + server-addr: 192.168.28.130:8848 + +spring: + application: + name: sc-gateway + cloud: + nacos: + config: + server-addr: ${zlt.nacos.server-addr} + file-extension: yml + shared-dataids: common.yml + refreshable-dataids: common.yml + discovery: + server-addr: ${zlt.nacos.server-addr} \ No newline at end of file diff --git a/zlt-gateway/sc-gateway/src/main/resources/pubkey.txt b/zlt-gateway/sc-gateway/src/main/resources/pubkey.txt new file mode 100644 index 00000000..f1f84dd8 --- /dev/null +++ b/zlt-gateway/sc-gateway/src/main/resources/pubkey.txt @@ -0,0 +1,9 @@ +-----BEGIN PUBLIC KEY----- +MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjmgfejBXsPYynAIPczHA +eEvTDfAVaNKQudyI7VszdezbHDM1CStCIgwiMmLd7QYf1SrrmQoqxhcSRbhjE3ej +RF5qzhtx3kmepdpMrQptcsLjRkixaxCc4E2k6Us5707gGwbhoaTrRit5F2MnAdLY +C1TS3WwnO/hQfqUcAglbK8yrJ4AwAv0DAoIUSWnWqzuniV1SYbdV57uswxUssoWy +sEfPz+nv1ZLRs6Wz4eQ5Myqx2+CjWc9F8iXa2PV8Rmjms3dVbWcLUpCP18Dfzp8l +n8vF9LfYB7UaLSpfJe6FFF6+vCg4JHfo12djTUgwGjauMF3e9mmjU83KIoQS66lp +AQIDAQAB +-----END PUBLIC KEY----- \ No newline at end of file diff --git a/zlt-gateway/zuul-gateway/pom.xml b/zlt-gateway/zuul-gateway/pom.xml index 8e45501e..1187cc72 100644 --- a/zlt-gateway/zuul-gateway/pom.xml +++ b/zlt-gateway/zuul-gateway/pom.xml @@ -27,6 +27,10 @@ com.zlt zlt-sentinel-spring-boot-starter + + com.zlt + zlt-redis-spring-boot-starter + com.alibaba.cloud diff --git a/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java b/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java index 6284fe3a..58e217f6 100644 --- a/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java +++ b/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/config/ResourceServerConfiguration.java @@ -2,12 +2,8 @@ package com.central.gateway.config; import com.central.common.config.DefaultPasswordConfig; import com.central.oauth2.common.config.DefaultResourceServerConf; -import com.central.oauth2.common.properties.SecurityProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import org.springframework.http.HttpMethod; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; @@ -17,29 +13,8 @@ import org.springframework.security.oauth2.config.annotation.web.configuration.E */ @Configuration @EnableResourceServer -@EnableConfigurationProperties(SecurityProperties.class) @Import({DefaultPasswordConfig.class}) public class ResourceServerConfiguration extends DefaultResourceServerConf { - @Autowired - private SecurityProperties securityProperties; - - @Override - public void configure(HttpSecurity http) throws Exception { - ExpressionUrlAuthorizationConfigurer.AuthorizedUrl authorizedUrl = setHttp(http) - .authorizeRequests() - .antMatchers(securityProperties.getAuth().getHttpUrls()).authenticated() - .antMatchers(securityProperties.getIgnore().getUrls()).permitAll() - .antMatchers(HttpMethod.OPTIONS).permitAll() - .anyRequest(); - setAuthenticate(authorizedUrl); - //允许使用iframe 嵌套,避免swagger-ui 不被加载的问题 - http.headers() - .frameOptions() - .disable() - .and() - .csrf().disable(); - } - @Override public HttpSecurity setAuthenticate(ExpressionUrlAuthorizationConfigurer.AuthorizedUrl authorizedUrl) { return authorizedUrl.access("@permissionService.hasPermission(request, authentication)").and(); diff --git a/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/filter/pre/LbIsolationFilter.java b/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/filter/pre/LbIsolationFilter.java deleted file mode 100644 index 80ec55b4..00000000 --- a/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/filter/pre/LbIsolationFilter.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.central.gateway.filter.pre; - -import cn.hutool.core.util.StrUtil; -import com.central.common.constant.CommonConstant; -import com.central.common.constant.ConfigConstants; -import com.central.common.context.LbIsolationContextHolder; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; -import org.springframework.stereotype.Component; - -/** - * 保存负载均衡隔离值 - * - * @author zlt - * @date 2019/8/13 - */ -@Component -public class LbIsolationFilter extends ZuulFilter { - @Value("${" + ConfigConstants.CONFIG_RIBBON_ISOLATION_ENABLED + ":false}") - private boolean enableIsolation; - - @Override - public String filterType() { - return FilterConstants.PRE_TYPE; - } - - @Override - public int filterOrder() { - return 0; - } - - @Override - public boolean shouldFilter() { - //根据配置控制是否开启过滤器 - return enableIsolation; - } - - @Override - public Object run() { - RequestContext ctx = RequestContext.getCurrentContext(); - String version = ctx.getRequest().getHeader(CommonConstant.Z_L_T_VERSION); - if (StrUtil.isNotEmpty(version)) { - LbIsolationContextHolder.setVersion(version); - } else { - LbIsolationContextHolder.clear(); - } - return null; - } -} diff --git a/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/service/impl/PermissionServiceImpl.java b/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/service/impl/PermissionServiceImpl.java index af95faaa..422e6e1f 100644 --- a/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/service/impl/PermissionServiceImpl.java +++ b/zlt-gateway/zuul-gateway/src/main/java/com/central/gateway/service/impl/PermissionServiceImpl.java @@ -4,8 +4,10 @@ import com.central.common.model.SysMenu; import com.central.gateway.feign.MenuService; import com.central.oauth2.common.service.impl.DefaultPermissionServiceImpl; import lombok.extern.slf4j.Slf4j; +import org.springframework.security.core.Authentication; import org.springframework.stereotype.Service; import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; import java.util.List; /** @@ -24,4 +26,8 @@ public class PermissionServiceImpl extends DefaultPermissionServiceImpl { public List findMenuByRoleCodes(String roleCodes) { return menuService.findByRoleCodes(roleCodes); } + + public boolean hasPermission(HttpServletRequest request, Authentication authentication) { + return hasPermission(authentication, request.getMethod(), request.getRequestURI()); + } } diff --git a/zlt-gateway/zuul-gateway/src/main/resources/application.yml b/zlt-gateway/zuul-gateway/src/main/resources/application.yml index 6131cdb0..e2a06e3d 100644 --- a/zlt-gateway/zuul-gateway/src/main/resources/application.yml +++ b/zlt-gateway/zuul-gateway/src/main/resources/application.yml @@ -164,7 +164,6 @@ hystrix: swagger: butler: - api-docs-path: v2/api-docs - swagger-version: 2.0 auto-generate-from-zuul-routes: true - generate-routes: user,file \ No newline at end of file + generate-routes: user,file + apiDocsPath: v2/api-docs \ No newline at end of file diff --git a/zlt-monitor/log-center/pom.xml b/zlt-monitor/log-center/pom.xml index 2bd3cde6..814cb9e0 100644 --- a/zlt-monitor/log-center/pom.xml +++ b/zlt-monitor/log-center/pom.xml @@ -30,7 +30,10 @@ com.zlt search-client - + + org.springframework.boot + spring-boot-starter-web + com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery diff --git a/zlt-uaa/pom.xml b/zlt-uaa/pom.xml index fb48a00d..ea0e2cef 100644 --- a/zlt-uaa/pom.xml +++ b/zlt-uaa/pom.xml @@ -13,6 +13,10 @@ com.zlt zlt-config + + com.zlt + zlt-common-spring-boot-starter + com.zlt zlt-auth-client-spring-boot-starter @@ -33,6 +37,10 @@ com.zlt zlt-sentinel-spring-boot-starter + + com.zlt + zlt-redis-spring-boot-starter + com.alibaba.cloud diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/CorsConfigration.java b/zlt-uaa/src/main/java/com/central/oauth/config/CorsConfigration.java deleted file mode 100644 index 95ea5713..00000000 --- a/zlt-uaa/src/main/java/com/central/oauth/config/CorsConfigration.java +++ /dev/null @@ -1,47 +0,0 @@ -package com.central.oauth.config; - -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; -import org.springframework.web.filter.CorsFilter; - -/** - * 跨域配置 - * - * @author zlt - * @date 2018/8/9 15:59 - */ -@Configuration -public class CorsConfigration { - - @Bean - public CorsFilter corsFilter() { - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - CorsConfiguration config = new CorsConfiguration(); - // #允许向该服务器提交请求的URI,*表示全部允许 - config.addAllowedOrigin(CorsConfiguration.ALL); - // 允许cookies跨域 - config.setAllowCredentials(true); - // #允许访问的头信息,*表示全部 - config.addAllowedHeader(CorsConfiguration.ALL); - // 允许提交请求的方法,*表示全部允许 - config.addAllowedMethod(CorsConfiguration.ALL); - source.registerCorsConfiguration("/**", config); - return new CorsFilter(source); - } - - /** - * 配置过滤器 - */ - @Bean - public FilterRegistrationBean someFilterRegistration() { - FilterRegistrationBean registration = new FilterRegistrationBean<>(); - registration.setFilter(corsFilter()); - registration.addUrlPatterns("/*"); - registration.setName("corsFilter"); - registration.setOrder(Integer.MIN_VALUE); - return registration; - } -} diff --git a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java b/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java index 0d411acc..4838b878 100644 --- a/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java +++ b/zlt-uaa/src/main/java/com/central/oauth/config/SecurityConfig.java @@ -4,9 +4,7 @@ import com.central.common.constant.SecurityConstants; import com.central.oauth.mobile.MobileAuthenticationSecurityConfig; import com.central.oauth.openid.OpenIdAuthenticationSecurityConfig; import com.central.common.config.DefaultPasswordConfig; -import com.central.oauth2.common.properties.SecurityProperties; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @@ -32,7 +30,6 @@ import javax.annotation.Resource; * @author zlt */ @Configuration -@EnableConfigurationProperties(SecurityProperties.class) @Import(DefaultPasswordConfig.class) public class SecurityConfig extends WebSecurityConfigurerAdapter { @@ -53,9 +50,6 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { @Resource private LogoutHandler oauthLogoutHandler; - @Autowired - private SecurityProperties securityProperties; - @Autowired private ValidateCodeSecurityConfig validateCodeSecurityConfig; diff --git a/zlt-uaa/src/main/resources/bootstrap.yml b/zlt-uaa/src/main/resources/bootstrap.yml index aed49be4..1625c4cb 100644 --- a/zlt-uaa/src/main/resources/bootstrap.yml +++ b/zlt-uaa/src/main/resources/bootstrap.yml @@ -1,5 +1,9 @@ server: port: 8000 + servlet: + session: + cookie: + name: OAUTH2SESSION zlt: nacos: diff --git a/zlt-web/back-web/src/main/resources/static/module/admin.js b/zlt-web/back-web/src/main/resources/static/module/admin.js index b818f62f..931cf024 100644 --- a/zlt-web/back-web/src/main/resources/static/module/admin.js +++ b/zlt-web/back-web/src/main/resources/static/module/admin.js @@ -102,7 +102,7 @@ layui.define(['config', 'layer'], function (exports) { if (!noHeaderToken) { let token = config.getToken(); if (token) { - xhr.setRequestHeader('Authorization', 'bearer ' + token.access_token); + xhr.setRequestHeader('Authorization', 'Bearer ' + token.access_token); } } let isolationVersion = config.isolationVersion; diff --git a/zlt-web/back-web/src/main/resources/static/pages/attestation/app.html b/zlt-web/back-web/src/main/resources/static/pages/attestation/app.html index 8eb0188a..812cdfc9 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/attestation/app.html +++ b/zlt-web/back-web/src/main/resources/static/pages/attestation/app.html @@ -76,7 +76,7 @@ elem: '#app-table', url: config.base_server + 'api-uaa/clients/list', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: true, cols: [[ {type: 'numbers'}, diff --git a/zlt-web/back-web/src/main/resources/static/pages/files/files.html b/zlt-web/back-web/src/main/resources/static/pages/files/files.html index 3db3e043..756ae6bd 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/files/files.html +++ b/zlt-web/back-web/src/main/resources/static/pages/files/files.html @@ -41,7 +41,7 @@ // url: config.base_server + 'user_query.json', url: config.base_server + 'api-file/files', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: true, cols: [[ {type: 'numbers'}, diff --git a/zlt-web/back-web/src/main/resources/static/pages/generator/list.html b/zlt-web/back-web/src/main/resources/static/pages/generator/list.html index 087b5c51..2bb5e915 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/generator/list.html +++ b/zlt-web/back-web/src/main/resources/static/pages/generator/list.html @@ -37,7 +37,7 @@ elem: '#generator-table', url: config.base_server + 'api-generator/generator/list', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: true, cols: [[ {type: 'numbers'}, diff --git a/zlt-web/back-web/src/main/resources/static/pages/log/slowQueryLog.html b/zlt-web/back-web/src/main/resources/static/pages/log/slowQueryLog.html index 3dcb6c59..f319fdda 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/log/slowQueryLog.html +++ b/zlt-web/back-web/src/main/resources/static/pages/log/slowQueryLog.html @@ -31,7 +31,7 @@ elem: '#slowQueryLog-table', url: config.base_server + 'api-log/slowQueryLog', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: true, cols: [[ {type: 'numbers'}, diff --git a/zlt-web/back-web/src/main/resources/static/pages/log/sysLog.html b/zlt-web/back-web/src/main/resources/static/pages/log/sysLog.html index 97f908af..742425f8 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/log/sysLog.html +++ b/zlt-web/back-web/src/main/resources/static/pages/log/sysLog.html @@ -36,7 +36,7 @@ elem: '#sysLog-table', url: config.base_server + 'api-log/sysLog?data', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: true, cols: [[ {type: 'numbers'}, diff --git a/zlt-web/back-web/src/main/resources/static/pages/search/index_manager.html b/zlt-web/back-web/src/main/resources/static/pages/search/index_manager.html index e69759cd..aec9112c 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/search/index_manager.html +++ b/zlt-web/back-web/src/main/resources/static/pages/search/index_manager.html @@ -33,7 +33,7 @@ elem: '#index-table', url: config.base_server + 'api-search/admin/indices', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: false, cols: [[ {type: 'numbers'}, diff --git a/zlt-web/back-web/src/main/resources/static/pages/search/user_search.html b/zlt-web/back-web/src/main/resources/static/pages/search/user_search.html index 549db6bb..a1412b87 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/search/user_search.html +++ b/zlt-web/back-web/src/main/resources/static/pages/search/user_search.html @@ -36,7 +36,7 @@ elem: '#userSearch-table', url: config.base_server + 'api-user/users/search', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: true, cols: [[ {type: 'numbers'}, diff --git a/zlt-web/back-web/src/main/resources/static/pages/system/myInfo.html b/zlt-web/back-web/src/main/resources/static/pages/system/myInfo.html index f59e1a54..94e4ec49 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/system/myInfo.html +++ b/zlt-web/back-web/src/main/resources/static/pages/system/myInfo.html @@ -89,9 +89,9 @@ url: config.base_server + 'api-file/files-anon', accept: 'file' , auto: true , + headers: {"Authorization" : "Bearer " + config.getToken().access_token}, before: function(obj){ layer.load(); //上传loading - this.data={access_token:config.getToken().access_token}; //预读本地文件示例,不支持ie8 obj.preview(function (index, file, result) { $(".layui-upload-img").remove(); diff --git a/zlt-web/back-web/src/main/resources/static/pages/system/role.html b/zlt-web/back-web/src/main/resources/static/pages/system/role.html index 9660b99f..80f2d681 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/system/role.html +++ b/zlt-web/back-web/src/main/resources/static/pages/system/role.html @@ -72,7 +72,7 @@ table.render({ elem: '#role-table', url: config.base_server + 'api-user/roles', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: true, cols: [[ {type: 'numbers'}, diff --git a/zlt-web/back-web/src/main/resources/static/pages/system/tokens.html b/zlt-web/back-web/src/main/resources/static/pages/system/tokens.html index 02dfada6..e0352e1b 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/system/tokens.html +++ b/zlt-web/back-web/src/main/resources/static/pages/system/tokens.html @@ -37,7 +37,7 @@ elem: '#tokens-table', url: config.base_server + 'api-uaa/tokens', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, where: {tenantId: config.clientId}, page: true, cols: [[ diff --git a/zlt-web/back-web/src/main/resources/static/pages/system/user.html b/zlt-web/back-web/src/main/resources/static/pages/system/user.html index 91886db0..644db720 100644 --- a/zlt-web/back-web/src/main/resources/static/pages/system/user.html +++ b/zlt-web/back-web/src/main/resources/static/pages/system/user.html @@ -59,7 +59,7 @@ elem: '#user-table', url: config.base_server + 'api-user/users', method: 'GET', - headers:{'Authorization': 'bearer ' + config.getToken().access_token}, + headers:{'Authorization': 'Bearer ' + config.getToken().access_token}, page: true, cols: [[ {type: 'numbers'}, @@ -148,11 +148,12 @@ // 导出 $('#user-btn-export').click(function () { - var url = config.base_server + 'api-user/users/export?access_token='+config.getToken().access_token; + var url = config.base_server + 'api-user/users/export'; var xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.responseType = "blob"; xhr.setRequestHeader("client_type", "DESKTOP_WEB"); + xhr.setRequestHeader("Authorization", "Bearer " + config.getToken().access_token); xhr.onload = function() { if (this.status == 200) { var fileName = "user.xlsx"; @@ -192,12 +193,13 @@ }); //上传 - var importUrl = config.base_server + 'api-user/users/import?access_token='+config.getToken().access_token; + var importUrl = config.base_server + 'api-user/users/import'; upload.render({ elem: '#user-btn-import' ,url: importUrl ,accept: 'file' //普通文件 - ,multiple: true + ,multiple: false + ,headers: {"Authorization" : "Bearer " + config.getToken().access_token} ,done: function(data){ if (data.resp_code == 0) { layer.msg(data.resp_msg, {icon: 1, time: 500});