From 1ec839c9594e201693059f03a9e8e4488cf4a3dc Mon Sep 17 00:00:00 2001 From: qraddx Date: Wed, 30 Mar 2022 11:12:56 +0800 Subject: [PATCH] =?UTF-8?q?:recycle:=20Refactoring=20code.=20close=20#I50B?= =?UTF-8?q?A0=20=E5=90=8E=E5=8F=B0=E6=8A=A5=E9=94=99=E4=BD=BF=E7=94=A8?= =?UTF-8?q?=E5=9B=BD=E9=99=85=E5=8C=96=E6=96=87=E4=BB=B6=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- db/pig_config.sql | 2 +- .../core/config/WebMvcConfiguration.java | 16 +++++++- .../pig/common/core/exception/ErrorCodes.java | 21 ++++++++++ .../pig/common/core/util/MsgUtils.java | 38 +++++++++++++++++++ .../resources/i18n/messages_zh_CN.properties | 2 + ...PigSecurityMessageSourceConfiguration.java | 4 +- .../pig/admin/controller/UserController.java | 3 +- .../pig/admin/service/SysUserService.java | 2 +- .../service/impl/SysUserServiceImpl.java | 18 ++++++--- 9 files changed, 93 insertions(+), 13 deletions(-) create mode 100644 pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/ErrorCodes.java create mode 100644 pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/MsgUtils.java create mode 100644 pig-common/pig-common-core/src/main/resources/i18n/messages_zh_CN.properties diff --git a/db/pig_config.sql b/db/pig_config.sql index 2358e2b8..d85f07bb 100644 --- a/db/pig_config.sql +++ b/db/pig_config.sql @@ -36,7 +36,7 @@ CREATE TABLE `config_info` ( -- Records of config_info -- ---------------------------- BEGIN; -INSERT INTO `config_info` VALUES (1, 'application-dev.yml', 'DEFAULT_GROUP', '# 加解密根密码\njasypt:\n encryptor:\n password: pig #根密码\n\n# Spring 相关\n\nspring:\n mvc:\n pathmatch:\n matching-strategy: ant_path_matcher\n redis:\n host: pig-redis\n cloud:\n sentinel:\n eager: true\n transport:\n dashboard: pig-sentinel:5003\n\n# 暴露监控端点\nmanagement:\n endpoints:\n web:\n exposure:\n include: \"*\" \n endpoint:\n health:\n show-details: ALWAYS\n\n\n# feign 配置\nfeign:\n sentinel:\n enabled: true\n okhttp:\n enabled: true\n httpclient:\n enabled: false\n client:\n config:\n default:\n connectTimeout: 10000\n readTimeout: 10000\n compression:\n request:\n enabled: true\n response:\n enabled: true\n\n# mybaits-plus配置\nmybatis-plus:\n mapper-locations: classpath:/mapper/*Mapper.xml\n global-config:\n banner: false\n db-config:\n id-type: auto\n table-underline: true\n logic-delete-value: 1\n logic-not-delete-value: 0\n configuration:\n map-underscore-to-camel-case: true\n\n# spring security 配置\nsecurity:\n oauth2:\n resource:\n loadBalanced: true\n token-info-uri: http://pig-auth/oauth/check_token\n # 通用放行URL,服务个性化,请在对应配置文件覆盖\n ignore:\n urls:\n - /v3/api-docs\n - /v2/api-docs\n - /actuator/**\n - /user/registerUser\n# swagger 配置\nswagger:\n enabled: true\n title: Pig Swagger API\n gateway: http://${GATEWAY_HOST:pig-gateway}:${GATEWAY-PORT:9999}\n token-url: ${swagger.gateway}/auth/oauth/token\n services:\n pig-upms-biz: admin\n pig-codegen: gen', 'fe841b616618e0d7dfdfbb78ff08dc93', '2019-11-29 16:31:20', '2022-03-27 23:19:22', '', '0:0:0:0:0:0:0:1', '', '', '', '', '', 'yaml', ''); +INSERT INTO `config_info` VALUES (1, 'application-dev.yml', 'DEFAULT_GROUP', '# 加解密根密码\njasypt:\n encryptor:\n password: pig #根密码\n\n# Spring 相关\n\nspring:\n mvc:\n pathmatch:\n matching-strategy: ant_path_matcher\n redis:\n host: pig-redis\n cloud:\n sentinel:\n eager: true\n transport:\n dashboard: pig-sentinel:5003\n\n# 暴露监控端点\nmanagement:\n endpoints:\n web:\n exposure:\n include: \"*\" \n endpoint:\n health:\n show-details: ALWAYS\n\n\n# feign 配置\nfeign:\n sentinel:\n enabled: true\n okhttp:\n enabled: true\n httpclient:\n enabled: false\n client:\n config:\n default:\n connectTimeout: 10000\n readTimeout: 10000\n compression:\n request:\n enabled: true\n response:\n enabled: true\n\n# mybaits-plus配置\nmybatis-plus:\n mapper-locations: classpath:/mapper/*Mapper.xml\n global-config:\n banner: false\n db-config:\n id-type: auto\n table-underline: true\n logic-delete-value: 1\n logic-not-delete-value: 0\n configuration:\n map-underscore-to-camel-case: true\n\n# spring security 配置\nsecurity:\n oauth2:\n resource:\n loadBalanced: true\n token-info-uri: http://pig-auth/oauth/check_token\n # 通用放行URL,服务个性化,请在对应配置文件覆盖\n ignore:\n urls:\n - /v3/api-docs\n - /actuator/**\n\n# swagger 配置\nswagger:\n enabled: true\n title: Pig Swagger API\n gateway: http://${GATEWAY_HOST:pig-gateway}:${GATEWAY-PORT:9999}\n token-url: ${swagger.gateway}/auth/oauth/token\n services:\n pig-upms-biz: admin\n pig-codegen: gen', '8d9ffc03cef9e316905d4f86d1914e6b', '2019-11-29 16:31:20', '2022-03-30 10:48:26', 'nacos', '127.0.0.1', '', '', '', '', '', 'yaml', ''); INSERT INTO `config_info` VALUES (2, 'pig-auth-dev.yml', 'DEFAULT_GROUP', '# 数据源\nspring:\n datasource:\n type: com.zaxxer.hikari.HikariDataSource\n driver-class-name: com.mysql.cj.jdbc.Driver\n username: root\n password: root\n url: jdbc:mysql://pig-mysql:3306/pig?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true\n freemarker:\n allow-request-override: false\n allow-session-override: false\n cache: true\n charset: UTF-8\n check-template-location: true\n content-type: text/html\n enabled: true\n expose-request-attributes: false\n expose-session-attributes: false\n expose-spring-macro-helpers: true\n prefer-file-system-access: true\n suffix: .ftl\n template-loader-path: classpath:/templates/', '58b1b48a2888f49e667864be32edf9c1', '2019-11-29 16:31:48', '2020-01-01 18:30:58', NULL, '127.0.0.1', '', '', '认证中心配置', 'null', 'null', 'yaml', 'null'); INSERT INTO `config_info` VALUES (3, 'pig-codegen-dev.yml', 'DEFAULT_GROUP', '## spring security 配置\nsecurity:\n oauth2:\n client:\n client-id: ENC(27v1agvAug87ANOVnbKdsw==)\n client-secret: ENC(VbnkopxrwgbFVKp+UxJ2pg==)\n scope: server\n\n# 数据源配置\nspring:\n datasource:\n type: com.zaxxer.hikari.HikariDataSource\n driver-class-name: com.mysql.cj.jdbc.Driver\n username: root\n password: root\n url: jdbc:mysql://pig-mysql:3306/pig_codegen?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true\n resources:\n static-locations: classpath:/static/,classpath:/views/\n\n# 直接放行URL\nignore:\n urls:\n - /v2/api-docs\n - /actuator/**\n', 'abc702838b34d11b46e96143ccd9f367', '2019-11-29 16:32:12', '2019-11-29 16:32:12', NULL, '127.0.0.1', '', '', '代码生成配置', NULL, NULL, 'yaml', NULL); INSERT INTO `config_info` VALUES (4, 'pig-gateway-dev.yml', 'DEFAULT_GROUP', 'spring:\n cloud:\n gateway:\n locator:\n enabled: true\n routes:\n # 认证中心\n - id: pig-auth\n uri: lb://pig-auth\n predicates:\n - Path=/auth/**\n filters:\n # 验证码处理\n - ValidateCodeGatewayFilter\n # 前端密码解密\n - PasswordDecoderFilter\n #UPMS 模块\n - id: pig-upms-biz\n uri: lb://pig-upms-biz\n predicates:\n - Path=/admin/**\n filters:\n # 限流配置\n - name: RequestRateLimiter\n args:\n key-resolver: \'#{@remoteAddrKeyResolver}\'\n redis-rate-limiter.replenishRate: 100\n redis-rate-limiter.burstCapacity: 200\n # 代码生成模块\n - id: pig-codegen\n uri: lb://pig-codegen\n predicates:\n - Path=/gen/**\n # demo模块\n - id: pig-demo\n uri: lb://demo-biz\n predicates:\n - Path=/demo/**\n - id: openapi\n uri: http://localhost:${server.port}\n predicates:\n - Path=/v3/api-docs/**\n filters:\n - RewritePath=/v3/api-docs/(?.*), /$\\{path}/v3/api-docs\n\ngateway:\n encode-key: \'thanks,pig4cloud\'\n ignore-clients:\n - test', 'dbf00e83f80de7f011d244ea1ce5686e', '2019-11-29 16:32:42', '2022-03-27 23:19:33', '', '0:0:0:0:0:0:0:1', '', '', '网关配置', '', '', 'yaml', ''); diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/WebMvcConfiguration.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/WebMvcConfiguration.java index b86e112c..0c8c0037 100644 --- a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/WebMvcConfiguration.java +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/config/WebMvcConfiguration.java @@ -18,13 +18,14 @@ package com.pig4cloud.pig.common.core.config; import cn.hutool.core.date.DatePattern; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.context.MessageSource; +import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.format.FormatterRegistry; import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import java.time.format.DateTimeFormatter; - import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type.SERVLET; /** @@ -55,4 +56,15 @@ public class WebMvcConfiguration implements WebMvcConfigurer { registrar.registerFormatters(registry); } + /** + * 系统国际化文件配置 + * @return MessageSource + */ + @Bean + public MessageSource messageSource() { + ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); + messageSource.setBasename("classpath:i18n/messages"); + return messageSource; + } + } diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/ErrorCodes.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/ErrorCodes.java new file mode 100644 index 00000000..2a4a7ca9 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/exception/ErrorCodes.java @@ -0,0 +1,21 @@ +package com.pig4cloud.pig.common.core.exception; + +/** + * 错误编码 + * + * @author lengleng + * @date 2022/3/30 + */ +public interface ErrorCodes { + + /** + * 系统编码错误 + */ + String SYS_PARAM_CONFIG_ERROR = "sys.param.config.error"; + + /** + * 用户已存在 + */ + String SYS_USER_USERNAME_EXISTING = "sys.user.username.existing"; + +} diff --git a/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/MsgUtils.java b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/MsgUtils.java new file mode 100644 index 00000000..faa5d442 --- /dev/null +++ b/pig-common/pig-common-core/src/main/java/com/pig4cloud/pig/common/core/util/MsgUtils.java @@ -0,0 +1,38 @@ +package com.pig4cloud.pig.common.core.util; + +import cn.hutool.extra.spring.SpringUtil; +import lombok.experimental.UtilityClass; +import org.springframework.context.MessageSource; + +import java.util.Locale; + +/** + * i18n 工具类 + * + * @author lengleng + * @date 2022/3/30 + */ +@UtilityClass +public class MsgUtils { + + /** + * 通过code 获取中文错误信息 + * @param code + * @return + */ + public String getMessage(String code) { + MessageSource messageSource = SpringUtil.getBean("messageSource"); + return messageSource.getMessage(code, null, Locale.CHINA); + } + + /** + * 通过code 和参数获取中文错误信息 + * @param code + * @return + */ + public String getMessage(String code, Object... objects) { + MessageSource messageSource = SpringUtil.getBean("messageSource"); + return messageSource.getMessage(code, objects, Locale.CHINA); + } + +} diff --git a/pig-common/pig-common-core/src/main/resources/i18n/messages_zh_CN.properties b/pig-common/pig-common-core/src/main/resources/i18n/messages_zh_CN.properties new file mode 100644 index 00000000..5011630f --- /dev/null +++ b/pig-common/pig-common-core/src/main/resources/i18n/messages_zh_CN.properties @@ -0,0 +1,2 @@ +sys.user.username.existing={0} \u7528\u6237\u540D\u5DF2\u5B58\u5728 +sys.param.config.error={0} \u7CFB\u7EDF\u53C2\u6570\u914D\u7F6E\u9519\u8BEF diff --git a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigSecurityMessageSourceConfiguration.java b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigSecurityMessageSourceConfiguration.java index ad688bd6..e73e3c2a 100644 --- a/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigSecurityMessageSourceConfiguration.java +++ b/pig-common/pig-common-security/src/main/java/com/pig4cloud/pig/common/security/component/PigSecurityMessageSourceConfiguration.java @@ -26,7 +26,7 @@ import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebA /** * @author lengleng - * @date 2019-06-24 + * @date 2022年01月06日 *

* 注入自定义错误处理 */ @@ -34,7 +34,7 @@ import static org.springframework.boot.autoconfigure.condition.ConditionalOnWebA public class PigSecurityMessageSourceConfiguration implements WebMvcConfigurer { @Bean - public MessageSource messageSource() { + public MessageSource securityMessageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.addBasenames("classpath:org/springframework/security/messages"); return messageSource; diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java index 344d9968..d58a237c 100644 --- a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/controller/UserController.java @@ -221,10 +221,11 @@ public class UserController { * @param userDto 用户信息 * @return success/false */ + @Inner(value = false) @SysLog("注册用户") @PostMapping("/registerUser") public R registerUser(@RequestBody UserDTO userDto) { - return R.ok(userService.registerUser(userDto)); + return userService.registerUser(userDto); } } diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java index be3c80db..491c4b7a 100644 --- a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/SysUserService.java @@ -120,6 +120,6 @@ public interface SysUserService extends IService { * @param userDto 用户信息 * @return success/false */ - Boolean registerUser(UserDTO userDto); + R registerUser(UserDTO userDto); } diff --git a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java index 609039ec..bd013472 100644 --- a/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java +++ b/pig-upms/pig-upms-biz/src/main/java/com/pig4cloud/pig/admin/service/impl/SysUserServiceImpl.java @@ -18,7 +18,6 @@ package com.pig4cloud.pig.admin.service.impl; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.util.ArrayUtil; -import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; @@ -36,6 +35,8 @@ import com.pig4cloud.pig.admin.service.SysUserService; import com.pig4cloud.pig.common.core.constant.CacheConstants; import com.pig4cloud.pig.common.core.constant.CommonConstants; import com.pig4cloud.pig.common.core.constant.enums.MenuTypeEnum; +import com.pig4cloud.pig.common.core.exception.ErrorCodes; +import com.pig4cloud.pig.common.core.util.MsgUtils; import com.pig4cloud.pig.common.core.util.R; import com.pig4cloud.plugin.excel.vo.ErrorMessage; import lombok.RequiredArgsConstructor; @@ -364,20 +365,25 @@ public class SysUserServiceImpl extends ServiceImpl impl * @return success/false */ @Override - public Boolean registerUser(UserDTO userDto) { + public R registerUser(UserDTO userDto) { // 判断用户名是否存在 SysUser sysUser = this.getOne(Wrappers.lambdaQuery().eq(SysUser::getUsername, userDto.getUsername())); - Assert.isNull(sysUser, "用户名存在!"); + if (sysUser != null) { + return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERNAME_EXISTING, userDto.getUsername())); + } // 获取默认角色编码 - String defaultRole = ParamResolver.getStr("REGISTER_DEFAULT_ROLE"); + String defaultRole = ParamResolver.getStr("USER_DEFAULT_ROLE"); // 默认角色 SysRole sysRole = sysRoleMapper .selectOne(Wrappers.lambdaQuery().eq(SysRole::getRoleCode, defaultRole)); - Assert.isTrue(ObjectUtil.isNotEmpty(sysRole), "系统参数配置错误!"); + + if (sysRole == null) { + return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_PARAM_CONFIG_ERROR, "USER_DEFAULT_ROLE")); + } userDto.setRole(Collections.singletonList(sysRole.getRoleId())); - return saveUser(userDto); + return R.ok(saveUser(userDto)); } }