From 6258a14113e77e131e386bb1238a9ae2abd73f9a Mon Sep 17 00:00:00 2001 From: hrz <1710360675@qq.com> Date: Wed, 5 Mar 2025 21:40:26 +0800 Subject: [PATCH] =?UTF-8?q?update:=E8=B0=83=E6=95=B4=E9=A1=B9=E7=9B=AE?= =?UTF-8?q?=E7=9B=AE=E5=BD=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 3 +- main/manager-api/pom.xml | 229 ++++++ .../main/java/xiaozhi/AdminApplication.java | 13 + .../xiaozhi/common/annotation/DataFilter.java | 29 + .../common/annotation/LogOperation.java | 16 + .../common/aspect/DataFilterAspect.java | 99 +++ .../xiaozhi/common/aspect/RedisAspect.java | 40 ++ .../common/config/MybatisPlusConfig.java | 34 + .../xiaozhi/common/config/SwaggerConfig.java | 32 + .../xiaozhi/common/constant/Constant.java | 150 ++++ .../xiaozhi/common/convert/DateConverter.java | 73 ++ .../main/java/xiaozhi/common/dao/BaseDao.java | 12 + .../xiaozhi/common/entity/BaseEntity.java | 33 + .../xiaozhi/common/exception/ErrorCode.java | 38 + .../common/exception/RenException.java | 67 ++ .../common/exception/RenExceptionHandler.java | 57 ++ .../handler/FieldMetaObjectHandler.java | 59 ++ .../interceptor/DataFilterInterceptor.java | 81 +++ .../xiaozhi/common/interceptor/DataScope.java | 27 + .../java/xiaozhi/common/page/PageData.java | 33 + .../java/xiaozhi/common/page/TokenDTO.java | 26 + .../xiaozhi/common/redis/RedisConfig.java | 32 + .../java/xiaozhi/common/redis/RedisKeys.java | 80 +++ .../java/xiaozhi/common/redis/RedisUtils.java | 126 ++++ .../xiaozhi/common/service/BaseService.java | 108 +++ .../xiaozhi/common/service/CrudService.java | 28 + .../common/service/impl/BaseServiceImpl.java | 214 ++++++ .../common/service/impl/CrudServiceImpl.java | 73 ++ .../java/xiaozhi/common/user/UserDetail.java | 32 + .../xiaozhi/common/utils/ConvertUtils.java | 50 ++ .../java/xiaozhi/common/utils/DateUtils.java | 63 ++ .../common/utils/HttpContextUtils.java | 107 +++ .../java/xiaozhi/common/utils/IpUtils.java | 47 ++ .../java/xiaozhi/common/utils/JsonUtils.java | 68 ++ .../xiaozhi/common/utils/MessageUtils.java | 25 + .../xiaozhi/common/utils/PropertiesUtils.java | 11 + .../java/xiaozhi/common/utils/Result.java | 73 ++ .../common/utils/SpringContextUtils.java | 45 ++ .../java/xiaozhi/common/utils/TreeNode.java | 30 + .../java/xiaozhi/common/utils/TreeUtils.java | 71 ++ .../xiaozhi/common/validator/AssertUtils.java | 89 +++ .../common/validator/ValidatorUtils.java | 47 ++ .../common/validator/group/AddGroup.java | 8 + .../common/validator/group/DefaultGroup.java | 8 + .../common/validator/group/UpdateGroup.java | 8 + .../java/xiaozhi/common/xss/SqlFilter.java | 44 ++ .../java/xiaozhi/common/xss/XssConfig.java | 32 + .../java/xiaozhi/common/xss/XssFilter.java | 48 ++ .../xss/XssHttpServletRequestWrapper.java | 118 +++ .../xiaozhi/common/xss/XssProperties.java | 25 + .../java/xiaozhi/common/xss/XssUtils.java | 62 ++ .../modules/security/config/FilterConfig.java | 28 + .../modules/security/config/ShiroConfig.java | 89 +++ .../modules/security/config/WebMvcConfig.java | 65 ++ .../security/controller/LoginController.java | 55 ++ .../modules/security/dao/SysUserTokenDao.java | 23 + .../modules/security/dto/LoginDTO.java | 32 + .../security/entity/SysUserTokenEntity.java | 46 ++ .../modules/security/oauth2/Oauth2Filter.java | 101 +++ .../modules/security/oauth2/Oauth2Realm.java | 86 +++ .../modules/security/oauth2/Oauth2Token.java | 26 + .../security/oauth2/TokenGenerator.java | 44 ++ .../modules/security/password/BCrypt.java | 672 ++++++++++++++++++ .../password/BCryptPasswordEncoder.java | 78 ++ .../security/password/PasswordEncoder.java | 30 + .../security/password/PasswordUtils.java | 42 ++ .../security/service/CaptchaService.java | 27 + .../security/service/ShiroService.java | 30 + .../security/service/SysUserTokenService.java | 31 + .../service/impl/CaptchaServiceImpl.java | 94 +++ .../service/impl/ShiroServiceImpl.java | 48 ++ .../service/impl/SysUserTokenServiceImpl.java | 78 ++ .../modules/security/user/SecurityUser.java | 56 ++ .../sys/controller/SysUserController.java | 156 ++++ .../modules/sys/dao/SysDictDataDao.java | 23 + .../modules/sys/dao/SysDictTypeDao.java | 21 + .../xiaozhi/modules/sys/dao/SysParamsDao.java | 38 + .../xiaozhi/modules/sys/dao/SysUserDao.java | 34 + .../xiaozhi/modules/sys/dto/PasswordDTO.java | 24 + .../modules/sys/dto/SysDictDataDTO.java | 59 ++ .../modules/sys/dto/SysDictTypeDTO.java | 55 ++ .../xiaozhi/modules/sys/dto/SysParamsDTO.java | 52 ++ .../xiaozhi/modules/sys/dto/SysUserDTO.java | 85 +++ .../xiaozhi/modules/sys/entity/DictData.java | 15 + .../xiaozhi/modules/sys/entity/DictType.java | 18 + .../modules/sys/entity/SysDictDataEntity.java | 49 ++ .../modules/sys/entity/SysDictTypeEntity.java | 45 ++ .../modules/sys/entity/SysParamsEntity.java | 46 ++ .../modules/sys/entity/SysUserEntity.java | 75 ++ .../modules/sys/enums/SuperAdminEnum.java | 19 + .../modules/sys/redis/SysParamsRedis.java | 34 + .../sys/service/SysDictDataService.java | 25 + .../sys/service/SysDictTypeService.java | 26 + .../modules/sys/service/SysParamsService.java | 51 ++ .../modules/sys/service/SysUserService.java | 67 ++ .../service/impl/SysDictDataServiceImpl.java | 77 ++ .../service/impl/SysDictTypeServiceImpl.java | 102 +++ .../service/impl/SysParamsServiceImpl.java | 131 ++++ .../sys/service/impl/SysUserServiceImpl.java | 181 +++++ .../src/main/resources/application-dev.yml | 49 ++ .../src/main/resources/application.yml | 79 ++ .../resources/db/changelog/001create_sys.sql | 84 +++ .../db/changelog/db.changelog-master.yaml | 11 + .../main/resources/i18n/messages.properties | 54 ++ .../resources/i18n/messages_en_US.properties | 54 ++ .../resources/i18n/messages_zh_CN.properties | 54 ++ .../resources/i18n/messages_zh_TW.properties | 54 ++ .../main/resources/i18n/validation.properties | 109 +++ .../i18n/validation_en_US.properties | 110 +++ .../i18n/validation_zh_CN.properties | 109 +++ .../i18n/validation_zh_TW.properties | 110 +++ .../src/main/resources/logback-spring.xml | 35 + .../resources/mapper/sys/SysDictDataDao.xml | 13 + .../resources/mapper/sys/SysDictTypeDao.xml | 10 + .../resources/mapper/sys/SysParamsDao.xml | 23 + .../main/resources/mapper/sys/SysUserDao.xml | 50 ++ .../resources/mapper/sys/SysUserTokenDao.xml | 17 + .../src/test/java/xiaozhi/DbEncTest.java | 25 + .../src/test/java/xiaozhi/RedisTest.java | 27 + .../service/DynamicDataSourceTestService.java | 24 + {web/vue => main/manager-web}/README.md | 0 {web/vue => main/manager-web}/jsconfig.json | 0 .../manager-web}/package-lock.json | 0 {web/vue => main/manager-web}/package.json | 0 .../manager-web}/public/favicon.ico | Bin .../manager-web}/public/index.html | 0 {web/vue => main/manager-web}/src/App.vue | 0 .../manager-web}/src/assets/home/avatar.png | Bin .../src/assets/home/background.png | Bin .../manager-web}/src/assets/home/close.png | Bin .../manager-web}/src/assets/home/delete.png | Bin .../src/assets/home/equipment.png | Bin .../manager-web}/src/assets/home/info.png | Bin .../src/assets/home/main-top-bg.png | Bin .../manager-web}/src/assets/home/red-info.png | Bin .../manager-web}/src/assets/home/search.png | Bin .../src/assets/home/setting-user.png | Bin .../src/assets/login/background.png | Bin .../src/assets/login/down-arrow.png | Bin .../manager-web}/src/assets/login/hi.png | Bin .../src/assets/login/password.png | Bin .../manager-web}/src/assets/login/phone.png | Bin .../manager-web}/src/assets/login/shield.png | Bin .../src/assets/login/username.png | Bin .../manager-web}/src/assets/logo.png | Bin .../src/assets/welcome/background.png | Bin .../src/assets/welcome/github.png | Bin .../manager-web}/src/assets/welcome/more.png | Bin .../src/assets/welcome/questions.png | Bin .../manager-web}/src/assets/xiaozhi-ai.png | Bin .../manager-web}/src/assets/xiaozhi-logo.png | Bin .../src/components/HelloWorld.vue | 0 {web/vue => main/manager-web}/src/main.js | 0 .../manager-web}/src/router/index.js | 0 .../manager-web}/src/store/index.js | 0 .../manager-web}/src/views/home.vue | 0 .../manager-web}/src/views/login.vue | 0 .../manager-web}/src/views/welcome.vue | 0 .../xiaozhi-server/.dockerignore | 2 +- Dockerfile => main/xiaozhi-server/Dockerfile | 0 .../xiaozhi-server/Dockerfile-pip | 0 app.py => main/xiaozhi-server/app.py | 0 .../xiaozhi-server/config.yaml | 0 .../xiaozhi-server/config}/logger.py | 0 .../xiaozhi-server/config}/private_config.py | 0 .../xiaozhi-server/config}/settings.py | 0 {core => main/xiaozhi-server/core}/auth.py | 0 .../xiaozhi-server/core}/connection.py | 0 .../core}/handle/abortHandle.py | 0 .../core}/handle/helloHandle.py | 0 .../xiaozhi-server/core}/handle/iotHandle.py | 0 .../core}/handle/musicHandler.py | 0 .../core}/handle/receiveAudioHandle.py | 0 .../core}/handle/sendAudioHandle.py | 0 .../xiaozhi-server/core}/handle/textHandle.py | 0 .../core}/providers/asr/base.py | 0 .../core}/providers/asr/doubao.py | 0 .../core}/providers/asr/fun_local.py | 0 .../core}/providers/llm/base.py | 0 .../core}/providers/llm/coze/coze.py | 0 .../core}/providers/llm/dify/dify.py | 0 .../core}/providers/llm/gemini/gemini.py | 0 .../llm/homeassistant/homeassistant.py | 0 .../core}/providers/llm/ollama/ollama.py | 0 .../core}/providers/llm/openai/openai.py | 0 .../core}/providers/tts/aliyun.py | 0 .../core}/providers/tts/base.py | 0 .../core}/providers/tts/cozecn.py | 0 .../core}/providers/tts/doubao.py | 0 .../core}/providers/tts/edge.py | 0 .../core}/providers/tts/fishspeech.py | 0 .../core}/providers/tts/gpt_sovits_v2.py | 0 .../core}/providers/tts/minimax.py | 0 .../core}/providers/tts/siliconflow.py | 0 .../xiaozhi-server/core}/utils/asr.py | 0 .../core}/utils/auth_code_gen.py | 0 .../xiaozhi-server/core}/utils/dialogue.py | 0 .../xiaozhi-server/core}/utils/llm.py | 0 .../core}/utils/lock_manager.py | 0 .../xiaozhi-server/core}/utils/p3.py | 0 .../xiaozhi-server/core}/utils/tts.py | 0 .../xiaozhi-server/core}/utils/util.py | 0 .../xiaozhi-server/core}/utils/vad.py | 0 .../xiaozhi-server/core}/websocket_server.py | 0 main/xiaozhi-server/data/.config.yaml | 360 ++++++++++ .../xiaozhi-server/docker-compose.yml | 0 .../chn_jpn_yue_eng_ko_spectok.bpe.model | Bin .../models}/SenseVoiceSmall/config.yaml | 0 .../SenseVoiceSmall/configuration.json | 0 .../models}/SenseVoiceSmall/demo.py | 0 .../models}/SenseVoiceSmall/example/en.mp3 | Bin .../models}/SenseVoiceSmall/example/ja.mp3 | Bin .../models}/SenseVoiceSmall/example/ko.mp3 | Bin .../models}/SenseVoiceSmall/example/yue.mp3 | Bin .../models}/SenseVoiceSmall/example/zh.mp3 | Bin .../models}/snakers4_silero-vad/hubconf.py | 0 .../src/silero_vad/__init__.py | 0 .../src/silero_vad/data/__init__.py | 0 .../src/silero_vad/data/silero_vad.jit | Bin .../src/silero_vad/data/silero_vad.onnx | Bin .../silero_vad/data/silero_vad_16k_op15.onnx | Bin .../src/silero_vad/data/silero_vad_half.onnx | Bin .../src/silero_vad/model.py | 0 .../src/silero_vad/utils_vad.py | 0 .../xiaozhi-server/music}/一念千年_国风版.mp3 | Bin .../xiaozhi-server/music}/中秋月.mp3 | Bin .../music}/廉波老矣,尚能饭否.mp3 | Bin .../xiaozhi-server/performance_tester.py | 0 .../xiaozhi-server/poetry.lock | 0 .../xiaozhi-server/pyproject.toml | 0 web/__init__.py | 0 web/api/__init__.py | 0 web/api/admin/__init__.py | 0 web/api/admin/admin.py | 122 ---- web/api/auth/__init__.py | 0 web/api/auth/auth.py | 66 -- web/api/auth/dependencies.py | 59 -- web/api/auth/models.py | 37 - web/api/auth/security.py | 51 -- web/api/db/__init__.py | 0 web/api/db/database.py | 31 - web/api/db/models.py | 13 - web/app.py | 60 -- 243 files changed, 7673 insertions(+), 441 deletions(-) create mode 100644 main/manager-api/pom.xml create mode 100644 main/manager-api/src/main/java/xiaozhi/AdminApplication.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/annotation/DataFilter.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/annotation/LogOperation.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/aspect/DataFilterAspect.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/aspect/RedisAspect.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/config/MybatisPlusConfig.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/convert/DateConverter.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/dao/BaseDao.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/entity/BaseEntity.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/exception/RenException.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/exception/RenExceptionHandler.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/interceptor/DataScope.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/page/PageData.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/page/TokenDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/redis/RedisConfig.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/redis/RedisUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/service/BaseService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/service/CrudService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/user/UserDetail.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/ConvertUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/HttpContextUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/IpUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java create mode 100755 main/manager-api/src/main/java/xiaozhi/common/utils/PropertiesUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/Result.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/SpringContextUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/TreeNode.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/utils/TreeUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/validator/AssertUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/validator/ValidatorUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/validator/group/AddGroup.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/validator/group/DefaultGroup.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/validator/group/UpdateGroup.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/xss/SqlFilter.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/xss/XssConfig.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/xss/XssFilter.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/xss/XssHttpServletRequestWrapper.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/xss/XssProperties.java create mode 100644 main/manager-api/src/main/java/xiaozhi/common/xss/XssUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/config/FilterConfig.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/dao/SysUserTokenDao.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/entity/SysUserTokenEntity.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Token.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/TokenGenerator.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/password/BCrypt.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/password/BCryptPasswordEncoder.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordEncoder.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordUtils.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/service/CaptchaService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/service/ShiroService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/ShiroServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/security/user/SecurityUser.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysUserController.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictDataDao.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictTypeDao.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysParamsDao.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dto/PasswordDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictDataDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictTypeDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysParamsDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/entity/DictData.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/entity/DictType.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictDataEntity.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictTypeEntity.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysParamsEntity.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/enums/SuperAdminEnum.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/redis/SysParamsRedis.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictDataService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictTypeService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysParamsService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java create mode 100644 main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java create mode 100644 main/manager-api/src/main/resources/application-dev.yml create mode 100644 main/manager-api/src/main/resources/application.yml create mode 100644 main/manager-api/src/main/resources/db/changelog/001create_sys.sql create mode 100755 main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml create mode 100644 main/manager-api/src/main/resources/i18n/messages.properties create mode 100644 main/manager-api/src/main/resources/i18n/messages_en_US.properties create mode 100644 main/manager-api/src/main/resources/i18n/messages_zh_CN.properties create mode 100644 main/manager-api/src/main/resources/i18n/messages_zh_TW.properties create mode 100644 main/manager-api/src/main/resources/i18n/validation.properties create mode 100644 main/manager-api/src/main/resources/i18n/validation_en_US.properties create mode 100644 main/manager-api/src/main/resources/i18n/validation_zh_CN.properties create mode 100644 main/manager-api/src/main/resources/i18n/validation_zh_TW.properties create mode 100644 main/manager-api/src/main/resources/logback-spring.xml create mode 100644 main/manager-api/src/main/resources/mapper/sys/SysDictDataDao.xml create mode 100644 main/manager-api/src/main/resources/mapper/sys/SysDictTypeDao.xml create mode 100644 main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml create mode 100644 main/manager-api/src/main/resources/mapper/sys/SysUserDao.xml create mode 100644 main/manager-api/src/main/resources/mapper/sys/SysUserTokenDao.xml create mode 100755 main/manager-api/src/test/java/xiaozhi/DbEncTest.java create mode 100644 main/manager-api/src/test/java/xiaozhi/RedisTest.java create mode 100644 main/manager-api/src/test/java/xiaozhi/service/DynamicDataSourceTestService.java rename {web/vue => main/manager-web}/README.md (100%) rename {web/vue => main/manager-web}/jsconfig.json (100%) rename {web/vue => main/manager-web}/package-lock.json (100%) rename {web/vue => main/manager-web}/package.json (100%) rename {web/vue => main/manager-web}/public/favicon.ico (100%) rename {web/vue => main/manager-web}/public/index.html (100%) rename {web/vue => main/manager-web}/src/App.vue (100%) rename {web/vue => main/manager-web}/src/assets/home/avatar.png (100%) rename {web/vue => main/manager-web}/src/assets/home/background.png (100%) rename {web/vue => main/manager-web}/src/assets/home/close.png (100%) rename {web/vue => main/manager-web}/src/assets/home/delete.png (100%) rename {web/vue => main/manager-web}/src/assets/home/equipment.png (100%) rename {web/vue => main/manager-web}/src/assets/home/info.png (100%) rename {web/vue => main/manager-web}/src/assets/home/main-top-bg.png (100%) rename {web/vue => main/manager-web}/src/assets/home/red-info.png (100%) rename {web/vue => main/manager-web}/src/assets/home/search.png (100%) rename {web/vue => main/manager-web}/src/assets/home/setting-user.png (100%) rename {web/vue => main/manager-web}/src/assets/login/background.png (100%) rename {web/vue => main/manager-web}/src/assets/login/down-arrow.png (100%) rename {web/vue => main/manager-web}/src/assets/login/hi.png (100%) rename {web/vue => main/manager-web}/src/assets/login/password.png (100%) rename {web/vue => main/manager-web}/src/assets/login/phone.png (100%) rename {web/vue => main/manager-web}/src/assets/login/shield.png (100%) rename {web/vue => main/manager-web}/src/assets/login/username.png (100%) rename {web/vue => main/manager-web}/src/assets/logo.png (100%) rename {web/vue => main/manager-web}/src/assets/welcome/background.png (100%) rename {web/vue => main/manager-web}/src/assets/welcome/github.png (100%) rename {web/vue => main/manager-web}/src/assets/welcome/more.png (100%) rename {web/vue => main/manager-web}/src/assets/welcome/questions.png (100%) rename {web/vue => main/manager-web}/src/assets/xiaozhi-ai.png (100%) rename {web/vue => main/manager-web}/src/assets/xiaozhi-logo.png (100%) rename {web/vue => main/manager-web}/src/components/HelloWorld.vue (100%) rename {web/vue => main/manager-web}/src/main.js (100%) rename {web/vue => main/manager-web}/src/router/index.js (100%) rename {web/vue => main/manager-web}/src/store/index.js (100%) rename {web/vue => main/manager-web}/src/views/home.vue (100%) rename {web/vue => main/manager-web}/src/views/login.vue (100%) rename {web/vue => main/manager-web}/src/views/welcome.vue (100%) rename .dockerignore => main/xiaozhi-server/.dockerignore (92%) rename Dockerfile => main/xiaozhi-server/Dockerfile (100%) rename Dockerfile-pip => main/xiaozhi-server/Dockerfile-pip (100%) rename app.py => main/xiaozhi-server/app.py (100%) rename config.yaml => main/xiaozhi-server/config.yaml (100%) rename {config => main/xiaozhi-server/config}/logger.py (100%) rename {config => main/xiaozhi-server/config}/private_config.py (100%) rename {config => main/xiaozhi-server/config}/settings.py (100%) rename {core => main/xiaozhi-server/core}/auth.py (100%) rename {core => main/xiaozhi-server/core}/connection.py (100%) rename {core => main/xiaozhi-server/core}/handle/abortHandle.py (100%) rename {core => main/xiaozhi-server/core}/handle/helloHandle.py (100%) rename {core => main/xiaozhi-server/core}/handle/iotHandle.py (100%) rename {core => main/xiaozhi-server/core}/handle/musicHandler.py (100%) rename {core => main/xiaozhi-server/core}/handle/receiveAudioHandle.py (100%) rename {core => main/xiaozhi-server/core}/handle/sendAudioHandle.py (100%) rename {core => main/xiaozhi-server/core}/handle/textHandle.py (100%) rename {core => main/xiaozhi-server/core}/providers/asr/base.py (100%) rename {core => main/xiaozhi-server/core}/providers/asr/doubao.py (100%) rename {core => main/xiaozhi-server/core}/providers/asr/fun_local.py (100%) rename {core => main/xiaozhi-server/core}/providers/llm/base.py (100%) rename {core => main/xiaozhi-server/core}/providers/llm/coze/coze.py (100%) rename {core => main/xiaozhi-server/core}/providers/llm/dify/dify.py (100%) rename {core => main/xiaozhi-server/core}/providers/llm/gemini/gemini.py (100%) rename {core => main/xiaozhi-server/core}/providers/llm/homeassistant/homeassistant.py (100%) rename {core => main/xiaozhi-server/core}/providers/llm/ollama/ollama.py (100%) rename {core => main/xiaozhi-server/core}/providers/llm/openai/openai.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/aliyun.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/base.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/cozecn.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/doubao.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/edge.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/fishspeech.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/gpt_sovits_v2.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/minimax.py (100%) rename {core => main/xiaozhi-server/core}/providers/tts/siliconflow.py (100%) rename {core => main/xiaozhi-server/core}/utils/asr.py (100%) rename {core => main/xiaozhi-server/core}/utils/auth_code_gen.py (100%) rename {core => main/xiaozhi-server/core}/utils/dialogue.py (100%) rename {core => main/xiaozhi-server/core}/utils/llm.py (100%) rename {core => main/xiaozhi-server/core}/utils/lock_manager.py (100%) rename {core => main/xiaozhi-server/core}/utils/p3.py (100%) rename {core => main/xiaozhi-server/core}/utils/tts.py (100%) rename {core => main/xiaozhi-server/core}/utils/util.py (100%) rename {core => main/xiaozhi-server/core}/utils/vad.py (100%) rename {core => main/xiaozhi-server/core}/websocket_server.py (100%) create mode 100644 main/xiaozhi-server/data/.config.yaml rename docker-compose.yml => main/xiaozhi-server/docker-compose.yml (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/chn_jpn_yue_eng_ko_spectok.bpe.model (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/config.yaml (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/configuration.json (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/demo.py (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/example/en.mp3 (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/example/ja.mp3 (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/example/ko.mp3 (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/example/yue.mp3 (100%) rename {models => main/xiaozhi-server/models}/SenseVoiceSmall/example/zh.mp3 (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/hubconf.py (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/src/silero_vad/__init__.py (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/src/silero_vad/data/__init__.py (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/src/silero_vad/data/silero_vad.jit (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/src/silero_vad/data/silero_vad.onnx (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/src/silero_vad/data/silero_vad_16k_op15.onnx (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/src/silero_vad/data/silero_vad_half.onnx (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/src/silero_vad/model.py (100%) rename {models => main/xiaozhi-server/models}/snakers4_silero-vad/src/silero_vad/utils_vad.py (100%) rename {music => main/xiaozhi-server/music}/一念千年_国风版.mp3 (100%) rename {music => main/xiaozhi-server/music}/中秋月.mp3 (100%) rename {music => main/xiaozhi-server/music}/廉波老矣,尚能饭否.mp3 (100%) rename performance_tester.py => main/xiaozhi-server/performance_tester.py (100%) rename poetry.lock => main/xiaozhi-server/poetry.lock (100%) rename pyproject.toml => main/xiaozhi-server/pyproject.toml (100%) delete mode 100644 web/__init__.py delete mode 100644 web/api/__init__.py delete mode 100644 web/api/admin/__init__.py delete mode 100644 web/api/admin/admin.py delete mode 100644 web/api/auth/__init__.py delete mode 100644 web/api/auth/auth.py delete mode 100644 web/api/auth/dependencies.py delete mode 100644 web/api/auth/models.py delete mode 100644 web/api/auth/security.py delete mode 100644 web/api/db/__init__.py delete mode 100644 web/api/db/database.py delete mode 100644 web/api/db/models.py delete mode 100644 web/app.py diff --git a/.gitignore b/.gitignore index 5edf237e4..b855d20b1 100644 --- a/.gitignore +++ b/.gitignore @@ -142,5 +142,6 @@ model.pt tmp .DS_Store /data -/web/node_modules +*/node_modules web/vue/node_modules +main/manager-web/node_modules diff --git a/main/manager-api/pom.xml b/main/manager-api/pom.xml new file mode 100644 index 000000000..050f863d1 --- /dev/null +++ b/main/manager-api/pom.xml @@ -0,0 +1,229 @@ + + 4.0.0 + xiaozhi + xiaozhi-esp32-api + jar + 0.0.1 + xiaozhi-esp32-api + 小智后台管理系统 + + + org.springframework.boot + spring-boot-starter-parent + 3.4.3 + + + + UTF-8 + UTF-8 + 21 + 5.12.0 + 1.2.20 + 3.5.5 + 5.8.24 + 1.19.1 + 3.0.5 + 4.6.0 + 2.3.2 + 2.0.2 + 1.6.2 + 33.0.0-jre + 3.3.2 + 4.20.0 + + + + + org.quartz-scheduler + quartz + ${quartz.version} + + + com.mchange + c3p0 + + + com.zaxxer + HikariCP-java6 + + + + + org.apache.shiro + shiro-core + jakarta + ${shiro.version} + + + org.apache.shiro + shiro-spring + jakarta + ${shiro.version} + + + org.apache.shiro + shiro-core + + + org.apache.shiro + shiro-web + + + + + org.apache.shiro + shiro-web + jakarta + ${shiro.version} + + + org.apache.shiro + shiro-core + + + + + com.github.whvcse + easy-captcha + ${captcha.version} + + + + org.springframework.boot + spring-boot-starter-websocket + + + com.google.guava + guava + ${guava.version} + + + org.junit.jupiter + junit-jupiter-api + ${junit.version} + test + + + org.springframework.boot + spring-boot-starter-test + test + + + jakarta.servlet + jakarta.servlet-api + provided + + + org.springframework.boot + spring-boot-starter-web + + + org.springframework.boot + spring-boot-starter-aop + + + org.springframework + spring-context-support + + + org.springframework.boot + spring-boot-starter-data-redis + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + com.mysql + mysql-connector-j + + + com.alibaba + druid-spring-boot-3-starter + ${druid.version} + + + org.liquibase + liquibase-core + ${liquibase-core.version} + + + com.baomidou + mybatis-plus-boot-starter + ${mybatisplus.version} + + + org.mybatis + mybatis-spring + 3.0.3 + + + cn.hutool + hutool-all + ${hutool.version} + + + org.jsoup + jsoup + ${jsoup.version} + + + com.github.xingfudeshi + knife4j-openapi3-jakarta-spring-boot-starter + ${knife4j.version} + + + org.projectlombok + lombok + true + + + + + + + public + aliyun nexus + https://maven.aliyun.com/repository/public/ + + true + + + + + + public + aliyun nexus + https://maven.aliyun.com/repository/public/ + + true + + + false + + + + + ${project.artifactId} + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/AdminApplication.java b/main/manager-api/src/main/java/xiaozhi/AdminApplication.java new file mode 100644 index 000000000..87edd5103 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/AdminApplication.java @@ -0,0 +1,13 @@ +package xiaozhi; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class AdminApplication { + + public static void main(String[] args) { + SpringApplication.run(AdminApplication.class, args); + System.out.println("http://localhost:8002/xiaozhi-esp32-api/doc.html"); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/annotation/DataFilter.java b/main/manager-api/src/main/java/xiaozhi/common/annotation/DataFilter.java new file mode 100644 index 000000000..b25c6fb4f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/annotation/DataFilter.java @@ -0,0 +1,29 @@ +package xiaozhi.common.annotation; + +import java.lang.annotation.*; + +/** + * 数据过滤注解 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface DataFilter { + /** + * 表的别名 + */ + String tableAlias() default ""; + + /** + * 用户ID + */ + String userId() default "creator"; + + /** + * 部门ID + */ + String deptId() default "dept_id"; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/annotation/LogOperation.java b/main/manager-api/src/main/java/xiaozhi/common/annotation/LogOperation.java new file mode 100644 index 000000000..b2514ef56 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/annotation/LogOperation.java @@ -0,0 +1,16 @@ +package xiaozhi.common.annotation; + +import java.lang.annotation.*; + +/** + * 操作日志注解 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface LogOperation { + + String value() default ""; +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/aspect/DataFilterAspect.java b/main/manager-api/src/main/java/xiaozhi/common/aspect/DataFilterAspect.java new file mode 100644 index 000000000..db75689dc --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/aspect/DataFilterAspect.java @@ -0,0 +1,99 @@ +package xiaozhi.common.aspect; + +import cn.hutool.core.collection.CollUtil; +import xiaozhi.common.annotation.DataFilter; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.interceptor.DataScope; +import xiaozhi.common.user.UserDetail; +import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.enums.SuperAdminEnum; +import org.apache.commons.lang3.StringUtils; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.springframework.stereotype.Component; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; + +/** + * 数据过滤,切面处理类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Aspect +@Component +public class DataFilterAspect { + + @Pointcut("@annotation(xiaozhi.common.annotation.DataFilter)") + public void dataFilterCut() { + + } + + @Before("dataFilterCut()") + public void dataFilter(JoinPoint point) { + Object params = point.getArgs()[0]; + if (params != null && params instanceof Map) { + UserDetail user = SecurityUser.getUser(); + + //如果是超级管理员,则不进行数据过滤 + if (user.getSuperAdmin() == SuperAdminEnum.YES.value()) { + return; + } + + try { + //否则进行数据过滤 + Map map = (Map) params; + String sqlFilter = getSqlFilter(user, point); + map.put(Constant.SQL_FILTER, new DataScope(sqlFilter)); + } catch (Exception e) { + + } + + return; + } + + throw new RenException(ErrorCode.DATA_SCOPE_PARAMS_ERROR); + } + + /** + * 获取数据过滤的SQL + */ + private String getSqlFilter(UserDetail user, JoinPoint point) throws Exception { + MethodSignature signature = (MethodSignature) point.getSignature(); + Method method = point.getTarget().getClass().getDeclaredMethod(signature.getName(), signature.getParameterTypes()); + DataFilter dataFilter = method.getAnnotation(DataFilter.class); + + //获取表的别名 + String tableAlias = dataFilter.tableAlias(); + if (StringUtils.isNotBlank(tableAlias)) { + tableAlias += "."; + } + + StringBuilder sqlFilter = new StringBuilder(); + sqlFilter.append(" ("); + + //部门ID列表 + List deptIdList = user.getDeptIdList(); + if (CollUtil.isNotEmpty(deptIdList)) { + sqlFilter.append(tableAlias).append(dataFilter.deptId()); + + sqlFilter.append(" in(").append(StringUtils.join(deptIdList, ",")).append(")"); + } + + //查询本人数据 + if (CollUtil.isNotEmpty(deptIdList)) { + sqlFilter.append(" or "); + } + sqlFilter.append(tableAlias).append(dataFilter.userId()).append("=").append(user.getId()); + + sqlFilter.append(")"); + + return sqlFilter.toString(); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/aspect/RedisAspect.java b/main/manager-api/src/main/java/xiaozhi/common/aspect/RedisAspect.java new file mode 100644 index 000000000..ab5309002 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/aspect/RedisAspect.java @@ -0,0 +1,40 @@ +package xiaozhi.common.aspect; + +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +/** + * Redis切面处理类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Slf4j +@Aspect +@Component +public class RedisAspect { + /** + * 是否开启redis缓存 true开启 false关闭 + */ + @Value("${renren.redis.open}") + private boolean open; + + @Around("execution(* xiaozhi.common.redis.RedisUtils.*(..))") + public Object around(ProceedingJoinPoint point) throws Throwable { + Object result = null; + if (open) { + try { + result = point.proceed(); + } catch (Exception e) { + log.error("redis error", e); + throw new RenException(ErrorCode.REDIS_ERROR); + } + } + return result; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/MybatisPlusConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/MybatisPlusConfig.java new file mode 100644 index 000000000..2890a61c4 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/config/MybatisPlusConfig.java @@ -0,0 +1,34 @@ +package xiaozhi.common.config; + +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import xiaozhi.common.interceptor.DataFilterInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * mybatis-plus配置 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Configuration +public class MybatisPlusConfig { + + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor(); + // 数据权限 + mybatisPlusInterceptor.addInnerInterceptor(new DataFilterInterceptor()); + // 分页插件 + mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor()); + // 乐观锁 + mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor()); + // 防止全表更新与删除 + mybatisPlusInterceptor.addInnerInterceptor(new BlockAttackInnerInterceptor()); + + return mybatisPlusInterceptor; + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java new file mode 100644 index 000000000..c9e38ab16 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/config/SwaggerConfig.java @@ -0,0 +1,32 @@ +package xiaozhi.common.config; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; +import org.springdoc.core.models.GroupedOpenApi; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Swagger配置 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Configuration +public class SwaggerConfig { + + @Bean + public GroupedOpenApi userApi() { + String[] paths = {"/**"}; + return GroupedOpenApi.builder().group("xiaozhi") + .pathsToMatch(paths).build(); + } + + @Bean + public OpenAPI customOpenAPI() { + return new OpenAPI().info(new Info() + .title("xiaozhi-esp32-manager-api") + .description("xiaozhi-esp32-manager-api文档") + .version("3.0") + .termsOfService("https://127.0.0.1")); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java new file mode 100644 index 000000000..ffe7ff3c1 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/constant/Constant.java @@ -0,0 +1,150 @@ +package xiaozhi.common.constant; + +/** + * 常量 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public interface Constant { + /** + * 成功 + */ + int SUCCESS = 1; + /** + * 失败 + */ + int FAIL = 0; + /** + * OK + */ + String OK = "OK"; + /** + * 用户标识 + */ + String USER_KEY = "userId"; + /** + * 菜单根节点标识 + */ + Long MENU_ROOT = 0L; + /** + * 部门根节点标识 + */ + Long DEPT_ROOT = 0L; + /** + * 数据字典根节点标识 + */ + Long DICT_ROOT = 0L; + /** + * 升序 + */ + String ASC = "asc"; + /** + * 降序 + */ + String DESC = "desc"; + /** + * 创建时间字段名 + */ + String CREATE_DATE = "create_date"; + + /** + * 创建时间字段名 + */ + String ID = "id"; + + /** + * 数据权限过滤 + */ + String SQL_FILTER = "sqlFilter"; + + /** + * 当前页码 + */ + String PAGE = "page"; + /** + * 每页显示记录数 + */ + String LIMIT = "limit"; + /** + * 排序字段 + */ + String ORDER_FIELD = "orderField"; + /** + * 排序方式 + */ + String ORDER = "order"; + /** + * token header + */ + String TOKEN_HEADER = "token"; + + /** + * 路径分割符 + */ + String FILE_EXTENSION_SEG = "."; + + enum SysBaseParam { + /** + * 系统全称 + */ + SYS_NAME("SYS_NAME"), + /** + * 系统简称 + */ + SYS_SHORT_NAME("SYS_SHORT_NAME"), + /** + * 系统描述 + */ + SYS_DES("SYS_DES"), + /** + * 登录失败几次锁定 + */ + LOGIN_LOCK_COUNT("LOGIN_LOCK_COUNT"), + /** + * 账号失败锁定分钟数 + */ + LOGIN_LOCK_TIME("LOGIN_LOCK_TIME"), + /** + * TOKEN强验证 + */ + SYS_TOKEN_SECURITY("SYS_TOKEN_SECURITY"); + + private String value; + + SysBaseParam(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } + + /** + * 数据状态 + */ + enum DataOperation { + /** + * 插入 + */ + INSERT("I"), + /** + * 已修改 + */ + UPDATE("U"), + /** + * 已删除 + */ + DELETE("D"); + + private String value; + + DataOperation(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/convert/DateConverter.java b/main/manager-api/src/main/java/xiaozhi/common/convert/DateConverter.java new file mode 100644 index 000000000..a84391807 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/convert/DateConverter.java @@ -0,0 +1,73 @@ +package xiaozhi.common.convert; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +/** + * 日期转换 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Component +public class DateConverter implements Converter { + private static final Logger logger = LoggerFactory.getLogger(DateConverter.class); + private static final List formatList = new ArrayList<>(5); + + static { + formatList.add("yyyy-MM"); + formatList.add("yyyy-MM-dd"); + formatList.add("yyyy-MM-dd hh:mm"); + formatList.add("yyyy-MM-dd hh:mm:ss"); + formatList.add("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + } + + @Override + public Date convert(String source) { + String value = source.trim(); + if (StringUtils.isEmpty(value)) { + return null; + } + + if (source.matches("^\\d{4}-\\d{1,2}$")) { + return parseDate(source, formatList.get(0)); + } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) { + return parseDate(source, formatList.get(1)); + } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")) { + return parseDate(source, formatList.get(2)); + } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) { + return parseDate(source, formatList.get(3)); + } else if (source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}.*T.*\\d{1,2}:\\d{1,2}:\\d{1,2}.*..*$")) { + return parseDate(source, formatList.get(4)); + } else { + throw new IllegalArgumentException("Invalid boolean value '" + source + "'"); + } + } + + /** + * 格式化日期 + * + * @param dateStr String 字符型日期 + * @param format String 格式 + * @return Date 日期 + */ + public Date parseDate(String dateStr, String format) { + Date date = null; + try { + DateFormat dateFormat = new SimpleDateFormat(format); + date = dateFormat.parse(dateStr); + } catch (Exception e) { + logger.error("Formatted date with date: {} and format : {} ", dateStr, format); + } + return date; + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/dao/BaseDao.java b/main/manager-api/src/main/java/xiaozhi/common/dao/BaseDao.java new file mode 100644 index 000000000..d65e78305 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/dao/BaseDao.java @@ -0,0 +1,12 @@ +package xiaozhi.common.dao; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; + +/** + * 基础Dao + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public interface BaseDao extends BaseMapper { + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/entity/BaseEntity.java b/main/manager-api/src/main/java/xiaozhi/common/entity/BaseEntity.java new file mode 100644 index 000000000..e7e2f345d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/entity/BaseEntity.java @@ -0,0 +1,33 @@ +package xiaozhi.common.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 基础实体类,所有实体都需要继承 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Data +public abstract class BaseEntity implements Serializable { + /** + * id + */ + @TableId + private Long id; + /** + * 创建者 + */ + @TableField(fill = FieldFill.INSERT) + private Long creator; + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java new file mode 100644 index 000000000..22fd6100a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/ErrorCode.java @@ -0,0 +1,38 @@ +package xiaozhi.common.exception; + +/** + * 错误编码,由5位数字组成,前2位为模块编码,后3位为业务编码 + *

+ * 如:10001(10代表系统模块,001代表业务代码) + *

+ * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public interface ErrorCode { + int INTERNAL_SERVER_ERROR = 500; + int UNAUTHORIZED = 401; + int FORBIDDEN = 403; + + int NOT_NULL = 10001; + int DB_RECORD_EXISTS = 10002; + int PARAMS_GET_ERROR = 10003; + int ACCOUNT_PASSWORD_ERROR = 10004; + int ACCOUNT_DISABLE = 10005; + int IDENTIFIER_NOT_NULL = 10006; + int CAPTCHA_ERROR = 10007; + int SUB_MENU_EXIST = 10008; + int PASSWORD_ERROR = 10009; + int SUPERIOR_DEPT_ERROR = 10011; + int SUPERIOR_MENU_ERROR = 10012; + int DATA_SCOPE_PARAMS_ERROR = 10013; + int DEPT_SUB_DELETE_ERROR = 10014; + int DEPT_USER_DELETE_ERROR = 10015; + int UPLOAD_FILE_EMPTY = 10019; + int TOKEN_NOT_EMPTY = 10020; + int TOKEN_INVALID = 10021; + int ACCOUNT_LOCK = 10022; + int OSS_UPLOAD_FILE_ERROR = 10024; + int REDIS_ERROR = 10027; + int JOB_ERROR = 10028; + int INVALID_SYMBOL = 10029; +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/RenException.java b/main/manager-api/src/main/java/xiaozhi/common/exception/RenException.java new file mode 100644 index 000000000..cf295dcfe --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/RenException.java @@ -0,0 +1,67 @@ +package xiaozhi.common.exception; + + +import xiaozhi.common.utils.MessageUtils; + +/** + * 自定义异常 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class RenException extends RuntimeException { + + + private int code; + private String msg; + + public RenException(int code) { + this.code = code; + this.msg = MessageUtils.getMessage(code); + } + + public RenException(int code, String... params) { + this.code = code; + this.msg = MessageUtils.getMessage(code, params); + } + + public RenException(int code, Throwable e) { + super(e); + this.code = code; + this.msg = MessageUtils.getMessage(code); + } + + public RenException(int code, Throwable e, String... params) { + super(e); + this.code = code; + this.msg = MessageUtils.getMessage(code, params); + } + + public RenException(String msg) { + super(msg); + this.code = ErrorCode.INTERNAL_SERVER_ERROR; + this.msg = msg; + } + + public RenException(String msg, Throwable e) { + super(msg, e); + this.code = ErrorCode.INTERNAL_SERVER_ERROR; + this.msg = msg; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/exception/RenExceptionHandler.java b/main/manager-api/src/main/java/xiaozhi/common/exception/RenExceptionHandler.java new file mode 100644 index 000000000..06665ee2f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/exception/RenExceptionHandler.java @@ -0,0 +1,57 @@ +package xiaozhi.common.exception; + +import lombok.AllArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.authz.UnauthorizedException; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import xiaozhi.common.utils.Result; + + +/** + * 异常处理器 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Slf4j +@AllArgsConstructor +@RestControllerAdvice +public class RenExceptionHandler { + + /** + * 处理自定义异常 + */ + @ExceptionHandler(RenException.class) + public Result handleRenException(RenException ex) { + Result result = new Result(); + result.error(ex.getCode(), ex.getMsg()); + + return result; + } + + @ExceptionHandler(DuplicateKeyException.class) + public Result handleDuplicateKeyException(DuplicateKeyException ex) { + Result result = new Result(); + result.error(ErrorCode.DB_RECORD_EXISTS); + + return result; + } + + @ExceptionHandler(UnauthorizedException.class) + public Result handleUnauthorizedException(UnauthorizedException ex) { + Result result = new Result(); + result.error(ErrorCode.FORBIDDEN); + + return result; + } + + + @ExceptionHandler(Exception.class) + public Result handleException(Exception ex) { + log.error(ex.getMessage(), ex); + + return new Result().error(); + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java b/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java new file mode 100644 index 000000000..fbb75322d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/handler/FieldMetaObjectHandler.java @@ -0,0 +1,59 @@ +package xiaozhi.common.handler; + +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.user.UserDetail; +import xiaozhi.modules.security.user.SecurityUser; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.util.Date; + +/** + * 公共字段,自动填充值 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Component +public class FieldMetaObjectHandler implements MetaObjectHandler { + private final static String CREATE_DATE = "createDate"; + private final static String CREATOR = "creator"; + private final static String UPDATE_DATE = "updateDate"; + private final static String UPDATER = "updater"; + + private final static String DATA_OPERATION = "dataOperation"; + private final static String DEPT_ID = "deptId"; + + @Override + public void insertFill(MetaObject metaObject) { + UserDetail user = SecurityUser.getUser(); + Date date = new Date(); + + //创建者 + strictInsertFill(metaObject, CREATOR, Long.class, user.getId()); + //创建时间 + strictInsertFill(metaObject, CREATE_DATE, Date.class, date); + + //创建者所属部门 + strictInsertFill(metaObject, DEPT_ID, Long.class, user.getDeptId()); + + //更新者 + strictInsertFill(metaObject, UPDATER, Long.class, user.getId()); + //更新时间 + strictInsertFill(metaObject, UPDATE_DATE, Date.class, date); + + //数据标识 + strictInsertFill(metaObject, DATA_OPERATION, String.class, Constant.DataOperation.INSERT.getValue()); + } + + @Override + public void updateFill(MetaObject metaObject) { + //更新者 + strictUpdateFill(metaObject, UPDATER, Long.class, SecurityUser.getUserId()); + //更新时间 + strictUpdateFill(metaObject, UPDATE_DATE, Date.class, new Date()); + + //数据标识 + strictInsertFill(metaObject, DATA_OPERATION, String.class, Constant.DataOperation.UPDATE.getValue()); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java new file mode 100644 index 000000000..160e7ff33 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataFilterInterceptor.java @@ -0,0 +1,81 @@ +package xiaozhi.common.interceptor; + +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.toolkit.PluginUtils; +import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor; +import net.sf.jsqlparser.JSQLParserException; +import net.sf.jsqlparser.expression.Expression; +import net.sf.jsqlparser.expression.StringValue; +import net.sf.jsqlparser.expression.operators.conditional.AndExpression; +import net.sf.jsqlparser.parser.CCJSqlParserUtil; +import net.sf.jsqlparser.statement.select.PlainSelect; +import net.sf.jsqlparser.statement.select.Select; +import org.apache.ibatis.executor.Executor; +import org.apache.ibatis.mapping.BoundSql; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.session.ResultHandler; +import org.apache.ibatis.session.RowBounds; + +import java.util.Map; + +/** + * 数据过滤 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class DataFilterInterceptor implements InnerInterceptor { + + @Override + public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) { + DataScope scope = getDataScope(parameter); + // 不进行数据过滤 + if (scope == null || StrUtil.isBlank(scope.getSqlFilter())) { + return; + } + + // 拼接新SQL + String buildSql = getSelect(boundSql.getSql(), scope); + + // 重写SQL + PluginUtils.mpBoundSql(boundSql).sql(buildSql); + } + + private DataScope getDataScope(Object parameter) { + if (parameter == null) { + return null; + } + + // 判断参数里是否有DataScope对象 + if (parameter instanceof Map) { + Map parameterMap = (Map) parameter; + for (Map.Entry entry : parameterMap.entrySet()) { + if (entry.getValue() != null && entry.getValue() instanceof DataScope) { + return (DataScope) entry.getValue(); + } + } + } else if (parameter instanceof DataScope) { + return (DataScope) parameter; + } + + return null; + } + + private String getSelect(String buildSql, DataScope scope) { + try { + Select select = (Select) CCJSqlParserUtil.parse(buildSql); + PlainSelect plainSelect = (PlainSelect) select.getSelectBody(); + + Expression expression = plainSelect.getWhere(); + if (expression == null) { + plainSelect.setWhere(new StringValue(scope.getSqlFilter())); + } else { + AndExpression andExpression = new AndExpression(expression, new StringValue(scope.getSqlFilter())); + plainSelect.setWhere(andExpression); + } + + return select.toString().replaceAll("'", ""); + } catch (JSQLParserException e) { + return buildSql; + } + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataScope.java b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataScope.java new file mode 100644 index 000000000..b59de67b0 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/interceptor/DataScope.java @@ -0,0 +1,27 @@ +package xiaozhi.common.interceptor; + +/** + * 数据范围 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class DataScope { + private String sqlFilter; + + public DataScope(String sqlFilter) { + this.sqlFilter = sqlFilter; + } + + public String getSqlFilter() { + return sqlFilter; + } + + public void setSqlFilter(String sqlFilter) { + this.sqlFilter = sqlFilter; + } + + @Override + public String toString() { + return this.sqlFilter; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/page/PageData.java b/main/manager-api/src/main/java/xiaozhi/common/page/PageData.java new file mode 100644 index 000000000..b7e943d2d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/page/PageData.java @@ -0,0 +1,33 @@ +package xiaozhi.common.page; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * 分页工具类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Data +@Schema(description = "分页数据") +public class PageData implements Serializable { + @Schema(description = "总记录数") + private int total; + + @Schema(description = "列表数据") + private List list; + + /** + * 分页 + * + * @param list 列表数据 + * @param total 总记录数 + */ + public PageData(List list, long total) { + this.list = list; + this.total = (int) total; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/page/TokenDTO.java b/main/manager-api/src/main/java/xiaozhi/common/page/TokenDTO.java new file mode 100644 index 000000000..48d26f3a1 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/page/TokenDTO.java @@ -0,0 +1,26 @@ +package xiaozhi.common.page; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.io.Serializable; + +/** + * 令牌信息 + * + * @author Jack + */ +@Data +@Schema(description = "令牌信息") +public class TokenDTO implements Serializable { + + + @Schema(description = "密码") + private String token; + + @Schema(description = "过期时间") + private int expire; + + @Schema(description = "客户端指纹") + private String clientHash; +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisConfig.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisConfig.java new file mode 100644 index 000000000..a4316b63a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisConfig.java @@ -0,0 +1,32 @@ +package xiaozhi.common.redis; + +import jakarta.annotation.Resource; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +/** + * Redis配置 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Configuration +public class RedisConfig { + @Resource + private RedisConnectionFactory factory; + + @Bean + public RedisTemplate redisTemplate() { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setKeySerializer(new StringRedisSerializer()); + redisTemplate.setValueSerializer(RedisSerializer.json()); + redisTemplate.setHashKeySerializer(new StringRedisSerializer()); + redisTemplate.setHashValueSerializer(RedisSerializer.json()); + redisTemplate.setConnectionFactory(factory); + + return redisTemplate; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java new file mode 100644 index 000000000..0c5940599 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisKeys.java @@ -0,0 +1,80 @@ +package xiaozhi.common.redis; + +/** + * Redis Key 常量类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class RedisKeys { + /** + * 系统参数Key + */ + public static String getSysParamsKey() { + return "sys:params"; + } + + /** + * 验证码Key + */ + public static String getCaptchaKey(String uuid) { + return "sys:captcha:" + uuid; + } + + /** + * 登录用户Key + */ + public static String getSecurityUserKey(Long id) { + return "sys:security:user:" + id; + } + + /** + * 系统日志Key + */ + public static String getSysLogKey() { + return "sys:log"; + } + + /** + * 系统资源Key + */ + public static String getSysResourceKey() { + return "sys:resource"; + } + + /** + * 用户菜单导航Key + */ + public static String getUserMenuNavKey(Long userId) { + return "sys:user:nav:" + userId; + } + + /** + * 用户权限标识Key + */ + public static String getUserPermissionsKey(Long userId) { + return "sys:user:permissions:" + userId; + } + + /** + * 用户登陆错误次数 + * + * @param username + * @return + */ + public static String getUserLoginErrorCountKey(String username) { + return "sys:user:login:error:" + username; + } + + public static String getUserInfoKey(Long userId) { + return "sys:user:" + userId; + } + + public static String getDataScopeListKey(Long userId) { + return "sys:user:data:scope:" + userId; + } + + public static String getSysUserName(Long id) { + return "sys:user:name" + id; + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/redis/RedisUtils.java b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisUtils.java new file mode 100644 index 000000000..4626b14d4 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/redis/RedisUtils.java @@ -0,0 +1,126 @@ +package xiaozhi.common.redis; + +import jakarta.annotation.Resource; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * Redis工具类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Component +public class RedisUtils { + @Resource + private RedisTemplate redisTemplate; + + /** + * 默认过期时长为24小时,单位:秒 + */ + public final static long DEFAULT_EXPIRE = 60 * 60 * 24L; + /** + * 过期时长为1小时,单位:秒 + */ + public final static long HOUR_ONE_EXPIRE = 60 * 60 * 1L; + /** + * 过期时长为6小时,单位:秒 + */ + public final static long HOUR_SIX_EXPIRE = 60 * 60 * 6L; + /** + * 不设置过期时长 + */ + public final static long NOT_EXPIRE = -1L; + + public void set(String key, Object value, long expire) { + redisTemplate.opsForValue().set(key, value); + if (expire != NOT_EXPIRE) { + expire(key, expire); + } + } + + public void set(String key, Object value) { + set(key, value, DEFAULT_EXPIRE); + } + + public Object get(String key, long expire) { + Object value = redisTemplate.opsForValue().get(key); + if (expire != NOT_EXPIRE) { + expire(key, expire); + } + return value; + } + + public Object get(String key) { + return get(key, NOT_EXPIRE); + } + + public void delete(String key) { + redisTemplate.delete(key); + } + + public void delete(Collection keys) { + redisTemplate.delete(keys); + } + + public Object hGet(String key, String field) { + return redisTemplate.opsForHash().get(key, field); + } + + public Map hGetAll(String key) { + HashOperations hashOperations = redisTemplate.opsForHash(); + return hashOperations.entries(key); + } + + public void hMSet(String key, Map map) { + hMSet(key, map, DEFAULT_EXPIRE); + } + + public void hMSet(String key, Map map, long expire) { + redisTemplate.opsForHash().putAll(key, map); + + if (expire != NOT_EXPIRE) { + expire(key, expire); + } + } + + public void hSet(String key, String field, Object value) { + hSet(key, field, value, DEFAULT_EXPIRE); + } + + public void hSet(String key, String field, Object value, long expire) { + redisTemplate.opsForHash().put(key, field, value); + + if (expire != NOT_EXPIRE) { + expire(key, expire); + } + } + + public void expire(String key, long expire) { + redisTemplate.expire(key, expire, TimeUnit.SECONDS); + } + + public void hDel(String key, Object... fields) { + redisTemplate.opsForHash().delete(key, fields); + } + + public void leftPush(String key, Object value) { + leftPush(key, value, DEFAULT_EXPIRE); + } + + public void leftPush(String key, Object value, long expire) { + redisTemplate.opsForList().leftPush(key, value); + + if (expire != NOT_EXPIRE) { + expire(key, expire); + } + } + + public Object rightPop(String key) { + return redisTemplate.opsForList().rightPop(key); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/BaseService.java b/main/manager-api/src/main/java/xiaozhi/common/service/BaseService.java new file mode 100644 index 000000000..254511409 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/service/BaseService.java @@ -0,0 +1,108 @@ +package xiaozhi.common.service; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; + +import java.io.Serializable; +import java.util.Collection; + +/** + * 基础服务接口,所有Service接口都要继承 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public interface BaseService { + Class currentModelClass(); + + /** + *

+ * 插入一条记录(选择字段,策略插入) + *

+ * + * @param entity 实体对象 + */ + boolean insert(T entity); + + /** + *

+ * 插入(批量),该方法不支持 Oracle、SQL Server + *

+ * + * @param entityList 实体对象集合 + */ + boolean insertBatch(Collection entityList); + + /** + *

+ * 插入(批量),该方法不支持 Oracle、SQL Server + *

+ * + * @param entityList 实体对象集合 + * @param batchSize 插入批次数量 + */ + boolean insertBatch(Collection entityList, int batchSize); + + /** + *

+ * 根据 ID 选择修改 + *

+ * + * @param entity 实体对象 + */ + boolean updateById(T entity); + + /** + *

+ * 根据 whereEntity 条件,更新记录 + *

+ * + * @param entity 实体对象 + * @param updateWrapper 实体对象封装操作类 {@link com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper} + */ + boolean update(T entity, Wrapper updateWrapper); + + /** + *

+ * 根据ID 批量更新 + *

+ * + * @param entityList 实体对象集合 + */ + boolean updateBatchById(Collection entityList); + + /** + *

+ * 根据ID 批量更新 + *

+ * + * @param entityList 实体对象集合 + * @param batchSize 更新批次数量 + */ + boolean updateBatchById(Collection entityList, int batchSize); + + /** + *

+ * 根据 ID 查询 + *

+ * + * @param id 主键ID + */ + T selectById(Serializable id); + + /** + *

+ * 根据 ID 删除 + *

+ * + * @param id 主键ID + */ + boolean deleteById(Serializable id); + + /** + *

+ * 删除(根据ID 批量删除) + *

+ * + * @param idList 主键ID列表 + */ + boolean deleteBatchIds(Collection idList); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/CrudService.java b/main/manager-api/src/main/java/xiaozhi/common/service/CrudService.java new file mode 100644 index 000000000..bc1094e4a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/service/CrudService.java @@ -0,0 +1,28 @@ +package xiaozhi.common.service; + +import xiaozhi.common.page.PageData; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; + +/** + * CRUD基础服务接口 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public interface CrudService extends BaseService { + + PageData page(Map params); + + List list(Map params); + + D get(Serializable id); + + void save(D dto); + + void update(D dto); + + void delete(Serializable[] ids); + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java new file mode 100644 index 000000000..b1559f3bb --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/service/impl/BaseServiceImpl.java @@ -0,0 +1,214 @@ +package xiaozhi.common.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.baomidou.mybatisplus.core.enums.SqlMethod; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.metadata.OrderItem; +import com.baomidou.mybatisplus.core.toolkit.Constants; +import com.baomidou.mybatisplus.core.toolkit.ReflectionKit; +import com.baomidou.mybatisplus.core.toolkit.StringUtils; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.toolkit.SqlHelper; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.common.utils.ConvertUtils; +import org.apache.ibatis.binding.MapperMethod; +import org.apache.ibatis.logging.Log; +import org.apache.ibatis.logging.LogFactory; +import org.apache.ibatis.session.SqlSession; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.transaction.annotation.Transactional; + +import java.io.Serializable; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.function.BiConsumer; + +/** + * 基础服务类,所有Service都要继承 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public abstract class BaseServiceImpl, T> implements BaseService { + @Autowired + protected M baseDao; + protected Log log = LogFactory.getLog(getClass()); + + /** + * 获取分页对象 + * + * @param params 分页查询参数 + * @param defaultOrderField 默认排序字段 + * @param isAsc 排序方式 + */ + protected IPage getPage(Map params, String defaultOrderField, boolean isAsc) { + //分页参数 + long curPage = 1; + long limit = 10; + + if (params.get(Constant.PAGE) != null) { + curPage = Long.parseLong((String) params.get(Constant.PAGE)); + } + if (params.get(Constant.LIMIT) != null) { + limit = Long.parseLong((String) params.get(Constant.LIMIT)); + } + + //分页对象 + Page page = new Page<>(curPage, limit); + + //分页参数 + params.put(Constant.PAGE, page); + + //排序字段 + String orderField = (String) params.get(Constant.ORDER_FIELD); + String order = (String) params.get(Constant.ORDER); + + //前端字段排序 + if (StringUtils.isNotBlank(orderField) && StringUtils.isNotBlank(order)) { + if (Constant.ASC.equalsIgnoreCase(order)) { + return page.addOrder(OrderItem.asc(orderField)); + } else { + return page.addOrder(OrderItem.desc(orderField)); + } + } + + //没有排序字段,则不排序 + if (StringUtils.isBlank(defaultOrderField)) { + return page; + } + + //默认排序 + if (isAsc) { + page.addOrder(OrderItem.asc(defaultOrderField)); + } else { + page.addOrder(OrderItem.desc(defaultOrderField)); + } + + return page; + } + + protected PageData getPageData(List list, long total, Class target) { + List targetList = ConvertUtils.sourceToTarget(list, target); + + return new PageData<>(targetList, total); + } + + protected PageData getPageData(IPage page, Class target) { + return getPageData(page.getRecords(), page.getTotal(), target); + } + + protected void paramsToLike(Map params, String... likes) { + for (String like : likes) { + String val = (String) params.get(like); + if (StringUtils.isNotBlank(val)) { + params.put(like, "%" + val + "%"); + } else { + params.put(like, null); + } + } + } + + /** + *

+ * 判断数据库操作是否成功 + *

+ *

+ * 注意!! 该方法为 Integer 判断,不可传入 int 基本类型 + *

+ * + * @param result 数据库操作返回影响条数 + * @return boolean + */ + protected static boolean retBool(Integer result) { + return SqlHelper.retBool(result); + } + + protected Class currentMapperClass() { + return (Class) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 0); + } + + @Override + public Class currentModelClass() { + return (Class) ReflectionKit.getSuperClassGenericType(this.getClass(), BaseServiceImpl.class, 1); + } + + protected String getSqlStatement(SqlMethod sqlMethod) { + return SqlHelper.getSqlStatement(this.currentMapperClass(), sqlMethod); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean insert(T entity) { + return BaseServiceImpl.retBool(baseDao.insert(entity)); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean insertBatch(Collection entityList) { + return insertBatch(entityList, 100); + } + + /** + * 批量插入 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean insertBatch(Collection entityList, int batchSize) { + String sqlStatement = getSqlStatement(SqlMethod.INSERT_ONE); + return executeBatch(entityList, batchSize, (sqlSession, entity) -> sqlSession.insert(sqlStatement, entity)); + } + + /** + * 执行批量操作 + */ + protected boolean executeBatch(Collection list, int batchSize, BiConsumer consumer) { + return SqlHelper.executeBatch(this.currentModelClass(), this.log, list, batchSize, consumer); + } + + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateById(T entity) { + return BaseServiceImpl.retBool(baseDao.updateById(entity)); + } + + @Override + public boolean update(T entity, Wrapper updateWrapper) { + return BaseServiceImpl.retBool(baseDao.update(entity, updateWrapper)); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateBatchById(Collection entityList) { + return updateBatchById(entityList, 30); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateBatchById(Collection entityList, int batchSize) { + String sqlStatement = getSqlStatement(SqlMethod.UPDATE_BY_ID); + return executeBatch(entityList, batchSize, (sqlSession, entity) -> { + MapperMethod.ParamMap param = new MapperMethod.ParamMap<>(); + param.put(Constants.ENTITY, entity); + sqlSession.update(sqlStatement, param); + }); + } + + @Override + public T selectById(Serializable id) { + return baseDao.selectById(id); + } + + @Override + public boolean deleteById(Serializable id) { + return SqlHelper.retBool(baseDao.deleteById(id)); + } + + @Override + public boolean deleteBatchIds(Collection idList) { + return SqlHelper.retBool(baseDao.deleteBatchIds(idList)); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java new file mode 100644 index 000000000..6608e7c3a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/service/impl/CrudServiceImpl.java @@ -0,0 +1,73 @@ +package xiaozhi.common.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.ReflectionKit; +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.CrudService; +import xiaozhi.common.utils.ConvertUtils; +import org.springframework.beans.BeanUtils; + +import java.io.Serializable; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * CRUD基础服务类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public abstract class CrudServiceImpl, T, D> extends BaseServiceImpl implements CrudService { + + protected Class currentDtoClass() { + return (Class) ReflectionKit.getSuperClassGenericType(getClass(), CrudServiceImpl.class, 2); + } + + @Override + public PageData page(Map params) { + IPage page = baseDao.selectPage( + getPage(params, null, false), + getWrapper(params) + ); + + return getPageData(page, currentDtoClass()); + } + + @Override + public List list(Map params) { + List entityList = baseDao.selectList(getWrapper(params)); + + return ConvertUtils.sourceToTarget(entityList, currentDtoClass()); + } + + public abstract QueryWrapper getWrapper(Map params); + + @Override + public D get(Serializable id) { + T entity = baseDao.selectById(id); + + return ConvertUtils.sourceToTarget(entity, currentDtoClass()); + } + + @Override + public void save(D dto) { + T entity = ConvertUtils.sourceToTarget(dto, currentModelClass()); + insert(entity); + + //copy主键值到dto + BeanUtils.copyProperties(entity, dto); + } + + @Override + public void update(D dto) { + T entity = ConvertUtils.sourceToTarget(dto, currentModelClass()); + updateById(entity); + } + + @Override + public void delete(Serializable[] ids) { + baseDao.deleteBatchIds(Arrays.asList(ids)); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/user/UserDetail.java b/main/manager-api/src/main/java/xiaozhi/common/user/UserDetail.java new file mode 100644 index 000000000..163982de8 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/user/UserDetail.java @@ -0,0 +1,32 @@ +package xiaozhi.common.user; + +import lombok.Data; + +import java.io.Serializable; +import java.util.List; + +/** + * 登录用户信息 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Data +public class UserDetail implements Serializable { + private Long id; + private String username; + private String realName; + private String headUrl; + private Integer gender; + private String email; + private String mobile; + private Long deptId; + private String password; + private Integer status; + private Integer superAdmin; + private String token; + /** + * 部门数据权限 + */ + private List deptIdList; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/ConvertUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/ConvertUtils.java new file mode 100644 index 000000000..7a5bc0ed7 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/ConvertUtils.java @@ -0,0 +1,50 @@ +package xiaozhi.common.utils; + +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.BeanUtils; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +/** + * 转换工具类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Slf4j +public class ConvertUtils { + public static T sourceToTarget(Object source, Class target) { + if (source == null) { + return null; + } + T targetObject = null; + try { + targetObject = target.newInstance(); + BeanUtils.copyProperties(source, targetObject); + } catch (Exception e) { + log.error("convert error ", e); + } + + return targetObject; + } + + public static List sourceToTarget(Collection sourceList, Class target) { + if (sourceList == null) { + return null; + } + + List targetList = new ArrayList<>(sourceList.size()); + try { + for (Object source : sourceList) { + T targetObject = target.newInstance(); + BeanUtils.copyProperties(source, targetObject); + targetList.add(targetObject); + } + } catch (Exception e) { + log.error("convert error ", e); + } + + return targetList; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java new file mode 100644 index 000000000..9e5ef3e1c --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/DateUtils.java @@ -0,0 +1,63 @@ +package xiaozhi.common.utils; + +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 日期处理 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class DateUtils { + /** + * 时间格式(yyyy-MM-dd) + */ + public final static String DATE_PATTERN = "yyyy-MM-dd"; + /** + * 时间格式(yyyy-MM-dd HH:mm:ss) + */ + public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss"; + + /** + * 日期格式化 日期格式为:yyyy-MM-dd + * + * @param date 日期 + * @return 返回yyyy-MM-dd格式日期 + */ + public static String format(Date date) { + return format(date, DATE_PATTERN); + } + + /** + * 日期格式化 日期格式为:yyyy-MM-dd + * + * @param date 日期 + * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN + * @return 返回yyyy-MM-dd格式日期 + */ + public static String format(Date date, String pattern) { + if (date != null) { + SimpleDateFormat df = new SimpleDateFormat(pattern); + return df.format(date); + } + return null; + } + + /** + * 日期解析 + * + * @param date 日期 + * @param pattern 格式,如:DateUtils.DATE_TIME_PATTERN + * @return 返回Date + */ + public static Date parse(String date, String pattern) { + try { + return new SimpleDateFormat(pattern).parse(date); + } catch (ParseException e) { + e.printStackTrace(); + } + return null; + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/HttpContextUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/HttpContextUtils.java new file mode 100644 index 000000000..3629d5533 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/HttpContextUtils.java @@ -0,0 +1,107 @@ +package xiaozhi.common.utils; + +import xiaozhi.common.constant.Constant; +import jakarta.servlet.http.HttpServletRequest; +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.HttpHeaders; +import org.springframework.util.DigestUtils; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; + +/** + * Http + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class HttpContextUtils { + + public static HttpServletRequest getHttpServletRequest() { + RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); + if (requestAttributes == null) { + return null; + } + + return ((ServletRequestAttributes) requestAttributes).getRequest(); + } + + public static String getToken() { + HttpServletRequest httpRequest = getHttpServletRequest(); + String token = httpRequest.getHeader(Constant.TOKEN_HEADER); + + //如果header中不存在token,则从参数中获取token + if (StringUtils.isBlank(token)) { + token = httpRequest.getParameter(Constant.TOKEN_HEADER); + } + return token; + } + + public static Map getParameterMap(HttpServletRequest request) { + Enumeration parameters = request.getParameterNames(); + + Map params = new HashMap<>(); + while (parameters.hasMoreElements()) { + String parameter = parameters.nextElement(); + String value = request.getParameter(parameter); + if (StringUtils.isNotBlank(value)) { + params.put(parameter, value); + } + } + + return params; + } + + public static String getDomain() { + HttpServletRequest request = getHttpServletRequest(); + StringBuffer url = request.getRequestURL(); + return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString(); + } + + public static String getOrigin() { + HttpServletRequest request = getHttpServletRequest(); + return request.getHeader(HttpHeaders.ORIGIN); + } + + public static String getLanguage() { + //默认语言 + String defaultLanguage = "zh-CN"; + //request + HttpServletRequest request = getHttpServletRequest(); + if (request == null) { + return defaultLanguage; + } + + //请求语言 + defaultLanguage = request.getHeader(HttpHeaders.ACCEPT_LANGUAGE); + + return defaultLanguage; + } + + /** + * 获取客户端的唯一标识 + * + * @return + */ + public static String getClientCode() { + HttpServletRequest request = getHttpServletRequest(); + if (request == null) { + return null; + } + String reqId = request.getHeader("User-Agent").toLowerCase(); + String ipAddr = IpUtils.getIpAddr(request); + String date = DateUtils.format(new Date()); + reqId = DigestUtils.md5DigestAsHex((ipAddr + date + reqId).getBytes()); + return reqId; + } + + public static String getRequestURI() { + HttpServletRequest request = getHttpServletRequest(); + String url = request.getRequestURI(); + return url; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/IpUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/IpUtils.java new file mode 100644 index 000000000..307ad3b51 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/IpUtils.java @@ -0,0 +1,47 @@ +package xiaozhi.common.utils; + +import jakarta.servlet.http.HttpServletRequest; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; + +/** + * IP地址 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Slf4j +public class IpUtils { + /** + * 获取IP地址 + *

+ * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 + * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 + */ + public static String getIpAddr(HttpServletRequest request) { + String unknown = "unknown"; + String ip = null; + try { + ip = request.getHeader("x-forwarded-for"); + if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("Proxy-Client-IP"); + } + if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("WL-Proxy-Client-IP"); + } + if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_CLIENT_IP"); + } + if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getHeader("HTTP_X_FORWARDED_FOR"); + } + if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) { + ip = request.getRemoteAddr(); + } + } catch (Exception e) { + log.error("IPUtils ERROR ", e); + } + + return ip; + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java new file mode 100644 index 000000000..4a9082458 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/JsonUtils.java @@ -0,0 +1,68 @@ +package xiaozhi.common.utils; + +import cn.hutool.core.util.ArrayUtil; +import cn.hutool.core.util.StrUtil; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.util.ArrayList; +import java.util.List; + +/** + * JSON 工具类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class JsonUtils { + private static final ObjectMapper objectMapper = new ObjectMapper(); + + public static String toJsonString(Object object) { + try { + return objectMapper.writeValueAsString(object); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(String text, Class clazz) { + if (StrUtil.isEmpty(text)) { + return null; + } + try { + return objectMapper.readValue(text, clazz); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(byte[] bytes, Class clazz) { + if (ArrayUtil.isEmpty(bytes)) { + return null; + } + try { + return objectMapper.readValue(bytes, clazz); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static T parseObject(String text, TypeReference typeReference) { + try { + return objectMapper.readValue(text, typeReference); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static List parseArray(String text, Class clazz) { + if (StrUtil.isEmpty(text)) { + return new ArrayList<>(); + } + try { + return objectMapper.readValue(text, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz)); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java new file mode 100644 index 000000000..c346bf3da --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/MessageUtils.java @@ -0,0 +1,25 @@ +package xiaozhi.common.utils; + +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; + +/** + * 国际化 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class MessageUtils { + private static MessageSource messageSource; + + static { + messageSource = (MessageSource) SpringContextUtils.getBean("messageSource"); + } + + public static String getMessage(int code) { + return getMessage(code, new String[0]); + } + + public static String getMessage(int code, String... params) { + return messageSource.getMessage(code + "", params, LocaleContextHolder.getLocale()); + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/PropertiesUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/PropertiesUtils.java new file mode 100755 index 000000000..1064299be --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/PropertiesUtils.java @@ -0,0 +1,11 @@ +package xiaozhi.common.utils; + +import org.springframework.stereotype.Component; + +/** + * 获取配置文件信息 + * Copyright xin-nan.com + */ +@Component +public class PropertiesUtils { +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java b/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java new file mode 100644 index 000000000..c21bdbf9d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/Result.java @@ -0,0 +1,73 @@ +package xiaozhi.common.utils; + +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.page.PageData; +import xiaozhi.modules.security.user.SecurityUser; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import org.apache.commons.lang3.StringUtils; + +import java.io.Serializable; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 响应数据 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Data +@Schema(description = "响应") +public class Result implements Serializable { + + /** + * 编码:0表示成功,其他值表示失败 + */ + @Schema(description = "编码:0表示成功,其他值表示失败") + private int code = 0; + /** + * 消息内容 + */ + @Schema(description = "消息内容") + private String msg = "success"; + /** + * 响应数据 + */ + @Schema(description = "响应数据") + private T data; + + public Result ok(T data) { + this.setData(data); + return this; + } + + public boolean success() { + return code == 0; + } + + public Result error() { + this.code = ErrorCode.INTERNAL_SERVER_ERROR; + this.msg = MessageUtils.getMessage(this.code); + return this; + } + + public Result error(int code) { + this.code = code; + this.msg = MessageUtils.getMessage(this.code); + return this; + } + + public Result error(int code, String msg) { + this.code = code; + this.msg = msg; + return this; + } + + public Result error(String msg) { + this.code = ErrorCode.INTERNAL_SERVER_ERROR; + this.msg = msg; + return this; + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/SpringContextUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/SpringContextUtils.java new file mode 100644 index 000000000..52aec0b72 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/SpringContextUtils.java @@ -0,0 +1,45 @@ +package xiaozhi.common.utils; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +/** + * Spring Context 工具类 + */ +@Component +public class SpringContextUtils implements ApplicationContextAware { + public static ApplicationContext applicationContext; + + @Override + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + SpringContextUtils.applicationContext = applicationContext; + } + + public static Object getBean(String name) { + return applicationContext.getBean(name); + } + + public static T getBean(Class requiredType) { + return applicationContext.getBean(requiredType); + } + + public static T getBean(String name, Class requiredType) { + return applicationContext.getBean(name, requiredType); + } + + public static boolean containsBean(String name) { + return applicationContext.containsBean(name); + } + + public static boolean isSingleton(String name) { + return applicationContext.isSingleton(name); + } + + public static Class getType(String name) { + return applicationContext.getType(name); + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/TreeNode.java b/main/manager-api/src/main/java/xiaozhi/common/utils/TreeNode.java new file mode 100644 index 000000000..b60bc9cf0 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/TreeNode.java @@ -0,0 +1,30 @@ +package xiaozhi.common.utils; + +import lombok.Data; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +/** + * 树节点,所有需要实现树节点的,都需要继承该类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Data +public class TreeNode implements Serializable { + + /** + * 主键 + */ + private Long id; + /** + * 上级ID + */ + private Long pid; + /** + * 子节点列表 + */ + private List children = new ArrayList<>(); + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/utils/TreeUtils.java b/main/manager-api/src/main/java/xiaozhi/common/utils/TreeUtils.java new file mode 100644 index 000000000..766cb0295 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/utils/TreeUtils.java @@ -0,0 +1,71 @@ +package xiaozhi.common.utils; + +import xiaozhi.common.validator.AssertUtils; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 树形结构工具类,如:菜单、部门等 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class TreeUtils { + + /** + * 根据pid,构建树节点 + */ + public static List build(List treeNodes, Long pid) { + //pid不能为空 + AssertUtils.isNull(pid, "pid"); + + List treeList = new ArrayList<>(); + for (T treeNode : treeNodes) { + if (pid.equals(treeNode.getPid())) { + treeList.add(findChildren(treeNodes, treeNode)); + } + } + + return treeList; + } + + /** + * 查找子节点 + */ + private static T findChildren(List treeNodes, T rootNode) { + for (T treeNode : treeNodes) { + if (rootNode.getId().equals(treeNode.getPid())) { + rootNode.getChildren().add(findChildren(treeNodes, treeNode)); + } + } + return rootNode; + } + + /** + * 构建树节点 + */ + public static List build(List treeNodes) { + List result = new ArrayList<>(); + + //list转map + Map nodeMap = new LinkedHashMap<>(treeNodes.size()); + for (T treeNode : treeNodes) { + nodeMap.put(treeNode.getId(), treeNode); + } + + for (T node : nodeMap.values()) { + T parent = nodeMap.get(node.getPid()); + if (parent != null && !(node.getId().equals(parent.getId()))) { + parent.getChildren().add(node); + continue; + } + + result.add(node); + } + + return result; + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/AssertUtils.java b/main/manager-api/src/main/java/xiaozhi/common/validator/AssertUtils.java new file mode 100644 index 000000000..6a6b43e1c --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/AssertUtils.java @@ -0,0 +1,89 @@ +package xiaozhi.common.validator; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.ArrayUtil; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import org.apache.commons.lang3.StringUtils; + +import java.util.List; +import java.util.Map; + +/** + * 校验工具类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class AssertUtils { + + public static void isBlank(String str, String... params) { + isBlank(str, ErrorCode.NOT_NULL, params); + } + + public static void isBlank(String str, Integer code, String... params) { + if (code == null) { + throw new RenException(ErrorCode.NOT_NULL, "code"); + } + + if (StringUtils.isBlank(str)) { + throw new RenException(code, params); + } + } + + public static void isNull(Object object, String... params) { + isNull(object, ErrorCode.NOT_NULL, params); + } + + public static void isNull(Object object, Integer code, String... params) { + if (code == null) { + throw new RenException(ErrorCode.NOT_NULL, "code"); + } + + if (object == null) { + throw new RenException(code, params); + } + } + + public static void isArrayEmpty(Object[] array, String... params) { + isArrayEmpty(array, ErrorCode.NOT_NULL, params); + } + + public static void isArrayEmpty(Object[] array, Integer code, String... params) { + if (code == null) { + throw new RenException(ErrorCode.NOT_NULL, "code"); + } + + if (ArrayUtil.isEmpty(array)) { + throw new RenException(code, params); + } + } + + public static void isListEmpty(List list, String... params) { + isListEmpty(list, ErrorCode.NOT_NULL, params); + } + + public static void isListEmpty(List list, Integer code, String... params) { + if (code == null) { + throw new RenException(ErrorCode.NOT_NULL, "code"); + } + + if (CollUtil.isEmpty(list)) { + throw new RenException(code, params); + } + } + + public static void isMapEmpty(Map map, String... params) { + isMapEmpty(map, ErrorCode.NOT_NULL, params); + } + + public static void isMapEmpty(Map map, Integer code, String... params) { + if (code == null) { + throw new RenException(ErrorCode.NOT_NULL, "code"); + } + + if (MapUtil.isEmpty(map)) { + throw new RenException(code, params); + } + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/ValidatorUtils.java b/main/manager-api/src/main/java/xiaozhi/common/validator/ValidatorUtils.java new file mode 100644 index 000000000..80acb097a --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/ValidatorUtils.java @@ -0,0 +1,47 @@ +package xiaozhi.common.validator; + +import xiaozhi.common.exception.RenException; +import jakarta.validation.ConstraintViolation; +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator; +import org.springframework.context.i18n.LocaleContextHolder; +import org.springframework.context.support.ResourceBundleMessageSource; +import org.springframework.validation.beanvalidation.MessageSourceResourceBundleLocator; + +import java.util.Locale; +import java.util.Set; + +/** + * hibernate-validator校验工具类 + * 参考文档:http://docs.jboss.org/hibernate/validator/6.0/reference/en-US/html_single/ + */ +public class ValidatorUtils { + + private static ResourceBundleMessageSource getMessageSource() { + ResourceBundleMessageSource bundleMessageSource = new ResourceBundleMessageSource(); + bundleMessageSource.setDefaultEncoding("UTF-8"); + bundleMessageSource.setBasenames("i18n/validation"); + return bundleMessageSource; + } + + /** + * 校验对象 + * + * @param object 待校验对象 + * @param groups 待校验的组 + */ + public static void validateEntity(Object object, Class... groups) + throws RenException { + Locale.setDefault(LocaleContextHolder.getLocale()); + Validator validator = Validation.byDefaultProvider().configure().messageInterpolator( + new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(getMessageSource()))) + .buildValidatorFactory().getValidator(); + + Set> constraintViolations = validator.validate(object, groups); + if (!constraintViolations.isEmpty()) { + ConstraintViolation constraint = constraintViolations.iterator().next(); + throw new RenException(constraint.getMessage()); + } + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/group/AddGroup.java b/main/manager-api/src/main/java/xiaozhi/common/validator/group/AddGroup.java new file mode 100644 index 000000000..fd8290fde --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/group/AddGroup.java @@ -0,0 +1,8 @@ +package xiaozhi.common.validator.group; + +/** + * 新增 Group + */ +public interface AddGroup { + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/group/DefaultGroup.java b/main/manager-api/src/main/java/xiaozhi/common/validator/group/DefaultGroup.java new file mode 100644 index 000000000..60ddb7305 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/group/DefaultGroup.java @@ -0,0 +1,8 @@ +package xiaozhi.common.validator.group; + +/** + * 默认 Group + */ +public interface DefaultGroup { + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/validator/group/UpdateGroup.java b/main/manager-api/src/main/java/xiaozhi/common/validator/group/UpdateGroup.java new file mode 100644 index 000000000..220fda333 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/validator/group/UpdateGroup.java @@ -0,0 +1,8 @@ +package xiaozhi.common.validator.group; + +/** + * 修改 Group + */ +public interface UpdateGroup { + +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/SqlFilter.java b/main/manager-api/src/main/java/xiaozhi/common/xss/SqlFilter.java new file mode 100644 index 000000000..20291da1c --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/SqlFilter.java @@ -0,0 +1,44 @@ +package xiaozhi.common.xss; + +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import org.apache.commons.lang3.StringUtils; + +/** + * SQL过滤 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class SqlFilter { + + /** + * SQL注入过滤 + * + * @param str 待验证的字符串 + */ + public static String sqlInject(String str) { + if (StringUtils.isBlank(str)) { + return null; + } + //去掉'|"|;|\字符 + str = StringUtils.replace(str, "'", ""); + str = StringUtils.replace(str, "\"", ""); + str = StringUtils.replace(str, ";", ""); + str = StringUtils.replace(str, "\\", ""); + + //转换成小写 + str = str.toLowerCase(); + + //非法字符 + String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alter", "drop"}; + + //判断是否包含非法字符 + for (String keyword : keywords) { + if (str.contains(keyword)) { + throw new RenException(ErrorCode.INVALID_SYMBOL); + } + } + + return str; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssConfig.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssConfig.java new file mode 100644 index 000000000..f62786fd9 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssConfig.java @@ -0,0 +1,32 @@ +package xiaozhi.common.xss; + +import jakarta.servlet.DispatcherType; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.PathMatcher; + +/** + * XSS 配置文件 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Configuration +@EnableConfigurationProperties(XssProperties.class) +@ConditionalOnProperty(prefix = "renren.xss", value = "enabled") +public class XssConfig { + + @Bean + public FilterRegistrationBean xssFilter(XssProperties properties, PathMatcher pathMatcher) { + FilterRegistrationBean bean = new FilterRegistrationBean<>(); + bean.setDispatcherTypes(DispatcherType.REQUEST); + bean.setFilter(new XssFilter(properties, pathMatcher)); + bean.addUrlPatterns("/*"); + bean.setOrder(Integer.MAX_VALUE); + bean.setName("xssFilter"); + + return bean; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssFilter.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssFilter.java new file mode 100644 index 000000000..9a24d7eb7 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssFilter.java @@ -0,0 +1,48 @@ +package xiaozhi.common.xss; + +import jakarta.servlet.*; +import jakarta.servlet.http.HttpServletRequest; +import lombok.AllArgsConstructor; +import org.springframework.util.PathMatcher; + +import java.io.IOException; + +/** + * XSS过滤 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@AllArgsConstructor +public class XssFilter implements Filter { + private final XssProperties properties; + private final PathMatcher pathMatcher; + + @Override + public void init(FilterConfig config) throws ServletException { + } + + @Override + public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + throws IOException, ServletException { + HttpServletRequest httpServletRequest = (HttpServletRequest) request; + + // 放行 + if (shouldNotFilter(httpServletRequest)) { + chain.doFilter(request, response); + + return; + } + + chain.doFilter(new XssHttpServletRequestWrapper(httpServletRequest), response); + } + + private boolean shouldNotFilter(HttpServletRequest request) { + // 放行不过滤的URL + return properties.getExcludeUrls().stream().anyMatch(excludeUrl -> pathMatcher.match(excludeUrl, request.getServletPath())); + } + + @Override + public void destroy() { + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssHttpServletRequestWrapper.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssHttpServletRequestWrapper.java new file mode 100644 index 000000000..1306c2dd5 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssHttpServletRequestWrapper.java @@ -0,0 +1,118 @@ +package xiaozhi.common.xss; + +import cn.hutool.core.io.IoUtil; +import jakarta.servlet.ReadListener; +import jakarta.servlet.ServletInputStream; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletRequestWrapper; +import org.apache.commons.lang3.StringUtils; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.LinkedHashMap; +import java.util.Map; + + +/** + * XSS过滤处理 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { + + public XssHttpServletRequestWrapper(HttpServletRequest request) { + super(request); + } + + @Override + public ServletInputStream getInputStream() throws IOException { + //非json类型,直接返回 + if (!MediaType.APPLICATION_JSON_VALUE.equalsIgnoreCase(super.getHeader(HttpHeaders.CONTENT_TYPE))) { + return super.getInputStream(); + } + + //为空,直接返回 + String json = IoUtil.readUtf8(super.getInputStream()); + if (StringUtils.isBlank(json)) { + return super.getInputStream(); + } + + //xss过滤 + json = xssEncode(json); + final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); + return new ServletInputStream() { + @Override + public boolean isFinished() { + return true; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener readListener) { + + } + + @Override + public int read() { + return bis.read(); + } + }; + } + + @Override + public String getParameter(String name) { + String value = super.getParameter(xssEncode(name)); + if (StringUtils.isNotBlank(value)) { + value = xssEncode(value); + } + return value; + } + + @Override + public String[] getParameterValues(String name) { + String[] parameters = super.getParameterValues(name); + if (parameters == null || parameters.length == 0) { + return null; + } + + for (int i = 0; i < parameters.length; i++) { + parameters[i] = xssEncode(parameters[i]); + } + return parameters; + } + + @Override + public Map getParameterMap() { + Map map = new LinkedHashMap<>(); + Map parameters = super.getParameterMap(); + for (String key : parameters.keySet()) { + String[] values = parameters.get(key); + for (int i = 0; i < values.length; i++) { + values[i] = xssEncode(values[i]); + } + map.put(key, values); + } + return map; + } + + @Override + public String getHeader(String name) { + String value = super.getHeader(xssEncode(name)); + if (StringUtils.isNotBlank(value)) { + value = xssEncode(value); + } + return value; + } + + private String xssEncode(String input) { + return XssUtils.filter(input); + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssProperties.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssProperties.java new file mode 100644 index 000000000..bf36ddbed --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssProperties.java @@ -0,0 +1,25 @@ +package xiaozhi.common.xss; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; + +import java.util.Collections; +import java.util.List; + +/** + * XSS 配置项 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Data +@ConfigurationProperties(prefix = "renren.xss") +public class XssProperties { + /** + * 是否开启 XSS + */ + private boolean enabled; + /** + * 排除的URL列表 + */ + private List excludeUrls = Collections.emptyList(); +} diff --git a/main/manager-api/src/main/java/xiaozhi/common/xss/XssUtils.java b/main/manager-api/src/main/java/xiaozhi/common/xss/XssUtils.java new file mode 100644 index 000000000..5d4ac6b35 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/common/xss/XssUtils.java @@ -0,0 +1,62 @@ +package xiaozhi.common.xss; + +import org.jsoup.Jsoup; +import org.jsoup.safety.Safelist; + +/** + * XSS过滤工具类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class XssUtils extends Safelist { + + /** + * XSS过滤 + */ + public static String filter(String html) { + return Jsoup.clean(html, xssWhitelist()); + } + + /** + * XSS过滤白名单 + */ + private static Safelist xssWhitelist() { + return new Safelist() + //支持的标签 + .addTags("a", "b", "blockquote", "br", "caption", "cite", "code", "col", "colgroup", "dd", "div", "dl", + "dt", "em", "h1", "h2", "h3", "h4", "h5", "h6", "i", "img", "li", "ol", "p", "pre", "q", "small", + "strike", "strong", "sub", "sup", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "u", "ul", + "embed", "object", "param", "span") + + //支持的标签属性 + .addAttributes("a", "href", "class", "style", "target", "rel", "nofollow") + .addAttributes("blockquote", "cite") + .addAttributes("code", "class", "style") + .addAttributes("col", "span", "width") + .addAttributes("colgroup", "span", "width") + .addAttributes("img", "align", "alt", "height", "src", "title", "width", "class", "style") + .addAttributes("ol", "start", "type") + .addAttributes("q", "cite") + .addAttributes("table", "summary", "width", "class", "style") + .addAttributes("tr", "abbr", "axis", "colspan", "rowspan", "width", "style") + .addAttributes("td", "abbr", "axis", "colspan", "rowspan", "width", "style") + .addAttributes("th", "abbr", "axis", "colspan", "rowspan", "scope", "width", "style") + .addAttributes("ul", "type", "style") + .addAttributes("pre", "class", "style") + .addAttributes("div", "class", "id", "style") + .addAttributes("embed", "src", "wmode", "flashvars", "pluginspage", "allowFullScreen", "allowfullscreen", + "quality", "width", "height", "align", "allowScriptAccess", "allowscriptaccess", "allownetworking", "type") + .addAttributes("object", "type", "id", "name", "data", "width", "height", "style", "classid", "codebase") + .addAttributes("param", "name", "value") + .addAttributes("span", "class", "style") + + //标签属性对应的协议 + .addProtocols("a", "href", "ftp", "http", "https", "mailto") + .addProtocols("img", "src", "http", "https") + .addProtocols("blockquote", "cite", "http", "https") + .addProtocols("cite", "cite", "http", "https") + .addProtocols("q", "cite", "http", "https") + .addProtocols("embed", "src", "http", "https"); + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/FilterConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/FilterConfig.java new file mode 100644 index 000000000..607cb68b5 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/FilterConfig.java @@ -0,0 +1,28 @@ +package xiaozhi.modules.security.config; + +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.filter.DelegatingFilterProxy; + + +/** + * Filter配置 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Configuration +public class FilterConfig { + + @Bean + public FilterRegistrationBean shiroFilterRegistration() { + FilterRegistrationBean registration = new FilterRegistrationBean<>(); + registration.setFilter(new DelegatingFilterProxy("shiroFilter")); + //该值缺省为false,表示生命周期由SpringApplicationContext管理,设置为true则表示由ServletContainer管理 + registration.addInitParameter("targetFilterLifecycle", "true"); + registration.setEnabled(true); + registration.setOrder(Integer.MAX_VALUE - 1); + registration.addUrlPatterns("/*"); + return registration; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java new file mode 100644 index 000000000..678c546ea --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/ShiroConfig.java @@ -0,0 +1,89 @@ +package xiaozhi.modules.security.config; + +import xiaozhi.modules.security.oauth2.Oauth2Filter; +import xiaozhi.modules.security.oauth2.Oauth2Realm; +import jakarta.servlet.Filter; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.session.mgt.SessionManager; +import org.apache.shiro.spring.LifecycleBeanPostProcessor; +import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.config.ShiroFilterConfiguration; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.apache.shiro.web.session.mgt.DefaultWebSessionManager; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * Shiro的配置文件 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Configuration +public class ShiroConfig { + + @Bean + public DefaultWebSessionManager sessionManager() { + DefaultWebSessionManager sessionManager = new DefaultWebSessionManager(); + sessionManager.setSessionValidationSchedulerEnabled(false); + sessionManager.setSessionIdUrlRewritingEnabled(false); + + return sessionManager; + } + + @Bean("securityManager") + public SecurityManager securityManager(Oauth2Realm oAuth2Realm, SessionManager sessionManager) { + DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); + securityManager.setRealm(oAuth2Realm); + securityManager.setSessionManager(sessionManager); + securityManager.setRememberMeManager(null); + return securityManager; + } + + @Bean("shiroFilter") + public ShiroFilterFactoryBean shirFilter(SecurityManager securityManager) { + ShiroFilterConfiguration config = new ShiroFilterConfiguration(); + config.setFilterOncePerRequest(true); + + ShiroFilterFactoryBean shiroFilter = new ShiroFilterFactoryBean(); + shiroFilter.setSecurityManager(securityManager); + shiroFilter.setShiroFilterConfiguration(config); + + //oauth过滤 + Map filters = new HashMap<>(); + filters.put("oauth2", new Oauth2Filter()); + shiroFilter.setFilters(filters); + + Map filterMap = new LinkedHashMap<>(); + filterMap.put("/webjars/**", "anon"); + filterMap.put("/druid/**", "anon"); + filterMap.put("/login", "anon"); + filterMap.put("/publicKey", "anon"); + filterMap.put("/v3/api-docs/**", "anon"); + filterMap.put("/doc.html", "anon"); + filterMap.put("/sys/oss/download/**", "anon"); + filterMap.put("/captcha", "anon"); + filterMap.put("/favicon.ico", "anon"); + filterMap.put("/mobile/**", "anon"); + filterMap.put("/**", "oauth2"); + shiroFilter.setFilterChainDefinitionMap(filterMap); + + return shiroFilter; + } + + @Bean("lifecycleBeanPostProcessor") + public LifecycleBeanPostProcessor lifecycleBeanPostProcessor() { + return new LifecycleBeanPostProcessor(); + } + + @Bean + public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { + AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor(); + advisor.setSecurityManager(securityManager); + return advisor; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java b/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java new file mode 100644 index 000000000..a086e9536 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/config/WebMvcConfig.java @@ -0,0 +1,65 @@ +package xiaozhi.modules.security.config; + +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.ByteArrayHttpMessageConverter; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.ResourceHttpMessageConverter; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import java.util.List; +import java.util.TimeZone; + +@Configuration +public class WebMvcConfig implements WebMvcConfigurer { + + @Override + public void addCorsMappings(CorsRegistry registry) { + registry.addMapping("/**") + .allowedOriginPatterns("*") + .allowCredentials(true) + .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") + .maxAge(3600); + } + + @Override + public void configureMessageConverters(List> converters) { + converters.add(new ByteArrayHttpMessageConverter()); + converters.add(new StringHttpMessageConverter()); + converters.add(new ResourceHttpMessageConverter()); + converters.add(new AllEncompassingFormHttpMessageConverter()); + converters.add(new StringHttpMessageConverter()); + converters.add(jackson2HttpMessageConverter()); + } + + @Bean + public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() { + MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); + ObjectMapper mapper = new ObjectMapper(); + + //忽略未知属性 + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + + //日期格式转换 + //mapper.setDateFormat(new SimpleDateFormat(DateUtils.DATE_TIME_PATTERN)); + mapper.setTimeZone(TimeZone.getTimeZone("GMT+8")); + + //Long类型转String类型 + SimpleModule simpleModule = new SimpleModule(); + simpleModule.addSerializer(Long.class, ToStringSerializer.instance); + simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance); + mapper.registerModule(simpleModule); + + converter.setObjectMapper(mapper); + return converter; + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java new file mode 100644 index 000000000..82051dab9 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/controller/LoginController.java @@ -0,0 +1,55 @@ +package xiaozhi.modules.security.controller; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.AllArgsConstructor; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.common.utils.PropertiesUtils; +import xiaozhi.common.utils.Result; +import xiaozhi.common.validator.AssertUtils; +import xiaozhi.modules.security.dto.LoginDTO; +import xiaozhi.modules.security.service.CaptchaService; +import xiaozhi.modules.security.service.SysUserTokenService; +import xiaozhi.modules.sys.service.SysParamsService; +import xiaozhi.modules.sys.service.SysUserService; + +import java.io.IOException; + +/** + * 登录 + */ +@AllArgsConstructor +@RestController +@Tag(name = "登录管理") +public class LoginController { + private final SysUserService sysUserService; + private final SysUserTokenService sysUserTokenService; + private final CaptchaService captchaService; + private final RedisUtils redisUtils; + private final SysParamsService sysParamsService; + private final PropertiesUtils propertiesUtils; + + @GetMapping("captcha") + @Operation(summary = "验证码") + public void captcha(HttpServletResponse response, String uuid) throws IOException { + //uuid不能为空 + AssertUtils.isBlank(uuid, ErrorCode.IDENTIFIER_NOT_NULL); + + //生成验证码 + captchaService.create(response, uuid); + } + + @PostMapping("login") + @Operation(summary = "登录") + public Result login(HttpServletRequest request, @RequestBody LoginDTO login) { + return sysUserTokenService.createToken(1L); + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/dao/SysUserTokenDao.java b/main/manager-api/src/main/java/xiaozhi/modules/security/dao/SysUserTokenDao.java new file mode 100644 index 000000000..044568e5f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/dao/SysUserTokenDao.java @@ -0,0 +1,23 @@ +package xiaozhi.modules.security.dao; + +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import xiaozhi.common.dao.BaseDao; +import xiaozhi.modules.security.entity.SysUserTokenEntity; + +import java.util.Date; + +/** + * 系统用户Token + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Mapper +public interface SysUserTokenDao extends BaseDao { + + SysUserTokenEntity getByToken(String token); + + SysUserTokenEntity getByUserId(Long userId); + + void logout(@Param("userId") Long userId, @Param("expireDate") Date expireDate); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java new file mode 100644 index 000000000..67f50f198 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/dto/LoginDTO.java @@ -0,0 +1,32 @@ +package xiaozhi.modules.security.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +import java.io.Serializable; + +/** + * 登录表单 + */ +@Data +@Schema(description = "登录表单") +public class LoginDTO implements Serializable { + + @Schema(description = "用户名", required = true) + @NotBlank(message = "{sysuser.username.require}") + private String username; + + @Schema(description = "密码") + @NotBlank(message = "{sysuser.password.require}") + private String password; + + @Schema(description = "验证码") + @NotBlank(message = "{sysuser.captcha.require}") + private String captcha; + + @Schema(description = "唯一标识") + @NotBlank(message = "{sysuser.uuid.require}") + private String uuid; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/entity/SysUserTokenEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/security/entity/SysUserTokenEntity.java new file mode 100644 index 000000000..fb96f88c2 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/entity/SysUserTokenEntity.java @@ -0,0 +1,46 @@ +package xiaozhi.modules.security.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 系统用户Token + */ +@Data +@TableName("sys_user_token") +public class SysUserTokenEntity implements Serializable { + + /** + * id + */ + @TableId + private Long id; + /** + * 用户ID + */ + private Long userId; + /** + * 用户token + */ + private String token; + /** + * 过期时间 + */ + private Date expireDate; + /** + * 更新时间 + */ + private Date updateDate; + /** + * 创建时间 + */ + @TableField(fill = FieldFill.INSERT) + private Date createDate; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java new file mode 100644 index 000000000..3d8cf0cb2 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Filter.java @@ -0,0 +1,101 @@ +package xiaozhi.modules.security.oauth2; + +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.web.filter.authc.AuthenticatingFilter; +import org.springframework.web.bind.annotation.RequestMethod; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.utils.HttpContextUtils; +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.common.utils.Result; + +import java.io.IOException; + +/** + * oauth2过滤器 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class Oauth2Filter extends AuthenticatingFilter { + + @Override + protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception { + //获取请求token + String token = getRequestToken((HttpServletRequest) request); + + if (StringUtils.isBlank(token)) { + return null; + } + + return new Oauth2Token(token); + } + + @Override + protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { + if (((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name())) { + return true; + } + + return false; + } + + @Override + protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { + //获取请求token,如果token不存在,直接返回401 + String token = getRequestToken((HttpServletRequest) request); + if (StringUtils.isBlank(token)) { + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.setContentType("application/json;charset=utf-8"); + httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); + httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); + + String json = JsonUtils.toJsonString(new Result().error(ErrorCode.UNAUTHORIZED)); + + httpResponse.getWriter().print(json); + + return false; + } + + return executeLogin(request, response); + } + + @Override + protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) { + HttpServletResponse httpResponse = (HttpServletResponse) response; + httpResponse.setContentType("application/json;charset=utf-8"); + httpResponse.setHeader("Access-Control-Allow-Credentials", "true"); + httpResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin()); + try { + //处理登录失败的异常 + Throwable throwable = e.getCause() == null ? e : e.getCause(); + Result r = new Result().error(ErrorCode.UNAUTHORIZED, throwable.getMessage()); + + String json = JsonUtils.toJsonString(r); + httpResponse.getWriter().print(json); + } catch (IOException e1) { + + } + + return false; + } + + /** + * 获取请求的token + */ + private String getRequestToken(HttpServletRequest httpRequest) { + //从header中获取token + String token = httpRequest.getHeader(Constant.TOKEN_HEADER); + + //如果header中不存在token,则从参数中获取token + if (StringUtils.isBlank(token)) { + token = httpRequest.getParameter(Constant.TOKEN_HEADER); + } + return token; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java new file mode 100644 index 000000000..933724a1b --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Realm.java @@ -0,0 +1,86 @@ +package xiaozhi.modules.security.oauth2; + +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.MessageUtils; +import xiaozhi.modules.security.entity.SysUserTokenEntity; +import xiaozhi.modules.security.service.ShiroService; +import xiaozhi.modules.sys.entity.SysUserEntity; +import jakarta.annotation.Resource; +import org.apache.shiro.authc.*; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Set; + +/** + * 认证 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +@Component +public class Oauth2Realm extends AuthorizingRealm { + @Lazy + @Resource + private ShiroService shiroService; + + @Override + public boolean supports(AuthenticationToken token) { + return token instanceof Oauth2Token; + } + + /** + * 授权(验证权限时调用) + */ + @Override + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) { + UserDetail user = (UserDetail) principals.getPrimaryPrincipal(); + + //用户权限列表 + Set permsSet = shiroService.getUserPermissions(user); + + SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); + info.setStringPermissions(permsSet); + return info; + } + + /** + * 认证(登录时调用) + */ + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { + String accessToken = (String) token.getPrincipal(); + + //根据accessToken,查询用户信息 + SysUserTokenEntity tokenEntity = shiroService.getByToken(accessToken); + //token失效 + if (tokenEntity == null || tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) { + throw new IncorrectCredentialsException(MessageUtils.getMessage(ErrorCode.TOKEN_INVALID)); + } + + //查询用户信息 + SysUserEntity userEntity = shiroService.getUser(tokenEntity.getUserId()); + + //转换成UserDetail对象 + UserDetail userDetail = ConvertUtils.sourceToTarget(userEntity, UserDetail.class); + + //获取用户对应的部门数据权限 + userDetail.setDeptIdList(null); + userDetail.setToken(accessToken); + + //账号锁定 + if (userDetail.getStatus() == 0) { + throw new LockedAccountException(MessageUtils.getMessage(ErrorCode.ACCOUNT_LOCK)); + } + + SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userDetail, accessToken, getName()); + return info; + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Token.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Token.java new file mode 100644 index 000000000..62adc903c --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/Oauth2Token.java @@ -0,0 +1,26 @@ +package xiaozhi.modules.security.oauth2; + +import org.apache.shiro.authc.AuthenticationToken; + +/** + * token + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class Oauth2Token implements AuthenticationToken { + private String token; + + public Oauth2Token(String token) { + this.token = token; + } + + @Override + public String getPrincipal() { + return token; + } + + @Override + public Object getCredentials() { + return token; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/TokenGenerator.java b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/TokenGenerator.java new file mode 100644 index 000000000..0ca1cede6 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/oauth2/TokenGenerator.java @@ -0,0 +1,44 @@ +package xiaozhi.modules.security.oauth2; + +import xiaozhi.common.exception.RenException; + +import java.security.MessageDigest; +import java.util.UUID; + +/** + * 生成token + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class TokenGenerator { + + public static String generateValue() { + return generateValue(UUID.randomUUID().toString()); + } + + private static final char[] HEX_CODE = "0123456789abcdef".toCharArray(); + + public static String toHexString(byte[] data) { + if (data == null) { + return null; + } + StringBuilder r = new StringBuilder(data.length * 2); + for (byte b : data) { + r.append(HEX_CODE[(b >> 4) & 0xF]); + r.append(HEX_CODE[(b & 0xF)]); + } + return r.toString(); + } + + public static String generateValue(String param) { + try { + MessageDigest algorithm = MessageDigest.getInstance("MD5"); + algorithm.reset(); + algorithm.update(param.getBytes()); + byte[] messageDigest = algorithm.digest(); + return toHexString(messageDigest); + } catch (Exception e) { + throw new RenException("token invalid", e); + } + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/password/BCrypt.java b/main/manager-api/src/main/java/xiaozhi/modules/security/password/BCrypt.java new file mode 100644 index 000000000..6a9efff97 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/password/BCrypt.java @@ -0,0 +1,672 @@ +package xiaozhi.modules.security.password; + +import java.io.ByteArrayOutputStream; +import java.io.UnsupportedEncodingException; +import java.security.SecureRandom; + +/** + * BCrypt implements OpenBSD-style Blowfish password hashing using the scheme described in + * "A Future-Adaptable Password Scheme" by Niels Provos and David Mazieres. + *

+ * This password hashing system tries to thwart off-line password cracking using a + * computationally-intensive hashing algorithm, based on Bruce Schneier's Blowfish cipher. + * The work factor of the algorithm is parameterised, so it can be increased as computers + * get faster. + *

+ * Usage is really simple. To hash a password for the first time, call the hashpw method + * with a random salt, like this: + *

+ * + * String pw_hash = BCrypt.hashpw(plain_password, BCrypt.gensalt());
+ *
+ *

+ * To check whether a plaintext password matches one that has been hashed previously, use + * the checkpw method: + *

+ * + * if (BCrypt.checkpw(candidate_password, stored_hash))
+ *     System.out.println("It matches");
+ * else
+ *     System.out.println("It does not match");
+ *
+ *

+ * The gensalt() method takes an optional parameter (log_rounds) that determines the + * computational complexity of the hashing: + *

+ * + * String strong_salt = BCrypt.gensalt(10)
+ * String stronger_salt = BCrypt.gensalt(12)
+ *
+ *

+ * The amount of work increases exponentially (2**log_rounds), so each increment is twice + * as much work. The default log_rounds is 10, and the valid range is 4 to 31. + * + * @author Damien Miller + */ +public class BCrypt { + // BCrypt parameters + + private static final int GENSALT_DEFAULT_LOG2_ROUNDS = 10; + private static final int BCRYPT_SALT_LEN = 16; + // Blowfish parameters + private static final int BLOWFISH_NUM_ROUNDS = 16; + // Initial contents of key schedule + private static final int P_orig[] = {0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, + 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, + 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, + 0x9216d5d9, 0x8979fb1b}; + private static final int S_orig[] = {0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, + 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, + 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, + 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, + 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, + 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, + 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, + 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, + 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, + 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, + 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, + 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, + 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, + 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, + 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, + 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, + 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, + 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, + 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, + 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, + 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, + 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, + 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, + 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, + 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, + 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, + 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, + 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, + 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, + 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, + 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, + 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, + 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, + 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, + 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, + 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, + 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, + 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, + 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, + 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, + 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, + 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, + 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, + 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, + 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, + 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, + 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, + 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, + 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, + 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, + 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, + 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, + 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, + 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, + 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, + 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, + 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, + 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, + 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, + 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, + 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, + 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, + 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, + 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, + 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, + 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, + 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, + 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, + 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, + 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, + 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, + 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, + 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, + 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, + 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, + 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, + 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, + 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, + 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, + 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, + 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, + 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, + 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, + 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, + 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, + 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, 0xe93d5a68, 0x948140f7, + 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, + 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, + 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, + 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, + 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, + 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, + 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, + 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, + 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, + 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, + 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, + 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, + 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, + 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, + 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, + 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, + 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, + 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, + 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, + 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, + 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, + 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, + 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, + 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, + 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, + 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, + 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, + 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, + 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, + 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, + 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, + 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, + 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, + 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, + 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, + 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, + 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, + 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, + 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, + 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, + 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, + 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, + 0x670efa8e, 0x406000e0, 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, + 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, + 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, + 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, + 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, + 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, + 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, + 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, + 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, + 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, + 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, + 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, + 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, + 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, + 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, + 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, + 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, + 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, + 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, + 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, + 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, + 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, + 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, + 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, + 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, + 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, + 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, + 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, + 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, + 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, + 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, + 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, + 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, + 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, + 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, + 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, + 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, + 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, + 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, + 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, + 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, + 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, + 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6}; + // bcrypt IV: "OrpheanBeholderScryDoubt" + static private final int bf_crypt_ciphertext[] = {0x4f727068, 0x65616e42, + 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274}; + // Table for Base64 encoding + static private final char base64_code[] = {'.', '/', 'A', 'B', 'C', 'D', 'E', 'F', + 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', + 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', + 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', + 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}; + // Table for Base64 decoding + static private final byte index_64[] = {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 54, 55, + 56, 57, 58, 59, 60, 61, 62, 63, -1, -1, -1, -1, -1, -1, -1, 2, 3, 4, 5, 6, 7, + 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, + -1, -1, -1, -1, -1, -1, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, -1, -1, -1, -1, -1}; + static final int MIN_LOG_ROUNDS = 4; + static final int MAX_LOG_ROUNDS = 31; + // Expanded Blowfish key + private int P[]; + private int S[]; + + /** + * Encode a byte array using bcrypt's slightly-modified base64 encoding scheme. Note + * that this is not compatible with the standard MIME-base64 + * encoding. + * + * @param d the byte array to encode + * @param len the number of bytes to encode + * @param rs the destination buffer for the base64-encoded string + * @throws IllegalArgumentException if the length is invalid + */ + static void encode_base64(byte d[], int len, StringBuilder rs) + throws IllegalArgumentException { + int off = 0; + int c1, c2; + + if (len <= 0 || len > d.length) { + throw new IllegalArgumentException("Invalid len"); + } + + while (off < len) { + c1 = d[off++] & 0xff; + rs.append(base64_code[(c1 >> 2) & 0x3f]); + c1 = (c1 & 0x03) << 4; + if (off >= len) { + rs.append(base64_code[c1 & 0x3f]); + break; + } + c2 = d[off++] & 0xff; + c1 |= (c2 >> 4) & 0x0f; + rs.append(base64_code[c1 & 0x3f]); + c1 = (c2 & 0x0f) << 2; + if (off >= len) { + rs.append(base64_code[c1 & 0x3f]); + break; + } + c2 = d[off++] & 0xff; + c1 |= (c2 >> 6) & 0x03; + rs.append(base64_code[c1 & 0x3f]); + rs.append(base64_code[c2 & 0x3f]); + } + } + + /** + * Look up the 3 bits base64-encoded by the specified character, range-checking + * against conversion table + * + * @param x the base64-encoded value + * @return the decoded value of x + */ + private static byte char64(char x) { + if (x > index_64.length) { + return -1; + } + return index_64[x]; + } + + /** + * Decode a string encoded using bcrypt's base64 scheme to a byte array. Note that + * this is *not* compatible with the standard MIME-base64 encoding. + * + * @param s the string to decode + * @param maxolen the maximum number of bytes to decode + * @return an array containing the decoded bytes + * @throws IllegalArgumentException if maxolen is invalid + */ + static byte[] decode_base64(String s, int maxolen) throws IllegalArgumentException { + ByteArrayOutputStream out = new ByteArrayOutputStream(maxolen); + int off = 0, slen = s.length(), olen = 0; + byte c1, c2, c3, c4, o; + + if (maxolen <= 0) { + throw new IllegalArgumentException("Invalid maxolen"); + } + + while (off < slen - 1 && olen < maxolen) { + c1 = char64(s.charAt(off++)); + c2 = char64(s.charAt(off++)); + if (c1 == -1 || c2 == -1) { + break; + } + o = (byte) (c1 << 2); + o |= (c2 & 0x30) >> 4; + out.write(o); + if (++olen >= maxolen || off >= slen) { + break; + } + c3 = char64(s.charAt(off++)); + if (c3 == -1) { + break; + } + o = (byte) ((c2 & 0x0f) << 4); + o |= (c3 & 0x3c) >> 2; + out.write(o); + if (++olen >= maxolen || off >= slen) { + break; + } + c4 = char64(s.charAt(off++)); + o = (byte) ((c3 & 0x03) << 6); + o |= c4; + out.write(o); + ++olen; + } + + return out.toByteArray(); + } + + /** + * Blowfish encipher a single 64-bit block encoded as two 32-bit halves + * + * @param lr an array containing the two 32-bit half blocks + * @param off the position in the array of the blocks + */ + private final void encipher(int lr[], int off) { + int i, n, l = lr[off], r = lr[off + 1]; + + l ^= P[0]; + for (i = 0; i <= BLOWFISH_NUM_ROUNDS - 2; ) { + // Feistel substitution on left word + n = S[(l >> 24) & 0xff]; + n += S[0x100 | ((l >> 16) & 0xff)]; + n ^= S[0x200 | ((l >> 8) & 0xff)]; + n += S[0x300 | (l & 0xff)]; + r ^= n ^ P[++i]; + + // Feistel substitution on right word + n = S[(r >> 24) & 0xff]; + n += S[0x100 | ((r >> 16) & 0xff)]; + n ^= S[0x200 | ((r >> 8) & 0xff)]; + n += S[0x300 | (r & 0xff)]; + l ^= n ^ P[++i]; + } + lr[off] = r ^ P[BLOWFISH_NUM_ROUNDS + 1]; + lr[off + 1] = l; + } + + /** + * Cycically extract a word of key material + * + * @param data the string to extract the data from + * @param offp a "pointer" (as a one-entry array) to the current offset into data + * @return the next word of material from data + */ + private static int streamtoword(byte data[], int offp[]) { + int i; + int word = 0; + int off = offp[0]; + + for (i = 0; i < 4; i++) { + word = (word << 8) | (data[off] & 0xff); + off = (off + 1) % data.length; + } + + offp[0] = off; + return word; + } + + /** + * Initialise the Blowfish key schedule + */ + private void init_key() { + P = (int[]) P_orig.clone(); + S = (int[]) S_orig.clone(); + } + + /** + * Key the Blowfish cipher + * + * @param key an array containing the key + */ + private void key(byte key[]) { + int i; + int koffp[] = {0}; + int lr[] = {0, 0}; + int plen = P.length, slen = S.length; + + for (i = 0; i < plen; i++) { + P[i] = P[i] ^ streamtoword(key, koffp); + } + + for (i = 0; i < plen; i += 2) { + encipher(lr, 0); + P[i] = lr[0]; + P[i + 1] = lr[1]; + } + + for (i = 0; i < slen; i += 2) { + encipher(lr, 0); + S[i] = lr[0]; + S[i + 1] = lr[1]; + } + } + + /** + * Perform the "enhanced key schedule" step described by Provos and Mazieres in + * "A Future-Adaptable Password Scheme" http://www.openbsd.org/papers/bcrypt-paper.ps + * + * @param data salt information + * @param key password information + */ + private void ekskey(byte data[], byte key[]) { + int i; + int koffp[] = {0}, doffp[] = {0}; + int lr[] = {0, 0}; + int plen = P.length, slen = S.length; + + for (i = 0; i < plen; i++) { + P[i] = P[i] ^ streamtoword(key, koffp); + } + + for (i = 0; i < plen; i += 2) { + lr[0] ^= streamtoword(data, doffp); + lr[1] ^= streamtoword(data, doffp); + encipher(lr, 0); + P[i] = lr[0]; + P[i + 1] = lr[1]; + } + + for (i = 0; i < slen; i += 2) { + lr[0] ^= streamtoword(data, doffp); + lr[1] ^= streamtoword(data, doffp); + encipher(lr, 0); + S[i] = lr[0]; + S[i + 1] = lr[1]; + } + } + + static long roundsForLogRounds(int log_rounds) { + if (log_rounds < 4 || log_rounds > 31) { + throw new IllegalArgumentException("Bad number of rounds"); + } + return 1L << log_rounds; + } + + /** + * Perform the central password hashing step in the bcrypt scheme + * + * @param password the password to hash + * @param salt the binary salt to hash with the password + * @param log_rounds the binary logarithm of the number of rounds of hashing to apply + * @return an array containing the binary hashed password + */ + private byte[] crypt_raw(byte password[], byte salt[], int log_rounds) { + int cdata[] = (int[]) bf_crypt_ciphertext.clone(); + int clen = cdata.length; + byte ret[]; + + long rounds = roundsForLogRounds(log_rounds); + + init_key(); + ekskey(salt, password); + for (long i = 0; i < rounds; i++) { + key(password); + key(salt); + } + + for (int i = 0; i < 64; i++) { + for (int j = 0; j < (clen >> 1); j++) { + encipher(cdata, j << 1); + } + } + + ret = new byte[clen * 4]; + for (int i = 0, j = 0; i < clen; i++) { + ret[j++] = (byte) ((cdata[i] >> 24) & 0xff); + ret[j++] = (byte) ((cdata[i] >> 16) & 0xff); + ret[j++] = (byte) ((cdata[i] >> 8) & 0xff); + ret[j++] = (byte) (cdata[i] & 0xff); + } + return ret; + } + + /** + * Hash a password using the OpenBSD bcrypt scheme + * + * @param password the password to hash + * @param salt the salt to hash with (perhaps generated using BCrypt.gensalt) + * @return the hashed password + * @throws IllegalArgumentException if invalid salt is passed + */ + public static String hashpw(String password, String salt) throws IllegalArgumentException { + BCrypt B; + String real_salt; + byte passwordb[], saltb[], hashed[]; + char minor = (char) 0; + int rounds, off = 0; + StringBuilder rs = new StringBuilder(); + + if (salt == null) { + throw new IllegalArgumentException("salt cannot be null"); + } + + int saltLength = salt.length(); + + if (saltLength < 28) { + throw new IllegalArgumentException("Invalid salt"); + } + + if (salt.charAt(0) != '$' || salt.charAt(1) != '2') { + throw new IllegalArgumentException("Invalid salt version"); + } + if (salt.charAt(2) == '$') { + off = 3; + } else { + minor = salt.charAt(2); + if (minor != 'a' || salt.charAt(3) != '$') { + throw new IllegalArgumentException("Invalid salt revision"); + } + off = 4; + } + + if (saltLength - off < 25) { + throw new IllegalArgumentException("Invalid salt"); + } + + // Extract number of rounds + if (salt.charAt(off + 2) > '$') { + throw new IllegalArgumentException("Missing salt rounds"); + } + rounds = Integer.parseInt(salt.substring(off, off + 2)); + + real_salt = salt.substring(off + 3, off + 25); + try { + passwordb = (password + (minor >= 'a' ? "\000" : "")).getBytes("UTF-8"); + } catch (UnsupportedEncodingException uee) { + throw new AssertionError("UTF-8 is not supported"); + } + + saltb = decode_base64(real_salt, BCRYPT_SALT_LEN); + + B = new BCrypt(); + hashed = B.crypt_raw(passwordb, saltb, rounds); + + rs.append("$2"); + if (minor >= 'a') { + rs.append(minor); + } + rs.append("$"); + if (rounds < 10) { + rs.append("0"); + } + rs.append(rounds); + rs.append("$"); + encode_base64(saltb, saltb.length, rs); + encode_base64(hashed, bf_crypt_ciphertext.length * 4 - 1, rs); + return rs.toString(); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method + * + * @param log_rounds the log2 of the number of rounds of hashing to apply - the work + * factor therefore increases as 2**log_rounds. Minimum 4, maximum 31. + * @param random an instance of SecureRandom to use + * @return an encoded salt value + */ + public static String gensalt(int log_rounds, SecureRandom random) { + if (log_rounds < MIN_LOG_ROUNDS || log_rounds > MAX_LOG_ROUNDS) { + throw new IllegalArgumentException("Bad number of rounds"); + } + StringBuilder rs = new StringBuilder(); + byte rnd[] = new byte[BCRYPT_SALT_LEN]; + + random.nextBytes(rnd); + + rs.append("$2a$"); + if (log_rounds < 10) { + rs.append("0"); + } + rs.append(log_rounds); + rs.append("$"); + encode_base64(rnd, rnd.length, rs); + return rs.toString(); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method + * + * @param log_rounds the log2 of the number of rounds of hashing to apply - the work + * factor therefore increases as 2**log_rounds. Minimum 4, maximum 31. + * @return an encoded salt value + */ + public static String gensalt(int log_rounds) { + return gensalt(log_rounds, new SecureRandom()); + } + + /** + * Generate a salt for use with the BCrypt.hashpw() method, selecting a reasonable + * default for the number of hashing rounds to apply + * + * @return an encoded salt value + */ + public static String gensalt() { + return gensalt(GENSALT_DEFAULT_LOG2_ROUNDS); + } + + /** + * Check that a plaintext password matches a previously hashed one + * + * @param plaintext the plaintext password to verify + * @param hashed the previously-hashed password + * @return true if the passwords match, false otherwise + */ + public static boolean checkpw(String plaintext, String hashed) { + return equalsNoEarlyReturn(hashed, hashpw(plaintext, hashed)); + } + + static boolean equalsNoEarlyReturn(String a, String b) { + char[] caa = a.toCharArray(); + char[] cab = b.toCharArray(); + + if (caa.length != cab.length) { + return false; + } + + byte ret = 0; + for (int i = 0; i < caa.length; i++) { + ret |= caa[i] ^ cab[i]; + } + return ret == 0; + } +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/password/BCryptPasswordEncoder.java b/main/manager-api/src/main/java/xiaozhi/modules/security/password/BCryptPasswordEncoder.java new file mode 100644 index 000000000..0d570a961 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/password/BCryptPasswordEncoder.java @@ -0,0 +1,78 @@ +package xiaozhi.modules.security.password; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.security.SecureRandom; +import java.util.regex.Pattern; + +/** + * Implementation of PasswordEncoder that uses the BCrypt strong hashing function. Clients + * can optionally supply a "strength" (a.k.a. log rounds in BCrypt) and a SecureRandom + * instance. The larger the strength parameter the more work will have to be done + * (exponentially) to hash the passwords. The default value is 10. + * + * @author Dave Syer + */ +public class BCryptPasswordEncoder implements PasswordEncoder { + private Pattern BCRYPT_PATTERN = Pattern + .compile("\\A\\$2a?\\$\\d\\d\\$[./0-9A-Za-z]{53}"); + private final Log logger = LogFactory.getLog(getClass()); + + private final int strength; + + private final SecureRandom random; + + public BCryptPasswordEncoder() { + this(-1); + } + + /** + * @param strength the log rounds to use, between 4 and 31 + */ + public BCryptPasswordEncoder(int strength) { + this(strength, null); + } + + /** + * @param strength the log rounds to use, between 4 and 31 + * @param random the secure random instance to use + */ + public BCryptPasswordEncoder(int strength, SecureRandom random) { + if (strength != -1 && (strength < BCrypt.MIN_LOG_ROUNDS || strength > BCrypt.MAX_LOG_ROUNDS)) { + throw new IllegalArgumentException("Bad strength"); + } + this.strength = strength; + this.random = random; + } + + @Override + public String encode(CharSequence rawPassword) { + String salt; + if (strength > 0) { + if (random != null) { + salt = BCrypt.gensalt(strength, random); + } else { + salt = BCrypt.gensalt(strength); + } + } else { + salt = BCrypt.gensalt(); + } + return BCrypt.hashpw(rawPassword.toString(), salt); + } + + @Override + public boolean matches(CharSequence rawPassword, String encodedPassword) { + if (encodedPassword == null || encodedPassword.length() == 0) { + logger.warn("Empty encoded password"); + return false; + } + + if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) { + logger.warn("Encoded password does not look like BCrypt"); + return false; + } + + return BCrypt.checkpw(rawPassword.toString(), encodedPassword); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordEncoder.java b/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordEncoder.java new file mode 100644 index 000000000..40d1e95c5 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordEncoder.java @@ -0,0 +1,30 @@ +package xiaozhi.modules.security.password; + +/** + * Service interface for encoding passwords. + *

+ * The preferred implementation is {@code BCryptPasswordEncoder}. + * + * @author Keith Donald + */ +public interface PasswordEncoder { + + /** + * Encode the raw password. Generally, a good encoding algorithm applies a SHA-1 or + * greater hash combined with an 8-byte or greater randomly generated salt. + */ + String encode(CharSequence rawPassword); + + /** + * Verify the encoded password obtained from storage matches the submitted raw + * password after it too is encoded. Returns true if the passwords match, false if + * they do not. The stored password itself is never decoded. + * + * @param rawPassword the raw password to encode and match + * @param encodedPassword the encoded password from storage to compare with + * @return true if the raw password, after encoding, matches the encoded password from + * storage + */ + boolean matches(CharSequence rawPassword, String encodedPassword); + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordUtils.java b/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordUtils.java new file mode 100644 index 000000000..b03570102 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/password/PasswordUtils.java @@ -0,0 +1,42 @@ +package xiaozhi.modules.security.password; + +/** + * 密码工具类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class PasswordUtils { + private static PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); + + /** + * 加密 + * + * @param str 字符串 + * @return 返回加密字符串 + */ + public static String encode(String str) { + return passwordEncoder.encode(str); + } + + + /** + * 比较密码是否相等 + * + * @param str 明文密码 + * @param password 加密后密码 + * @return true:成功 false:失败 + */ + public static boolean matches(String str, String password) { + return passwordEncoder.matches(str, password); + } + + + public static void main(String[] args) { + String str = "admin"; + String password = encode(str); + + System.out.println(password); + System.out.println(matches(str, password)); + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/CaptchaService.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/CaptchaService.java new file mode 100644 index 000000000..b91d5d9ab --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/CaptchaService.java @@ -0,0 +1,27 @@ +package xiaozhi.modules.security.service; + +import jakarta.servlet.http.HttpServletResponse; + +import java.io.IOException; + +/** + * 验证码 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public interface CaptchaService { + + /** + * 图片验证码 + */ + void create(HttpServletResponse response, String uuid) throws IOException; + + /** + * 验证码效验 + * + * @param uuid uuid + * @param code 验证码 + * @return true:成功 false:失败 + */ + boolean validate(String uuid, String code); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/ShiroService.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/ShiroService.java new file mode 100644 index 000000000..980645d6b --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/ShiroService.java @@ -0,0 +1,30 @@ +package xiaozhi.modules.security.service; + +import xiaozhi.common.user.UserDetail; +import xiaozhi.modules.security.entity.SysUserTokenEntity; +import xiaozhi.modules.sys.entity.SysUserEntity; + +import java.util.List; +import java.util.Set; + +/** + * shiro相关接口 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public interface ShiroService { + /** + * 获取用户权限列表 + */ + Set getUserPermissions(UserDetail user); + + SysUserTokenEntity getByToken(String token); + + /** + * 根据用户ID,查询用户 + * + * @param userId + */ + SysUserEntity getUser(Long userId); + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java new file mode 100644 index 000000000..220b18b51 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/SysUserTokenService.java @@ -0,0 +1,31 @@ +package xiaozhi.modules.security.service; + +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.common.utils.Result; +import xiaozhi.modules.security.entity.SysUserTokenEntity; + +import java.util.Map; + +/** + * 用户Token + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public interface SysUserTokenService extends BaseService { + + /** + * 生成token + * + * @param userId 用户ID + */ + Result createToken(Long userId); + + /** + * 退出 + * + * @param userId 用户ID + */ + void logout(Long userId); + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java new file mode 100644 index 000000000..fdc0d5b51 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/CaptchaServiceImpl.java @@ -0,0 +1,94 @@ +package xiaozhi.modules.security.service.impl; + +import com.google.common.cache.Cache; +import com.google.common.cache.CacheBuilder; +import com.wf.captcha.SpecCaptcha; +import com.wf.captcha.base.Captcha; +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.modules.security.service.CaptchaService; +import jakarta.annotation.Resource; +import jakarta.servlet.http.HttpServletResponse; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.io.IOException; +import java.util.concurrent.TimeUnit; + +/** + * 验证码 + */ +@Service +public class CaptchaServiceImpl implements CaptchaService { + @Resource + private RedisUtils redisUtils; + @Value("${renren.redis.open}") + private boolean open; + /** + * Local Cache 5分钟过期 + */ + Cache localCache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterAccess(5, TimeUnit.MINUTES).build(); + + @Override + public void create(HttpServletResponse response, String uuid) throws IOException { + response.setContentType("image/gif"); + response.setHeader("Pragma", "No-cache"); + response.setHeader("Cache-Control", "no-cache"); + response.setDateHeader("Expires", 0); + + //生成验证码 + SpecCaptcha captcha = new SpecCaptcha(150, 40); + captcha.setLen(5); + captcha.setCharType(Captcha.TYPE_DEFAULT); + captcha.out(response.getOutputStream()); + + //保存到缓存 + setCache(uuid, captcha.text()); + } + + @Override + public boolean validate(String uuid, String code) { + if (StringUtils.isBlank(code)) { + return false; + } + //获取验证码 + String captcha = getCache(uuid); + + //效验成功 + if (code.equalsIgnoreCase(captcha)) { + return true; + } + + return false; + } + + private void setCache(String key, String value) { + if (open) { + key = RedisKeys.getCaptchaKey(key); + redisUtils.set(key, value, 300); + } else { + localCache.put(key, value); + } + } + + private String getCache(String key) { + if (open) { + key = RedisKeys.getCaptchaKey(key); + String captcha = (String) redisUtils.get(key); + //删除验证码 + if (captcha != null) { + redisUtils.delete(key); + } + + return captcha; + } + + String captcha = localCache.getIfPresent(key); + //删除验证码 + if (captcha != null) { + localCache.invalidate(key); + } + return captcha; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/ShiroServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/ShiroServiceImpl.java new file mode 100644 index 000000000..128d9b9d6 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/ShiroServiceImpl.java @@ -0,0 +1,48 @@ +package xiaozhi.modules.security.service.impl; + +import xiaozhi.common.user.UserDetail; +import xiaozhi.modules.security.dao.SysUserTokenDao; +import xiaozhi.modules.security.entity.SysUserTokenEntity; +import xiaozhi.modules.security.service.ShiroService; +import xiaozhi.modules.sys.dao.SysUserDao; +import xiaozhi.modules.sys.entity.SysUserEntity; +import xiaozhi.modules.sys.enums.SuperAdminEnum; +import lombok.AllArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; + +import java.util.*; + +@AllArgsConstructor +@Service +public class ShiroServiceImpl implements ShiroService { + private final SysUserDao sysUserDao; + private final SysUserTokenDao sysUserTokenDao; + + @Override + public Set getUserPermissions(UserDetail user) { + //系统管理员,拥有最高权限 + // TODO: 暂时写死,后续改成从数据库查询 + List permissionsList = new ArrayList<>(); + //用户权限列表 + Set permsSet = new HashSet<>(); + for (String permissions : permissionsList) { + if (StringUtils.isBlank(permissions)) { + continue; + } + permsSet.addAll(Arrays.asList(permissions.trim().split(","))); + } + + return permsSet; + } + + @Override + public SysUserTokenEntity getByToken(String token) { + return sysUserTokenDao.getByToken(token); + } + + @Override + public SysUserEntity getUser(Long userId) { + return sysUserDao.selectById(userId); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java new file mode 100644 index 000000000..903ca242e --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/service/impl/SysUserTokenServiceImpl.java @@ -0,0 +1,78 @@ +package xiaozhi.modules.security.service.impl; + +import cn.hutool.core.date.DateUtil; +import xiaozhi.common.page.TokenDTO; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.common.utils.HttpContextUtils; +import xiaozhi.common.utils.Result; +import xiaozhi.modules.security.dao.SysUserTokenDao; +import xiaozhi.modules.security.entity.SysUserTokenEntity; +import xiaozhi.modules.security.oauth2.TokenGenerator; +import xiaozhi.modules.security.service.SysUserTokenService; +import org.springframework.stereotype.Service; + +import java.util.Date; + +@Service +public class SysUserTokenServiceImpl extends BaseServiceImpl implements SysUserTokenService { + /** + * 12小时后过期 + */ + private final static int EXPIRE = 3600 * 12; + + @Override + public Result createToken(Long userId) { + //用户token + String token; + + //当前时间 + Date now = new Date(); + //过期时间 + Date expireTime = new Date(now.getTime() + EXPIRE * 1000); + + //判断是否生成过token + SysUserTokenEntity tokenEntity = baseDao.getByUserId(userId); + if (tokenEntity == null) { + //生成一个token + token = TokenGenerator.generateValue(); + + tokenEntity = new SysUserTokenEntity(); + tokenEntity.setUserId(userId); + tokenEntity.setToken(token); + tokenEntity.setUpdateDate(now); + tokenEntity.setExpireDate(expireTime); + + //保存token + this.insert(tokenEntity); + } else { + //判断token是否过期 + if (tokenEntity.getExpireDate().getTime() < System.currentTimeMillis()) { + //token过期,重新生成token + token = TokenGenerator.generateValue(); + } else { + token = tokenEntity.getToken(); + } + + tokenEntity.setToken(token); + tokenEntity.setUpdateDate(now); + tokenEntity.setExpireDate(expireTime); + + //更新token + this.updateById(tokenEntity); + } + + String clientHash = HttpContextUtils.getClientCode(); + + TokenDTO tokenDTO = new TokenDTO(); + tokenDTO.setToken(token); + tokenDTO.setExpire(EXPIRE); + tokenDTO.setClientHash(clientHash); + return new Result().ok(tokenDTO); + } + + @Override + public void logout(Long userId) { + Date expireDate = DateUtil.offsetMinute(new Date(), -1); + baseDao.logout(userId, expireDate); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/security/user/SecurityUser.java b/main/manager-api/src/main/java/xiaozhi/modules/security/user/SecurityUser.java new file mode 100644 index 000000000..5dee27fba --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/security/user/SecurityUser.java @@ -0,0 +1,56 @@ +package xiaozhi.modules.security.user; + +import xiaozhi.common.user.UserDetail; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.subject.Subject; + +/** + * Shiro工具类 + * Copyright (c) 人人开源 All rights reserved. + * Website: https://www.renren.io + */ +public class SecurityUser { + + public static Subject getSubject() { + try { + return SecurityUtils.getSubject(); + } catch (Exception e) { + return null; + } + } + + /** + * 获取用户信息 + */ + public static UserDetail getUser() { + Subject subject = getSubject(); + if (subject == null) { + return new UserDetail(); + } + + UserDetail user = (UserDetail) subject.getPrincipal(); + if (user == null) { + return new UserDetail(); + } + + return user; + } + + public static String getToken() { + return getUser().getToken(); + } + + /** + * 获取用户ID + */ + public static Long getUserId() { + return getUser().getId(); + } + + /** + * 获取部门ID + */ + public static Long getDeptId() { + return getUser().getDeptId(); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysUserController.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysUserController.java new file mode 100644 index 000000000..2f030fffa --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/controller/SysUserController.java @@ -0,0 +1,156 @@ +package xiaozhi.modules.sys.controller; + +import xiaozhi.common.annotation.LogOperation; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.Result; +import xiaozhi.common.validator.AssertUtils; +import xiaozhi.common.validator.ValidatorUtils; +import xiaozhi.common.validator.group.AddGroup; +import xiaozhi.common.validator.group.DefaultGroup; +import xiaozhi.common.validator.group.UpdateGroup; +import xiaozhi.modules.security.password.PasswordUtils; +import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.dto.PasswordDTO; +import xiaozhi.modules.sys.dto.SysUserDTO; +import xiaozhi.modules.sys.service.SysUserService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.AllArgsConstructor; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.web.bind.annotation.*; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * 用户管理 + */ +@AllArgsConstructor +@RestController +@RequestMapping("/sys/user") +@Tag(name = "用户管理") +public class SysUserController { + private final SysUserService sysUserService; + + @GetMapping("page") + @Operation(summary = "分页") + @Parameters({ + @Parameter(name = Constant.PAGE, description = "当前页码,从1开始", required = true), + @Parameter(name = Constant.LIMIT, description = "每页显示记录数", required = true), + @Parameter(name = Constant.ORDER_FIELD, description = "排序字段"), + @Parameter(name = Constant.ORDER, description = "排序方式,可选值(asc、desc)"), + @Parameter(name = "username", description = "用户名"), + @Parameter(name = "gender", description = "性别"), + @Parameter(name = "deptId", description = "部门ID") + }) + @RequiresPermissions("sys:user:page") + public Result> page(@Parameter(hidden = true) @RequestParam Map params) { + PageData page = sysUserService.page(params); + + return new Result>().ok(page); + } + + @GetMapping("{id}") + @Operation(summary = "信息") + @RequiresPermissions("sys:user:info") + public Result get(@PathVariable("id") Long id) { + SysUserDTO data = sysUserService.get(id); + return new Result().ok(data); + } + + @GetMapping("info") + @Operation(summary = "登录用户信息") + public Result info() { + SysUserDTO data = ConvertUtils.sourceToTarget(SecurityUser.getUser(), SysUserDTO.class); + return new Result().ok(data); + } + + @PutMapping("password") + @Operation(summary = "修改密码") + @LogOperation("修改密码") + public Result password(@RequestBody PasswordDTO dto) { + //效验数据 + ValidatorUtils.validateEntity(dto); + String newPassword = dto.getNewPassword(); + String password = dto.getPassword(); + + //密码的强度 + if (newPassword == null || newPassword.length() < 8) { + return new Result().error(ErrorCode.PASSWORD_LENGTH_ERROR); + } + if (!sysUserService.isStrongPassword(newPassword)) { + return new Result().error(ErrorCode.PASSWORD_WEAK_ERROR); + } + UserDetail user = SecurityUser.getUser(); + //原密码不正确 + if (!PasswordUtils.matches(dto.getPassword(), user.getPassword())) { + return new Result().error(ErrorCode.PASSWORD_ERROR); + } + + sysUserService.updatePassword(user.getId(), dto.getNewPassword()); + + return new Result(); + } + + @PostMapping + @Operation(summary = "保存") + @LogOperation("保存") + @RequiresPermissions("sys:user:save") + public Result save(@RequestBody SysUserDTO dto) { + //效验数据 + ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class); + + sysUserService.save(dto); + + return new Result(); + } + + @PutMapping + @Operation(summary = "修改") + @LogOperation("修改") + @RequiresPermissions("sys:user:update") + public Result update(@RequestBody SysUserDTO dto) { + //效验数据 + ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class); + + sysUserService.update(dto); + + return new Result(); + } + + @PutMapping("app") + @Operation(summary = "修改") + @LogOperation("修改") + @RequiresPermissions("sys:user:update") + public Result updateUserInfo(@RequestBody SysUserDTO dto) { + sysUserService.updateUserInfo(dto); + + return new Result(); + } + + @DeleteMapping + @Operation(summary = "删除") + @LogOperation("删除") + @RequiresPermissions("sys:user:delete") + public Result delete(@RequestBody Long[] ids) { + //效验数据 + AssertUtils.isArrayEmpty(ids, "id"); + + List idList = Arrays.asList(ids); + if (idList.contains(SecurityUser.getUserId())) { + throw new RenException(ErrorCode.DEL_MYSELF_ERROR); + } + + sysUserService.deleteBatchIds(idList); + + return new Result(); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictDataDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictDataDao.java new file mode 100644 index 000000000..08aaca5be --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictDataDao.java @@ -0,0 +1,23 @@ +package xiaozhi.modules.sys.dao; + +import xiaozhi.common.dao.BaseDao; +import xiaozhi.modules.sys.dto.SysDictDataDTO; +import xiaozhi.modules.sys.entity.DictData; +import xiaozhi.modules.sys.entity.SysDictDataEntity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * 字典数据 + */ +@Mapper +public interface SysDictDataDao extends BaseDao { + + /** + * 字典数据列表 + */ + List getDictDataList(); + + List getDataByTypeCode(String dictType); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictTypeDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictTypeDao.java new file mode 100644 index 000000000..bca8e789b --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysDictTypeDao.java @@ -0,0 +1,21 @@ +package xiaozhi.modules.sys.dao; + +import xiaozhi.common.dao.BaseDao; +import xiaozhi.modules.sys.entity.DictType; +import xiaozhi.modules.sys.entity.SysDictTypeEntity; +import org.apache.ibatis.annotations.Mapper; + +import java.util.List; + +/** + * 字典类型 + */ +@Mapper +public interface SysDictTypeDao extends BaseDao { + + /** + * 字典类型列表 + */ + List getDictTypeList(); + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysParamsDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysParamsDao.java new file mode 100644 index 000000000..0c967a74f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysParamsDao.java @@ -0,0 +1,38 @@ +package xiaozhi.modules.sys.dao; + +import xiaozhi.common.dao.BaseDao; +import xiaozhi.modules.sys.entity.SysParamsEntity; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; + +/** + * 参数管理 + */ +@Mapper +public interface SysParamsDao extends BaseDao { + /** + * 根据参数编码,查询value + * + * @param paramCode 参数编码 + * @return 参数值 + */ + String getValueByCode(String paramCode); + + /** + * 获取参数编码列表 + * + * @param ids ids + * @return 返回参数编码列表 + */ + List getParamCodeList(Long[] ids); + + /** + * 根据参数编码,更新value + * + * @param paramCode 参数编码 + * @param paramValue 参数值 + */ + int updateValueByCode(@Param("paramCode") String paramCode, @Param("paramValue") String paramValue); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java new file mode 100644 index 000000000..08c48a4d4 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dao/SysUserDao.java @@ -0,0 +1,34 @@ +package xiaozhi.modules.sys.dao; + +import xiaozhi.common.dao.BaseDao; +import xiaozhi.modules.sys.entity.SysUserEntity; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * 系统用户 + */ +@Mapper +public interface SysUserDao extends BaseDao { + + List getList(Map params); + + SysUserEntity getById(Long id); + + SysUserEntity getByUsername(String username); + + int updatePassword(@Param("id") Long id, @Param("newPassword") String newPassword); + + /** + * 根据部门ID,查询用户数 + */ + int getCountByDeptId(Long deptId); + + /** + * 根据部门ID,查询用户ID列表 + */ + List getUserIdListByDeptId(List deptIdList); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/PasswordDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/PasswordDTO.java new file mode 100644 index 000000000..1ecadc68b --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/PasswordDTO.java @@ -0,0 +1,24 @@ +package xiaozhi.modules.sys.dto; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +import java.io.Serializable; + +/** + * 修改密码 + */ +@Data +@Schema(description = "修改密码") +public class PasswordDTO implements Serializable { + + @Schema(description = "原密码") + @NotBlank(message = "{sysuser.password.require}") + private String password; + + @Schema(description = "新密码") + @NotBlank(message = "{sysuser.password.require}") + private String newPassword; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictDataDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictDataDTO.java new file mode 100644 index 000000000..eb1065f33 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictDataDTO.java @@ -0,0 +1,59 @@ +package xiaozhi.modules.sys.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import xiaozhi.common.utils.DateUtils; +import xiaozhi.common.validator.group.AddGroup; +import xiaozhi.common.validator.group.DefaultGroup; +import xiaozhi.common.validator.group.UpdateGroup; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Null; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 字典数据 + */ +@Data +@Schema(description = "字典数据") +public class SysDictDataDTO implements Serializable { + + + @Schema(description = "id") + @Null(message = "{id.null}", groups = AddGroup.class) + @NotNull(message = "{id.require}", groups = UpdateGroup.class) + private Long id; + + @Schema(description = "字典类型ID") + @NotNull(message = "{sysdict.type.require}", groups = DefaultGroup.class) + private Long dictTypeId; + + @Schema(description = "字典标签") + @NotBlank(message = "{sysdict.label.require}", groups = DefaultGroup.class) + private String dictLabel; + + @Schema(description = "字典值") + private String dictValue; + + @Schema(description = "备注") + private String remark; + + @Schema(description = "排序") + @Min(value = 0, message = "{sort.number}", groups = DefaultGroup.class) + private Integer sort; + + @Schema(description = "创建时间") + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) + private Date createDate; + + @Schema(description = "更新时间") + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) + private Date updateDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictTypeDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictTypeDTO.java new file mode 100644 index 000000000..2e2c32193 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysDictTypeDTO.java @@ -0,0 +1,55 @@ +package xiaozhi.modules.sys.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import xiaozhi.common.utils.DateUtils; +import xiaozhi.common.validator.group.AddGroup; +import xiaozhi.common.validator.group.DefaultGroup; +import xiaozhi.common.validator.group.UpdateGroup; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Null; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 字典类型 + */ +@Data +@Schema(description = "字典类型") +public class SysDictTypeDTO implements Serializable { + + + @Schema(description = "id") + @Null(message = "{id.null}", groups = AddGroup.class) + @NotNull(message = "{id.require}", groups = UpdateGroup.class) + private Long id; + + @Schema(description = "字典类型") + @NotBlank(message = "{sysdict.type.require}", groups = DefaultGroup.class) + private String dictType; + + @Schema(description = "字典名称") + @NotBlank(message = "{sysdict.name.require}", groups = DefaultGroup.class) + private String dictName; + + @Schema(description = "备注") + private String remark; + + @Schema(description = "排序") + @Min(value = 0, message = "{sort.number}", groups = DefaultGroup.class) + private Integer sort; + + @Schema(description = "创建时间") + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) + private Date createDate; + + @Schema(description = "更新时间") + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + private Date updateDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysParamsDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysParamsDTO.java new file mode 100644 index 000000000..f55ab200f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysParamsDTO.java @@ -0,0 +1,52 @@ +package xiaozhi.modules.sys.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import xiaozhi.common.utils.DateUtils; +import xiaozhi.common.validator.group.AddGroup; +import xiaozhi.common.validator.group.DefaultGroup; +import xiaozhi.common.validator.group.UpdateGroup; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Null; +import lombok.Data; + +import java.io.Serializable; +import java.util.Date; + +/** + * 参数管理 + */ +@Data +@Schema(description = "参数管理") +public class SysParamsDTO implements Serializable { + + + @Schema(description = "id") + @Null(message = "{id.null}", groups = AddGroup.class) + @NotNull(message = "{id.require}", groups = UpdateGroup.class) + private Long id; + + @Schema(description = "参数编码") + @NotBlank(message = "{sysparams.paramcode.require}", groups = DefaultGroup.class) + private String paramCode; + + @Schema(description = "参数值") + @NotBlank(message = "{sysparams.paramvalue.require}", groups = DefaultGroup.class) + private String paramValue; + + @Schema(description = "备注") + private String remark; + + @Schema(description = "创建时间") + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) + private Date createDate; + + @Schema(description = "更新时间") + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) + private Date updateDate; + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java new file mode 100644 index 000000000..00f7fc78d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/dto/SysUserDTO.java @@ -0,0 +1,85 @@ +package xiaozhi.modules.sys.dto; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonProperty; +import xiaozhi.common.utils.DateUtils; +import xiaozhi.common.validator.group.AddGroup; +import xiaozhi.common.validator.group.DefaultGroup; +import xiaozhi.common.validator.group.UpdateGroup; +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Email; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Null; +import lombok.Data; +import org.hibernate.validator.constraints.Range; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +/** + * 用户管理 + */ +@Data +@Schema(description = "用户管理") +public class SysUserDTO implements Serializable { + @Schema(description = "id") + @Null(message = "{id.null}", groups = AddGroup.class) + @NotNull(message = "{id.require}", groups = UpdateGroup.class) + private Long id; + + @Schema(description = "用户名", required = true) + @NotBlank(message = "{sysuser.username.require}", groups = DefaultGroup.class) + private String username; + + @Schema(description = "密码") + @JsonProperty(access = JsonProperty.Access.WRITE_ONLY) + @NotBlank(message = "{sysuser.password.require}", groups = AddGroup.class) + private String password; + + @Schema(description = "姓名", required = true) + @NotBlank(message = "{sysuser.realname.require}", groups = DefaultGroup.class) + private String realName; + + @Schema(description = "头像") + private String headUrl; + + @Schema(description = "性别 0:男 1:女 2:保密", required = true) + @Range(min = 0, max = 2, message = "{sysuser.gender.range}", groups = DefaultGroup.class) + private Integer gender; + + @Schema(description = "邮箱") + @Email(message = "{sysuser.email.error}", groups = DefaultGroup.class) + private String email; + + @Schema(description = "手机号") + private String mobile; + + @Schema(description = "部门ID", required = true) + @NotNull(message = "{sysuser.deptId.require}", groups = DefaultGroup.class) + private Long deptId; + + @Schema(description = "状态 0:停用 1:正常", required = true) + @Range(min = 0, max = 1, message = "{sysuser.status.range}", groups = DefaultGroup.class) + private Integer status; + + @Schema(description = "创建时间") + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + @JsonFormat(pattern = DateUtils.DATE_TIME_PATTERN) + private Date createDate; + + @Schema(description = "超级管理员 0:否 1:是") + @JsonProperty(access = JsonProperty.Access.READ_ONLY) + private Integer superAdmin; + + @Schema(description = "角色ID列表") + private List roleIdList; + + @Schema(description = "岗位ID列表") + private List postIdList; + + @Schema(description = "部门名称") + private String deptName; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/DictData.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/DictData.java new file mode 100644 index 000000000..1e16a1927 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/DictData.java @@ -0,0 +1,15 @@ +package xiaozhi.modules.sys.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +/** + * 字典数据 + */ +@Data +public class DictData { + @JsonIgnore + private Long dictTypeId; + private String dictLabel; + private String dictValue; +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/DictType.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/DictType.java new file mode 100644 index 000000000..3cf946065 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/DictType.java @@ -0,0 +1,18 @@ +package xiaozhi.modules.sys.entity; + +import com.fasterxml.jackson.annotation.JsonIgnore; +import lombok.Data; + +import java.util.ArrayList; +import java.util.List; + +/** + * 字典类型 + */ +@Data +public class DictType { + @JsonIgnore + private Long id; + private String dictType; + private List dataList = new ArrayList<>(); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictDataEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictDataEntity.java new file mode 100644 index 000000000..4bfa4b627 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictDataEntity.java @@ -0,0 +1,49 @@ +package xiaozhi.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import xiaozhi.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +/** + * 数据字典 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("sys_dict_data") +public class SysDictDataEntity extends BaseEntity { + /** + * 字典类型ID + */ + private Long dictTypeId; + /** + * 字典标签 + */ + private String dictLabel; + /** + * 字典值 + */ + private String dictValue; + /** + * 备注 + */ + private String remark; + /** + * 排序 + */ + private Integer sort; + /** + * 更新者 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updater; + /** + * 更新时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictTypeEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictTypeEntity.java new file mode 100644 index 000000000..ea752c632 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysDictTypeEntity.java @@ -0,0 +1,45 @@ +package xiaozhi.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import xiaozhi.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +/** + * 字典类型 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("sys_dict_type") +public class SysDictTypeEntity extends BaseEntity { + /** + * 字典类型 + */ + private String dictType; + /** + * 字典名称 + */ + private String dictName; + /** + * 备注 + */ + private String remark; + /** + * 排序 + */ + private Integer sort; + /** + * 更新者 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updater; + /** + * 更新时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateDate; +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysParamsEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysParamsEntity.java new file mode 100644 index 000000000..054e51d7e --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysParamsEntity.java @@ -0,0 +1,46 @@ +package xiaozhi.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import xiaozhi.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +/** + * 参数管理 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("sys_params") +public class SysParamsEntity extends BaseEntity { + /** + * 参数编码 + */ + private String paramCode; + /** + * 参数值 + */ + private String paramValue; + /** + * 类型 0:系统参数 1:非系统参数 + */ + private Integer paramType; + /** + * 备注 + */ + private String remark; + /** + * 更新者 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updater; + /** + * 更新时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateDate; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java new file mode 100644 index 000000000..a5d14a717 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/entity/SysUserEntity.java @@ -0,0 +1,75 @@ +package xiaozhi.modules.sys.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import xiaozhi.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.util.Date; + +/** + * 系统用户 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@TableName("sys_user") +public class SysUserEntity extends BaseEntity { + /** + * 用户名 + */ + private String username; + /** + * 密码 + */ + private String password; + /** + * 姓名 + */ + private String realName; + /** + * 头像 + */ + private String headUrl; + /** + * 性别 0:男 1:女 2:保密 + */ + private Integer gender; + /** + * 邮箱 + */ + private String email; + /** + * 手机号 + */ + private String mobile; + /** + * 部门ID + */ + private Long deptId; + /** + * 超级管理员 0:否 1:是 + */ + private Integer superAdmin; + /** + * 状态 0:停用 1:正常 + */ + private Integer status; + /** + * 更新者 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updater; + /** + * 更新时间 + */ + @TableField(fill = FieldFill.INSERT_UPDATE) + private Date updateDate; + /** + * 部门名称 + */ + @TableField(exist = false) + private String deptName; + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/SuperAdminEnum.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/SuperAdminEnum.java new file mode 100644 index 000000000..655f46e68 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/enums/SuperAdminEnum.java @@ -0,0 +1,19 @@ +package xiaozhi.modules.sys.enums; + +/** + * 超级管理员枚举 + */ +public enum SuperAdminEnum { + YES(1), + NO(0); + + private int value; + + SuperAdminEnum(int value) { + this.value = value; + } + + public int value() { + return this.value; + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/redis/SysParamsRedis.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/redis/SysParamsRedis.java new file mode 100644 index 000000000..dcc14f69e --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/redis/SysParamsRedis.java @@ -0,0 +1,34 @@ +package xiaozhi.modules.sys.redis; + +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; +import lombok.AllArgsConstructor; +import org.springframework.stereotype.Component; + +/** + * 参数管理 + */ +@AllArgsConstructor +@Component +public class SysParamsRedis { + private final RedisUtils redisUtils; + + public void delete(Object[] paramCodes) { + String key = RedisKeys.getSysParamsKey(); + redisUtils.hDel(key, paramCodes); + } + + public void set(String paramCode, String paramValue) { + if (paramValue == null) { + return; + } + String key = RedisKeys.getSysParamsKey(); + redisUtils.hSet(key, paramCode, paramValue); + } + + public String get(String paramCode) { + String key = RedisKeys.getSysParamsKey(); + return (String) redisUtils.hGet(key, paramCode); + } + +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictDataService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictDataService.java new file mode 100644 index 000000000..77be8b3a8 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictDataService.java @@ -0,0 +1,25 @@ +package xiaozhi.modules.sys.service; + +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.modules.sys.dto.SysDictDataDTO; +import xiaozhi.modules.sys.entity.SysDictDataEntity; + +import java.util.Map; + +/** + * 数据字典 + */ +public interface SysDictDataService extends BaseService { + + PageData page(Map params); + + SysDictDataDTO get(Long id); + + void save(SysDictDataDTO dto); + + void update(SysDictDataDTO dto); + + void delete(Long[] ids); + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictTypeService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictTypeService.java new file mode 100644 index 000000000..0b4b51507 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysDictTypeService.java @@ -0,0 +1,26 @@ +package xiaozhi.modules.sys.service; + +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.modules.sys.dto.SysDictTypeDTO; +import xiaozhi.modules.sys.entity.DictType; +import xiaozhi.modules.sys.entity.SysDictTypeEntity; + +import java.util.List; +import java.util.Map; + +/** + * 数据字典 + */ +public interface SysDictTypeService extends BaseService { + + PageData page(Map params); + + SysDictTypeDTO get(Long id); + + void save(SysDictTypeDTO dto); + + void update(SysDictTypeDTO dto); + + void delete(Long[] ids); +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysParamsService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysParamsService.java new file mode 100644 index 000000000..d13e41ba8 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysParamsService.java @@ -0,0 +1,51 @@ +package xiaozhi.modules.sys.service; + + +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.modules.sys.dto.SysParamsDTO; +import xiaozhi.modules.sys.entity.SysParamsEntity; + +import java.util.List; +import java.util.Map; + +/** + * 参数管理 + */ +public interface SysParamsService extends BaseService { + + PageData page(Map params); + + List list(Map params); + + SysParamsDTO get(Long id); + + void save(SysParamsDTO dto); + + void update(SysParamsDTO dto); + + void delete(Long[] ids); + + /** + * 根据参数编码,获取参数的value值 + * + * @param paramCode 参数编码 + */ + String getValue(String paramCode); + + /** + * 根据参数编码,获取value的Object对象 + * + * @param paramCode 参数编码 + * @param clazz Object对象 + */ + T getValueObject(String paramCode, Class clazz); + + /** + * 根据参数编码,更新value + * + * @param paramCode 参数编码 + * @param paramValue 参数值 + */ + int updateValueByCode(String paramCode, String paramValue); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java new file mode 100644 index 000000000..288c4cc04 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/SysUserService.java @@ -0,0 +1,67 @@ +package xiaozhi.modules.sys.service; + +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.BaseService; +import xiaozhi.modules.sys.dto.SysUserDTO; +import xiaozhi.modules.sys.entity.SysUserEntity; + +import java.util.List; +import java.util.Map; + + +/** + * 系统用户 + */ +public interface SysUserService extends BaseService { + + PageData page(Map params); + + List list(Map params); + + SysUserDTO get(Long id); + + SysUserDTO getByUsername(String username); + + void save(SysUserDTO dto); + + void update(SysUserDTO dto); + + void updateUserInfo(SysUserDTO dto); + + void delete(Long[] ids); + + /** + * 修改密码 + * + * @param id 用户ID + * @param newPassword 新密码 + */ + void updatePassword(Long id, String newPassword); + + /** + * 根据部门ID,查询用户数 + */ + int getCountByDeptId(Long deptId); + + /** + * 根据部门ID,查询用户Id列表 + */ + List getUserIdListByDeptId(List deptIdList); + + /** + * 删除用户缓存 + * + * @param userId + */ + void deleteUserCache(Long userId); + + /** + * 验证密码强度 + * + * @param newPassword + * @return + */ + boolean isStrongPassword(String newPassword); + + String getName(Long creator); +} diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java new file mode 100644 index 000000000..a8420dc9d --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictDataServiceImpl.java @@ -0,0 +1,77 @@ +package xiaozhi.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.modules.sys.dao.SysDictDataDao; +import xiaozhi.modules.sys.dto.SysDictDataDTO; +import xiaozhi.modules.sys.entity.SysDictDataEntity; +import xiaozhi.modules.sys.service.SysDictDataService; + +import java.util.Arrays; +import java.util.Map; + +/** + * 字典类型 + */ +@Service +public class SysDictDataServiceImpl extends BaseServiceImpl implements SysDictDataService { + + @Override + public PageData page(Map params) { + IPage page = baseDao.selectPage( + getPage(params, "sort", true), + getWrapper(params) + ); + + return getPageData(page, SysDictDataDTO.class); + } + + private QueryWrapper getWrapper(Map params) { + String dictTypeId = (String) params.get("dictTypeId"); + String dictLabel = (String) params.get("dictLabel"); + String dictValue = (String) params.get("dictValue"); + + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("dict_type_id", Long.parseLong(dictTypeId)); + wrapper.like(StringUtils.isNotBlank(dictLabel), "dict_label", dictLabel); + wrapper.like(StringUtils.isNotBlank(dictValue), "dict_value", dictValue); + + return wrapper; + } + + @Override + public SysDictDataDTO get(Long id) { + SysDictDataEntity entity = baseDao.selectById(id); + + return ConvertUtils.sourceToTarget(entity, SysDictDataDTO.class); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void save(SysDictDataDTO dto) { + SysDictDataEntity entity = ConvertUtils.sourceToTarget(dto, SysDictDataEntity.class); + + insert(entity); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void update(SysDictDataDTO dto) { + SysDictDataEntity entity = ConvertUtils.sourceToTarget(dto, SysDictDataEntity.class); + + updateById(entity); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Long[] ids) { + //删除 + deleteBatchIds(Arrays.asList(ids)); + } +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java new file mode 100644 index 000000000..724df0984 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysDictTypeServiceImpl.java @@ -0,0 +1,102 @@ +package xiaozhi.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import lombok.AllArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.modules.sys.dao.SysDictDataDao; +import xiaozhi.modules.sys.dao.SysDictTypeDao; +import xiaozhi.modules.sys.dto.SysDictTypeDTO; +import xiaozhi.modules.sys.entity.DictData; +import xiaozhi.modules.sys.entity.DictType; +import xiaozhi.modules.sys.entity.SysDictTypeEntity; +import xiaozhi.modules.sys.service.SysDictTypeService; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * 字典类型 + */ +@AllArgsConstructor +@Service +public class SysDictTypeServiceImpl extends BaseServiceImpl implements SysDictTypeService { + private final SysDictDataDao sysDictDataDao; + + @Override + public PageData page(Map params) { + IPage page = baseDao.selectPage( + getPage(params, "sort", true), + getWrapper(params) + ); + + return getPageData(page, SysDictTypeDTO.class); + } + + private QueryWrapper getWrapper(Map params) { + String dictType = (String) params.get("dictType"); + String dictName = (String) params.get("dictName"); + + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.like(StringUtils.isNotBlank(dictType), "dict_type", dictType); + wrapper.like(StringUtils.isNotBlank(dictName), "dict_name", dictName); + + return wrapper; + } + + @Override + public SysDictTypeDTO get(Long id) { + SysDictTypeEntity entity = baseDao.selectById(id); + + return ConvertUtils.sourceToTarget(entity, SysDictTypeDTO.class); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void save(SysDictTypeDTO dto) { + SysDictTypeEntity entity = ConvertUtils.sourceToTarget(dto, SysDictTypeEntity.class); + + insert(entity); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void update(SysDictTypeDTO dto) { + SysDictTypeEntity entity = ConvertUtils.sourceToTarget(dto, SysDictTypeEntity.class); + + updateById(entity); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Long[] ids) { + //删除 + deleteBatchIds(Arrays.asList(ids)); + } + + @Override + public List getAllList() { + List typeList = baseDao.getDictTypeList(); + List dataList = sysDictDataDao.getDictDataList(); + for (DictType type : typeList) { + for (DictData data : dataList) { + if (type.getId().equals(data.getDictTypeId())) { + type.getDataList().add(data); + } + } + } + return typeList; + } + + @Override + public List getDictTypeList() { + return baseDao.getDictTypeList(); + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java new file mode 100644 index 000000000..558a27ec4 --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysParamsServiceImpl.java @@ -0,0 +1,131 @@ +package xiaozhi.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import xiaozhi.common.constant.Constant; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.common.utils.JsonUtils; +import xiaozhi.modules.sys.dao.SysParamsDao; +import xiaozhi.modules.sys.dto.SysParamsDTO; +import xiaozhi.modules.sys.entity.SysParamsEntity; +import xiaozhi.modules.sys.redis.SysParamsRedis; +import xiaozhi.modules.sys.service.SysParamsService; +import lombok.AllArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * 参数管理 + */ +@AllArgsConstructor +@Service +public class SysParamsServiceImpl extends BaseServiceImpl implements SysParamsService { + private final SysParamsRedis sysParamsRedis; + + @Override + public PageData page(Map params) { + IPage page = baseDao.selectPage( + getPage(params, Constant.CREATE_DATE, false), + getWrapper(params) + ); + + return getPageData(page, SysParamsDTO.class); + } + + @Override + public List list(Map params) { + List entityList = baseDao.selectList(getWrapper(params)); + + return ConvertUtils.sourceToTarget(entityList, SysParamsDTO.class); + } + + private QueryWrapper getWrapper(Map params) { + String paramCode = (String) params.get("paramCode"); + + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("param_type", 1); + wrapper.like(StringUtils.isNotBlank(paramCode), "param_code", paramCode); + + return wrapper; + } + + @Override + public SysParamsDTO get(Long id) { + SysParamsEntity entity = baseDao.selectById(id); + + return ConvertUtils.sourceToTarget(entity, SysParamsDTO.class); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void save(SysParamsDTO dto) { + SysParamsEntity entity = ConvertUtils.sourceToTarget(dto, SysParamsEntity.class); + insert(entity); + + sysParamsRedis.set(entity.getParamCode(), entity.getParamValue()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void update(SysParamsDTO dto) { + SysParamsEntity entity = ConvertUtils.sourceToTarget(dto, SysParamsEntity.class); + updateById(entity); + + sysParamsRedis.set(entity.getParamCode(), entity.getParamValue()); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Long[] ids) { + //删除Redis数据 + List paramCodeList = baseDao.getParamCodeList(ids); + String[] paramCodes = paramCodeList.toArray(new String[paramCodeList.size()]); + sysParamsRedis.delete(paramCodes); + + //删除 + deleteBatchIds(Arrays.asList(ids)); + } + + @Override + public String getValue(String paramCode) { + String paramValue = sysParamsRedis.get(paramCode); + if (paramValue == null) { + paramValue = baseDao.getValueByCode(paramCode); + + sysParamsRedis.set(paramCode, paramValue); + } + return paramValue; + } + + @Override + public T getValueObject(String paramCode, Class clazz) { + String paramValue = getValue(paramCode); + if (StringUtils.isNotBlank(paramValue)) { + return JsonUtils.parseObject(paramValue, clazz); + } + + try { + return clazz.newInstance(); + } catch (Exception e) { + throw new RenException(ErrorCode.PARAMS_GET_ERROR); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int updateValueByCode(String paramCode, String paramValue) { + int count = baseDao.updateValueByCode(paramCode, paramValue); + sysParamsRedis.set(paramCode, paramValue); + return count; + } + +} \ No newline at end of file diff --git a/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java new file mode 100644 index 000000000..c9960b07f --- /dev/null +++ b/main/manager-api/src/main/java/xiaozhi/modules/sys/service/impl/SysUserServiceImpl.java @@ -0,0 +1,181 @@ +package xiaozhi.modules.sys.service.impl; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import xiaozhi.common.exception.ErrorCode; +import xiaozhi.common.exception.RenException; +import xiaozhi.common.page.PageData; +import xiaozhi.common.redis.RedisKeys; +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.common.service.impl.BaseServiceImpl; +import xiaozhi.common.user.UserDetail; +import xiaozhi.common.utils.ConvertUtils; +import xiaozhi.modules.security.password.PasswordUtils; +import xiaozhi.modules.security.user.SecurityUser; +import xiaozhi.modules.sys.dao.SysUserDao; +import xiaozhi.modules.sys.dto.SysUserDTO; +import xiaozhi.modules.sys.entity.SysUserEntity; +import xiaozhi.modules.sys.enums.SuperAdminEnum; +import xiaozhi.modules.sys.service.SysUserService; +import lombok.AllArgsConstructor; +import org.apache.commons.lang3.StringUtils; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + + +/** + * 系统用户 + */ +@AllArgsConstructor +@Service +public class SysUserServiceImpl extends BaseServiceImpl implements SysUserService { + private final RedisUtils redisUtils; + + @Override + public PageData page(Map params) { + //转换成like + paramsToLike(params, "username"); + + //分页 + IPage page = getPage(params, "t1.create_date", false); + + //查询 + List list = baseDao.getList(params); + + return getPageData(list, page.getTotal(), SysUserDTO.class); + } + + @Override + public List list(Map params) { + + List entityList = baseDao.getList(params); + + return ConvertUtils.sourceToTarget(entityList, SysUserDTO.class); + } + + @Override + public SysUserDTO get(Long id) { + SysUserEntity entity = baseDao.getById(id); + + return ConvertUtils.sourceToTarget(entity, SysUserDTO.class); + } + + @Override + public SysUserDTO getByUsername(String username) { + SysUserEntity entity = baseDao.getByUsername(username); + return ConvertUtils.sourceToTarget(entity, SysUserDTO.class); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void save(SysUserDTO dto) { + SysUserEntity entity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class); + + //密码强度 + if (!isStrongPassword(entity.getPassword())) { + throw new RenException(ErrorCode.PASSWORD_WEAK_ERROR); + } + + //密码加密 + String password = PasswordUtils.encode(entity.getPassword()); + entity.setPassword(password); + + //保存用户 + entity.setSuperAdmin(SuperAdminEnum.NO.value()); + insert(entity); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void update(SysUserDTO dto) { + SysUserEntity entity = ConvertUtils.sourceToTarget(dto, SysUserEntity.class); + + //密码加密 + if (StringUtils.isBlank(dto.getPassword())) { + entity.setPassword(null); + } else { + //密码强度 + if (!isStrongPassword(entity.getPassword())) { + throw new RenException(ErrorCode.PASSWORD_WEAK_ERROR); + } + String password = PasswordUtils.encode(entity.getPassword()); + entity.setPassword(password); + } + + //更新用户 + updateById(entity); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updateUserInfo(SysUserDTO dto) { + SysUserEntity entity = selectById(dto.getId()); + entity.setHeadUrl(dto.getHeadUrl()); + entity.setRealName(dto.getRealName()); + entity.setGender(dto.getGender()); + entity.setMobile(dto.getMobile()); + entity.setEmail(dto.getEmail()); + + updateById(entity); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void delete(Long[] ids) { + //删除用户 + baseDao.deleteBatchIds(Arrays.asList(ids)); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void updatePassword(Long id, String newPassword) { + newPassword = PasswordUtils.encode(newPassword); + + baseDao.updatePassword(id, newPassword); + } + + @Override + public int getCountByDeptId(Long deptId) { + return baseDao.getCountByDeptId(deptId); + } + + @Override + public List getUserIdListByDeptId(List deptIdList) { + return baseDao.getUserIdListByDeptId(deptIdList); + } + + @Override + public void deleteUserCache(Long userId) { + // 删除缓存 + redisUtils.delete(RedisKeys.getUserInfoKey(userId)); + redisUtils.delete(RedisKeys.getDataScopeListKey(userId)); + redisUtils.delete(RedisKeys.getSysUserName(userId)); + } + + @Override + public boolean isStrongPassword(String password) { + // 弱密码的正则表达式 + String weakPasswordRegex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).+$"; + Pattern pattern = Pattern.compile(weakPasswordRegex); + Matcher matcher = pattern.matcher(password); + return matcher.matches(); + } + + @Override + public String getName(Long id) { + String name = (String) redisUtils.get(RedisKeys.getSysUserName(id)); + if (StringUtils.isBlank(name)) { + SysUserEntity sysUserEntity = selectById(id); + if (sysUserEntity != null) { + redisUtils.set(RedisKeys.getSysUserName(id), sysUserEntity.getUsername()); + return sysUserEntity.getUsername(); + } + } + return name; + } +} diff --git a/main/manager-api/src/main/resources/application-dev.yml b/main/manager-api/src/main/resources/application-dev.yml new file mode 100644 index 000000000..6cd4a99a4 --- /dev/null +++ b/main/manager-api/src/main/resources/application-dev.yml @@ -0,0 +1,49 @@ +knife4j: + production: false + enable: true + basic: + enable: false + username: renren + password: 2ZABCDEUgF + setting: + enableFooter: false +jasypt: + encryptor: + password: P9Hx718z8L +spring: + datasource: + druid: + #MySQL + driver-class-name: com.mysql.cj.jdbc.Driver + url: jdbc:mysql://localhost:3306/xiaozhi_esp32_server?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&nullCatalogMeansCurrent=true + username: root + password: 123456 + initial-size: 10 + max-active: 100 + min-idle: 10 + max-wait: 6000 + pool-prepared-statements: true + max-pool-prepared-statement-per-connection-size: 20 + time-between-eviction-runs-millis: 60000 + min-evictable-idle-time-millis: 300000 + test-while-idle: true + test-on-borrow: false + test-on-return: false + stat-view-servlet: + enabled: true + url-pattern: /druid/* + login-username: admin + login-password: D7Xj810i1C + filter: + stat: + log-slow-sql: true + slow-sql-millis: 1000 + merge-sql: false + wall: + config: + multi-statement-allow: true + +logging: + level: + org.flowable.engine.impl.persistence.entity.*: debug + org.flowable.task.service.impl.persistence.entity.*: debug \ No newline at end of file diff --git a/main/manager-api/src/main/resources/application.yml b/main/manager-api/src/main/resources/application.yml new file mode 100644 index 000000000..0b0e62813 --- /dev/null +++ b/main/manager-api/src/main/resources/application.yml @@ -0,0 +1,79 @@ +# Tomcat +server: + tomcat: + uri-encoding: UTF-8 + threads: + max: 1000 + min-spare: 30 + port: 8002 + servlet: + context-path: /xiaozhi-esp32-api + session: + cookie: + http-only: true + +spring: + # 环境 dev|test|prod + profiles: + active: dev + messages: + encoding: UTF-8 + basename: i18n/messages + servlet: + multipart: + max-file-size: 100MB + max-request-size: 100MB + enabled: true + data: + redis: + database: 0 + host: 127.0.0.1 + port: 6379 + password: # 密码(默认为空) + timeout: 6000ms # 连接超时时长(毫秒) + lettuce: + pool: + max-active: 1000 # 连接池最大连接数(使用负值表示没有限制) + max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制) + max-idle: 10 # 连接池中的最大空闲连接 + min-idle: 5 # 连接池中的最小空闲连接 + main: + allow-bean-definition-overriding: true + +knife4j: + enable: true + basic: + enable: false + username: admin + password: admin + setting: + enableFooter: false + +renren: + redis: + open: false + xss: + enabled: true + exclude-urls: + +#mybatis +mybatis-plus: + mapper-locations: classpath*:/mapper/**/*.xml + #实体扫描,多个package用逗号或者分号分隔 + typeAliasesPackage: xiaozhi.modules.*.entity + global-config: + #数据库相关配置 + db-config: + #主键类型 + id-type: ASSIGN_ID + banner: false + #原生配置 + configuration: + map-underscore-to-camel-case: true + cache-enabled: false + call-setters-on-nulls: true + jdbc-type-for-null: 'null' + configuration-properties: + prefix: + blobType: BLOB + boolValue: TRUE \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/001create_sys.sql b/main/manager-api/src/main/resources/db/changelog/001create_sys.sql new file mode 100644 index 000000000..c5bb0cdfe --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/001create_sys.sql @@ -0,0 +1,84 @@ +DROP TABLE IF EXISTS sys_user; +DROP TABLE IF EXISTS sys_params; +DROP TABLE IF EXISTS sys_user_token; +DROP TABLE IF EXISTS sys_dict_type; +DROP TABLE IF EXISTS sys_dict_data; + +-- 系统用户 +CREATE TABLE sys_user ( + id bigint NOT NULL COMMENT 'id', + username varchar(50) NOT NULL COMMENT '用户名', + password varchar(100) COMMENT '密码', + super_admin tinyint unsigned COMMENT '超级管理员 0:否 1:是', + status tinyint COMMENT '状态 0:停用 1:正常', + create_date datetime COMMENT '创建时间', + updater bigint COMMENT '更新者', + update_date datetime COMMENT '更新时间', + primary key (id), + unique key uk_username (username), + key idx_create_date (create_date) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统用户'; + +-- 系统用户Token +CREATE TABLE sys_user_token ( + id bigint NOT NULL COMMENT 'id', + user_id bigint NOT NULL COMMENT '用户id', + token varchar(100) NOT NULL COMMENT '用户token', + expire_date datetime COMMENT '过期时间', + update_date datetime COMMENT '更新时间', + create_date datetime COMMENT '创建时间', + PRIMARY KEY (id), + UNIQUE KEY user_id (user_id), + UNIQUE KEY token (token) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统用户Token'; + +-- 参数管理 +create table sys_params +( + id bigint NOT NULL COMMENT 'id', + param_code varchar(32) COMMENT '参数编码', + param_value varchar(2000) COMMENT '参数值', + param_type tinyint unsigned default 1 COMMENT '类型 0:系统参数 1:非系统参数', + remark varchar(200) COMMENT '备注', + creator bigint COMMENT '创建者', + create_date datetime COMMENT '创建时间', + updater bigint COMMENT '更新者', + update_date datetime COMMENT '更新时间', + primary key (id), + unique key uk_param_code (param_code), + key idx_create_date (create_date) +)ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT='参数管理'; + +-- 字典类型 +create table sys_dict_type +( + id bigint NOT NULL COMMENT 'id', + dict_type varchar(100) NOT NULL COMMENT '字典类型', + dict_name varchar(255) NOT NULL COMMENT '字典名称', + remark varchar(255) COMMENT '备注', + sort int unsigned COMMENT '排序', + creator bigint COMMENT '创建者', + create_date datetime COMMENT '创建时间', + updater bigint COMMENT '更新者', + update_date datetime COMMENT '更新时间', + primary key (id), + UNIQUE KEY(dict_type) +)ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT='字典类型'; + +-- 字典数据 +create table sys_dict_data +( + id bigint NOT NULL COMMENT 'id', + dict_type_id bigint NOT NULL COMMENT '字典类型ID', + dict_label varchar(255) NOT NULL COMMENT '字典标签', + dict_value varchar(255) COMMENT '字典值', + remark varchar(255) COMMENT '备注', + sort int unsigned COMMENT '排序', + creator bigint COMMENT '创建者', + create_date datetime COMMENT '创建时间', + updater bigint COMMENT '更新者', + update_date datetime COMMENT '更新时间', + primary key (id), + unique key uk_dict_type_value (dict_type_id, dict_value), + key idx_sort (sort) +)ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COMMENT='字典数据'; \ No newline at end of file diff --git a/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml new file mode 100755 index 000000000..73d916fad --- /dev/null +++ b/main/manager-api/src/main/resources/db/changelog/db.changelog-master.yaml @@ -0,0 +1,11 @@ +# 规范约定: +# id生成根据时间时分,文件名对应id +# 每次对数据表进行改动时,只允许新建新对changeSet,不允许对上一个changeSet配置及文件进行修改 +databaseChangeLog: + - changeSet: + id: 001create_sys + author: John + changes: + - sqlFile: + encoding: utf8 + path: classpath:db/changelog/001create_sys.sql \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages.properties b/main/manager-api/src/main/resources/i18n/messages.properties new file mode 100644 index 000000000..c4e78e94b --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/messages.properties @@ -0,0 +1,54 @@ +#Default +500=\u670D\u52A1\u5668\u5185\u90E8\u5F02\u5E38 +401=\u672A\u6388\u6743 +403=\u62D2\u7EDD\u8BBF\u95EE\uFF0C\u6CA1\u6709\u6743\u9650 +10001={0}\u4E0D\u80FD\u4E3A\u7A7A +10002=\u6570\u636E\u5E93\u4E2D\u5DF2\u5B58\u5728\u8BE5\u8BB0\u5F55 +10003=\u83B7\u53D6\u53C2\u6570\u5931\u8D25 +10004=\u8D26\u53F7\u6216\u5BC6\u7801\u9519\u8BEF +10005=\u8D26\u53F7\u5DF2\u88AB\u505C\u7528 +10006=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A +10007=\u9A8C\u8BC1\u7801\u4E0D\u6B63\u786E +10008=\u5148\u5220\u9664\u5B50\u83DC\u5355\u6216\u6309\u94AE +10009=\u539F\u5BC6\u7801\u4E0D\u6B63\u786E +10010=\u8D26\u53F7\u6216\u5BC6\u7801\u4E0D\u6B63\u786E,\u60A8\u8FD8\u6709\u53EF\u4EE5\u5C1D\u8BD5{0}\u6B21 +10011=\u4E0A\u7EA7\u90E8\u95E8\u9009\u62E9\u9519\u8BEF +10012=\u4E0A\u7EA7\u83DC\u5355\u4E0D\u80FD\u4E3A\u81EA\u8EAB +10013=\u6570\u636E\u6743\u9650\u63A5\u53E3\uFF0C\u53EA\u80FD\u662FMap\u7C7B\u578B\u53C2\u6570 +10014=\u8BF7\u5148\u5220\u9664\u4E0B\u7EA7\u90E8\u95E8 +10015=\u8BF7\u5148\u5220\u9664\u90E8\u95E8\u4E0B\u7684\u7528\u6237 +10016=\u90E8\u7F72\u5931\u8D25\uFF0C\u6CA1\u6709\u6D41\u7A0B +10017=\u6A21\u578B\u56FE\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 +10018=\u5BFC\u51FA\u5931\u8D25\uFF0C\u6A21\u578BID\u4E3A{0} +10019=\u8BF7\u4E0A\u4F20\u6587\u4EF6 +10020=token\u4E0D\u80FD\u4E3A\u7A7A +10021=token\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55 +10022=\u8D26\u53F7\u5DF2\u88AB\u9501\u5B9A +10023=\u8BF7\u4E0A\u4F20zip\u3001bar\u3001bpmn\u3001bpmn20.xml\u683C\u5F0F\u6587\u4EF6 +10024=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25{0} +10025=\u53D1\u9001\u77ED\u4FE1\u5931\u8D25{0} +10026=\u90AE\u4EF6\u6A21\u677F\u4E0D\u5B58\u5728 +10027=Redis\u670D\u52A1\u5F02\u5E38 +10028=\u5B9A\u65F6\u4EFB\u52A1\u5931\u8D25 +10029=\u4E0D\u80FD\u5305\u542B\u975E\u6CD5\u5B57\u7B26 +10030=\u53C2\u6570\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u8BF7\u4F7F\u7528JSON\u683C\u5F0F +10031=\u8BF7\u5148\u5B8C\u6210\u77ED\u4FE1\u914D\u7F6E +10032=\u4EFB\u52A1\u5DF2\u88AB\u7B7E\u6536\uFF0C\u64CD\u4F5C\u5931\u8D25 +10033=\u4E0D\u5B58\u5728\u7684\u6D41\u7A0B\u5B9A\u4E49 +10034=\u4E0A\u7EA7\u8282\u70B9\u4E0D\u5B58\u5728 +10035=\u9A73\u56DE +10036=\u56DE\u9000 +10037=\u4EFB\u52A1\u6CA1\u6709\u5206\u7EC4\uFF0C\u65E0\u6CD5\u53D6\u6D88\u8BA4\u9886 +10038=\u4E0A\u7EA7\u533A\u57DF\u9009\u62E9\u9519\u8BEF +10039=\u8BF7\u5148\u5220\u9664\u4E0B\u7EA7\u533A\u57DF +10040=\u6D41\u7A0B\u5DF2\u6302\u8D77\uFF0C\u4E0D\u80FD\u542F\u52A8\u5B9E\u4F8B +10041=\u591A\u5B9E\u4F8B\u4EFB\u52A1\u4E0D\u80FD\u9A73\u56DE +10042=\u5B58\u5728\u591A\u4E2A\u5904\u7406\u4E2D\u7684\u4EFB\u52A1\uFF0C\u4E0D\u80FD\u9A73\u56DE +10043=\u591A\u5B9E\u4F8B\u4EFB\u52A1\u4E0D\u80FD\u7EC8\u6B62 +10044=\u5B58\u5728\u591A\u4E2A\u5904\u7406\u4E2D\u7684\u4EFB\u52A1\uFF0C\u4E0D\u80FD\u7EC8\u6B62\u6D41\u7A0B +10045=\u7EC8\u6B62 +10046=\u591A\u5B9E\u4F8B\u4EFB\u52A1\u4E0D\u80FD\u56DE\u9000 +10047=\u5B58\u5728\u591A\u4E2A\u5E76\u884C\u6267\u884C\u7684\u4EFB\u52A1\uFF0C\u4E0D\u80FD\u56DE\u9000 +10048=\u767B\u5F55\u8D26\u53F7\uFF0C\u65E0\u6743\u5220\u9664 +10055=\u60A8\u7684\u5BC6\u7801\u957F\u5EA6\u4E0D\u591F8\u4F4D +10056=\u60A8\u7684\u5BC6\u7801\u590D\u6742\u5EA6\u4E0D\u591F\uFF0C\u9700\u8981\u540C\u65F6\u5305\u542B\u6570\u5B57,\u5C0F\u5199\u82F1\u6587,\u5927\u5199\u82F1\u6587 \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_en_US.properties b/main/manager-api/src/main/resources/i18n/messages_en_US.properties new file mode 100644 index 000000000..573e038a2 --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/messages_en_US.properties @@ -0,0 +1,54 @@ +#English +500=Server internal exception +401=Unauthorized +403=Access denied, no permissions +10001={0} cannot be empty +10002=The record already exists in the database +10003=Failed to get parameters +10004=The account number or password is incorrect. +10005=Account has been deactivated +10006=Unique ID cannot be empty +10007=The verification code is incorrect +10008=First delete submenu or button +10009=The original password is incorrect +10010=password error,you can try {0} times +10011=The superior department made a wrong choice +10012=Upper menu cannot be for itself +10013=Data permission interface, which can only be a Map type parameter. +10014=Please delete the subordinate department first +10015=Please delete the user under the department first +10016=Deployment failed, no process +10017=Model diagram is incorrect, please check +10018=The export failed with the model ID {0} +10019=Please upload a file +10020=token cannot be empty +10021=token is invalid, please log in again +10022=The account has been locked +10023=Please upload zip, bar, bpmn, bpmn20.xml format file +10024=Failed to upload file {0} +10025=Failed to send SMS {0} +10026=Mail template does not exist +10027=Redis service exception +10028=Timed task failed +10029=Cannot contain illegal characters +10030=The parameter format is incorrect. Please use JSON format. +10031=Please complete the SMS configuration first. +10032=Task has been signed and operation failed +10033=Non-existent process definition +10034=Superior node does not exist +10035=Reject +10036=Rollback +10037=Tasks are not grouped and cannot be cancelled +10038=Upper area selection error +10039=Please delete the subordinate area first +10040=The process has been suspended and the instance cannot be started +10041=Multi-instance tasks cannot be rejected +10042=Tasks in multiple processes cannot be rejected +10043=Multi-instance tasks cannot be terminated +10044=There are tasks in multiple processes that cannot terminate the process +10045=END +10046=Multi-instance tasks cannot be rolled back +10047=There are multiple parallel tasks that cannot be rolled back +10048 = Login account, no right to delete +10055=Your password length is less than 8 digits +10056=Your password is not complex enough and needs to include both numbers, lowercase English, and uppercase English \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties new file mode 100644 index 000000000..de062fd4d --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/messages_zh_CN.properties @@ -0,0 +1,54 @@ +#\u7B80\u4F53\u4E2D\u6587 +500=\u670D\u52A1\u5668\u5185\u90E8\u5F02\u5E38 +401=\u672A\u6388\u6743 +403=\u62D2\u7EDD\u8BBF\u95EE\uFF0C\u6CA1\u6709\u6743\u9650 +10001={0}\u4E0D\u80FD\u4E3A\u7A7A +10002=\u6570\u636E\u5E93\u4E2D\u5DF2\u5B58\u5728\u8BE5\u8BB0\u5F55 +10003=\u83B7\u53D6\u53C2\u6570\u5931\u8D25 +10004=\u8D26\u53F7\u6216\u5BC6\u7801\u9519\u8BEF +10005=\u8D26\u53F7\u5DF2\u88AB\u505C\u7528 +10006=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A +10007=\u9A8C\u8BC1\u7801\u4E0D\u6B63\u786E +10008=\u5148\u5220\u9664\u5B50\u83DC\u5355\u6216\u6309\u94AE +10009=\u539F\u5BC6\u7801\u4E0D\u6B63\u786E +10010=\u8D26\u53F7\u6216\u5BC6\u7801\u4E0D\u6B63\u786E,\u60A8\u8FD8\u6709\u53EF\u4EE5\u5C1D\u8BD5{0}\u6B21 +10011=\u4E0A\u7EA7\u90E8\u95E8\u9009\u62E9\u9519\u8BEF +10012=\u4E0A\u7EA7\u83DC\u5355\u4E0D\u80FD\u4E3A\u81EA\u8EAB +10013=\u6570\u636E\u6743\u9650\u63A5\u53E3\uFF0C\u53EA\u80FD\u662FMap\u7C7B\u578B\u53C2\u6570 +10014=\u8BF7\u5148\u5220\u9664\u4E0B\u7EA7\u90E8\u95E8 +10015=\u8BF7\u5148\u5220\u9664\u90E8\u95E8\u4E0B\u7684\u7528\u6237 +10016=\u90E8\u7F72\u5931\u8D25\uFF0C\u6CA1\u6709\u6D41\u7A0B +10017=\u6A21\u578B\u56FE\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5 +10018=\u5BFC\u51FA\u5931\u8D25\uFF0C\u6A21\u578BID\u4E3A{0} +10019=\u8BF7\u4E0A\u4F20\u6587\u4EF6 +10020=token\u4E0D\u80FD\u4E3A\u7A7A +10021=token\u5931\u6548\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55 +10022=\u8D26\u53F7\u5DF2\u88AB\u9501\u5B9A +10023=\u8BF7\u4E0A\u4F20zip\u3001bar\u3001bpmn\u3001bpmn20.xml\u683C\u5F0F\u6587\u4EF6 +10024=\u4E0A\u4F20\u6587\u4EF6\u5931\u8D25{0} +10025=\u53D1\u9001\u77ED\u4FE1\u5931\u8D25{0} +10026=\u90AE\u4EF6\u6A21\u677F\u4E0D\u5B58\u5728 +10027=Redis\u670D\u52A1\u5F02\u5E38 +10028=\u5B9A\u65F6\u4EFB\u52A1\u5931\u8D25 +10029=\u4E0D\u80FD\u5305\u542B\u975E\u6CD5\u5B57\u7B26 +10030=\u53C2\u6570\u683C\u5F0F\u4E0D\u6B63\u786E\uFF0C\u8BF7\u4F7F\u7528JSON\u683C\u5F0F +10031=\u8BF7\u5148\u5B8C\u6210\u77ED\u4FE1\u914D\u7F6E +10032=\u4EFB\u52A1\u5DF2\u88AB\u7B7E\u6536\uFF0C\u64CD\u4F5C\u5931\u8D25 +10033=\u4E0D\u5B58\u5728\u7684\u6D41\u7A0B\u5B9A\u4E49 +10034=\u4E0A\u7EA7\u8282\u70B9\u4E0D\u5B58\u5728 +10035=\u9A73\u56DE +10036=\u56DE\u9000 +10037=\u4EFB\u52A1\u6CA1\u6709\u5206\u7EC4\uFF0C\u65E0\u6CD5\u53D6\u6D88\u8BA4\u9886 +10038=\u4E0A\u7EA7\u533A\u57DF\u9009\u62E9\u9519\u8BEF +10039=\u8BF7\u5148\u5220\u9664\u4E0B\u7EA7\u533A\u57DF +10040=\u6D41\u7A0B\u5DF2\u6302\u8D77\uFF0C\u4E0D\u80FD\u542F\u52A8\u5B9E\u4F8B +10041=\u591A\u5B9E\u4F8B\u4EFB\u52A1\u4E0D\u80FD\u9A73\u56DE +10042=\u5B58\u5728\u591A\u4E2A\u5904\u7406\u4E2D\u7684\u4EFB\u52A1\uFF0C\u4E0D\u80FD\u9A73\u56DE +10043=\u591A\u5B9E\u4F8B\u4EFB\u52A1\u4E0D\u80FD\u7EC8\u6B62 +10044=\u5B58\u5728\u591A\u4E2A\u5904\u7406\u4E2D\u7684\u4EFB\u52A1\uFF0C\u4E0D\u80FD\u7EC8\u6B62\u6D41\u7A0B +10045=\u7EC8\u6B62 +10046=\u591A\u5B9E\u4F8B\u4EFB\u52A1\u4E0D\u80FD\u56DE\u9000 +10047=\u5B58\u5728\u591A\u4E2A\u5E76\u884C\u6267\u884C\u7684\u4EFB\u52A1\uFF0C\u4E0D\u80FD\u56DE\u9000 +10048=\u767B\u5F55\u8D26\u53F7\uFF0C\u65E0\u6743\u5220\u9664 +10055=\u60A8\u7684\u5BC6\u7801\u957F\u5EA6\u4E0D\u591F8\u4F4D +10056=\u60A8\u7684\u5BC6\u7801\u590D\u6742\u5EA6\u4E0D\u591F\uFF0C\u9700\u8981\u540C\u65F6\u5305\u542B\u6570\u5B57,\u5C0F\u5199\u82F1\u6587,\u5927\u5199\u82F1\u6587 \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties new file mode 100644 index 000000000..bd67d5b35 --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/messages_zh_TW.properties @@ -0,0 +1,54 @@ +#\u7E41\u4F53\u4E2D\u6587 +500=\u670D\u52D9\u5668\u5167\u90E8\u7570\u5E38 +401=\u672A\u6388\u6B0A +403=\u62D2\u7D55\u8A2A\u554F\uFF0C\u6C92\u6709\u6B0A\u9650 +10001={0}\u4E0D\u80FD\u70BA\u7A7A +10002=\u6578\u64DA\u5EAB\u4E2D\u5DF2\u5B58\u5728\u8A72\u8A18\u9304 +10003=\u7372\u53D6\u53C3\u6578\u5931\u6557 +10004=\u8CEC\u865F\u6216\u5BC6\u78BC\u932F\u8AA4 +10005=\u8CEC\u865F\u5DF2\u88AB\u505C\u7528 +10006=\u552F\u4E00\u6A19\u8B58\u4E0D\u80FD\u70BA\u7A7A +10007=\u9A57\u8B49\u78BC\u4E0D\u6B63\u78BA +10008=\u5148\u522A\u9664\u5B50\u83DC\u55AE\u6216\u6309\u9215 +10009=\u539F\u5BC6\u78BC\u4E0D\u6B63\u78BA +10010=\u8CEC\u865F\u6216\u5BC6\u78BC\u4E0D\u6B63\u78BA,\u60A8\u9084\u6709\u53EF\u4EE5\u5617\u8A66{0}\u6B21 +10011=\u4E0A\u7D1A\u90E8\u9580\u9078\u64C7\u932F\u8AA4 +10012=\u4E0A\u7D1A\u83DC\u55AE\u4E0D\u80FD\u70BA\u81EA\u8EAB +10013=\u6578\u64DA\u6B0A\u9650\u63A5\u53E3\uFF0C\u53EA\u80FD\u662FMap\u985E\u578B\u53C3\u6578 +10014=\u8ACB\u5148\u522A\u9664\u4E0B\u7D1A\u90E8\u9580 +10015=\u8ACB\u5148\u522A\u9664\u90E8\u9580\u4E0B\u7684\u7528\u6236 +10016=\u90E8\u7F72\u5931\u6557\uFF0C\u6C92\u6709\u6D41\u7A0B +10017=\u6A21\u578B\u5716\u4E0D\u6B63\u78BA\uFF0C\u8ACB\u6AA2\u67E5 +10018=\u5C0E\u51FA\u5931\u6557\uFF0C\u6A21\u578BID\u70BA{0} +10019=\u8ACB\u4E0A\u50B3\u6587\u4EF6 +10020=token\u4E0D\u80FD\u70BA\u7A7A +10021=token\u5931\u6548\uFF0C\u8ACB\u91CD\u65B0\u767B\u9304 +10022=\u8CEC\u865F\u5DF2\u88AB\u9396\u5B9A +10023=\u8ACB\u4E0A\u50B3zip\u3001bar\u3001bpmn\u3001bpmn20.xml\u683C\u5F0F\u6587\u4EF6 +10024=\u4E0A\u50B3\u6587\u4EF6\u5931\u6557{0} +10025=\u767C\u9001\u77ED\u4FE1\u5931\u6557{0} +10026=\u90F5\u4EF6\u6A21\u677F\u4E0D\u5B58\u5728 +10027=Redis\u670D\u52D9\u7570\u5E38 +10028=\u5B9A\u6642\u4EFB\u52D9\u5931\u6557 +10029=\u4E0D\u80FD\u5305\u542B\u975E\u6CD5\u5B57\u7B26 +10030=\u53C3\u6578\u683C\u5F0F\u4E0D\u6B63\u78BA\uFF0C\u8ACB\u4F7F\u7528JSON\u683C\u5F0F +10031=\u8ACB\u5148\u5B8C\u6210\u77ED\u4FE1\u914D\u7F6E +10032=\u4EFB\u52D9\u5DF2\u88AB\u7C3D\u6536\uFF0C\u64CD\u4F5C\u5931\u6557 +10033=\u4E0D\u5B58\u5728\u7684\u6D41\u7A0B\u5B9A\u7FA9 +10034=\u4E0A\u7D1A\u7BC0\u9EDE\u4E0D\u5B58\u5728 +10035=\u99C1\u56DE +10036=\u56DE\u9000 +10037=\u4EFB\u52D9\u6C92\u6709\u5206\u7D44\uFF0C\u7121\u6CD5\u53D6\u6D88\u8A8D\u9818 +10038=\u4E0A\u7D1A\u5340\u57DF\u9078\u64C7\u932F\u8AA4 +10039=\u8ACB\u5148\u522A\u9664\u4E0B\u7D1A\u5340\u57DF +10040=\u6D41\u7A0B\u5DF2\u639B\u8D77\uFF0C\u4E0D\u80FD\u555F\u52D5\u5BE6\u4F8B +10041=\u591A\u5BE6\u4F8B\u4EFB\u52D9\u4E0D\u80FD\u99C1\u56DE +10042=\u5B58\u5728\u591A\u500B\u8655\u7406\u4E2D\u7684\u4EFB\u52D9\uFF0C\u4E0D\u80FD\u99C1\u56DE +10043=\u591A\u5BE6\u4F8B\u4EFB\u52D9\u4E0D\u80FD\u7D42\u6B62 +10044=\u5B58\u5728\u591A\u500B\u8655\u7406\u4E2D\u7684\u4EFB\u52D9\uFF0C\u4E0D\u80FD\u7D42\u6B62\u6D41\u7A0B +10045=\u7D42\u6B62 +10046=\u591A\u5BE6\u4F8B\u4EFB\u52D9\u4E0D\u80FD\u56DE\u9000 +10047=\u5B58\u5728\u591A\u500B\u4E26\u884C\u57F7\u884C\u7684\u4EFB\u52D9\uFF0C\u4E0D\u80FD\u56DE\u9000 +10048=\u767B\u5165\u5E33\u865F\uFF0C\u7121\u6B0A\u5220\u9664 +10055=\u60A8\u7684\u5BC6\u78BC\u9577\u5EA6\u4E0D\u59208\u4F4D +10056=\u60A8\u7684\u5BC6\u78BC\u5FA9\u96DC\u5EA6\u4E0D\u5920\uFF0C\u9700\u8981\u540C\u6642\u5305\u542B\u6578\u5B57,\u5C0F\u5BEB\u82F1\u6587,\u5927\u5BEB\u82F1\u6587 \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation.properties b/main/manager-api/src/main/resources/i18n/validation.properties new file mode 100644 index 000000000..66d95744e --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/validation.properties @@ -0,0 +1,109 @@ +#\u7B80\u4F53\u4E2D\u6587 +id.require=ID\u4E0D\u80FD\u4E3A\u7A7A +id.null=ID\u5FC5\u987B\u4E3A\u7A7A +pid.require=\u4E0A\u7EA7ID\uFF0C\u4E0D\u80FD\u4E3A\u7A7A +sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0 + +sysparams.paramcode.require=\u53C2\u6570\u7F16\u7801\u4E0D\u80FD\u4E3A\u7A7A +sysparams.paramvalue.require=\u53C2\u6570\u503C\u4E0D\u80FD\u4E3A\u7A7A + +sysuser.username.require=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A +sysuser.password.require=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A +sysuser.realname.require=\u59D3\u540D\u4E0D\u80FD\u4E3A\u7A7A +sysuser.gender.range=\u6027\u522B\u53D6\u503C\u8303\u56F40~2 +sysuser.email.require=\u90AE\u7BB1\u4E0D\u80FD\u4E3A\u7A7A +sysuser.email.error=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E +sysuser.mobile.require=\u624B\u673A\u53F7\u4E0D\u80FD\u4E3A\u7A7A +sysuser.deptId.require=\u90E8\u95E8\u4E0D\u80FD\u4E3A\u7A7A +sysuser.superadmin.range=\u8D85\u7EA7\u7BA1\u7406\u5458\u53D6\u503C\u8303\u56F40~1 +sysuser.status.range=\u72B6\u6001\u53D6\u503C\u8303\u56F40~1 +sysuser.captcha.require=\u9A8C\u8BC1\u7801\u4E0D\u80FD\u4E3A\u7A7A +sysuser.uuid.require=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A + +sysmenu.pid.require=\u8BF7\u9009\u62E9\u4E0A\u7EA7\u83DC\u5355 +sysmenu.name.require=\u83DC\u5355\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A +sysmenu.type.range=\u83DC\u5355\u7C7B\u578B\u53D6\u503C\u8303\u56F40~1 +sysmenu.openstyle.range=\u83DC\u5355\u6253\u5F00\u65B9\u5F0F\u53D6\u503C\u8303\u56F40~1 + +sysdept.pid.require=\u8BF7\u9009\u62E9\u4E0A\u7EA7\u90E8\u95E8 +sysdept.name.require=\u90E8\u95E8\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A + +sysrole.name.require=\u89D2\u8272\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A + +sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A +sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A +sysdict.label.require=\u5B57\u5178\u6807\u7B7E\u4E0D\u80FD\u4E3A\u7A7A + +schedule.status.range=\u72B6\u6001\u53D6\u503C\u8303\u56F40~1 +schedule.cron.require=cron\u8868\u8FBE\u5F0F\u4E0D\u80FD\u4E3A\u7A7A +schedule.bean.require=bean\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A + +oss.type.range=\u7C7B\u578B\u53D6\u503C\u8303\u56F41~5 + +aliyun.accesskeyid.require=\u963F\u91CC\u4E91AccessKeyId\u4E0D\u80FD\u4E3A\u7A7A +aliyun.accesskeysecret.require=\u963F\u91CC\u4E91AccessKeySecret\u4E0D\u80FD\u4E3A\u7A7A +aliyun.signname.require=\u963F\u91CC\u4E91\u77ED\u4FE1\u7B7E\u540D\u4E0D\u80FD\u4E3A\u7A7A +aliyun.templatecode.require=\u963F\u91CC\u4E91\u77ED\u4FE1\u6A21\u677F\u4E0D\u80FD\u4E3A\u7A7A +aliyun.domain.require=\u963F\u91CC\u4E91\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +aliyun.domain.url=\u963F\u91CC\u4E91\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E +aliyun.endPoint.require=\u963F\u91CC\u4E91EndPoint\u4E0D\u80FD\u4E3A\u7A7A +aliyun.bucketname.require=\u963F\u91CC\u4E91BucketName\u4E0D\u80FD\u4E3A\u7A7A + +qcloud.appid.require=\u817E\u8BAF\u4E91AppId\u4E0D\u80FD\u4E3A\u7A7A +qcloud.appkey.require=\u817E\u8BAF\u4E91AppKey\u4E0D\u80FD\u4E3A\u7A7A +qcloud.secretId.require=\u817E\u8BAF\u4E91SecretId\u4E0D\u80FD\u4E3A\u7A7A +qcloud.secretkey.require=\u817E\u8BAF\u4E91SecretKey\u4E0D\u80FD\u4E3A\u7A7A +qcloud.signname.require=\u817E\u8BAF\u4E91\u77ED\u4FE1\u7B7E\u540D\u4E0D\u80FD\u4E3A\u7A7A +qcloud.templateid.require=\u817E\u8BAF\u4E91\u77ED\u4FE1\u6A21\u677FID\u4E0D\u80FD\u4E3A\u7A7A +qcloud.domain.require=\u817E\u8BAF\u4E91\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +qcloud.domain.url=\u817E\u8BAF\u4E91\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E +qcloud.bucketname.require=\u817E\u8BAF\u4E91BucketName\u4E0D\u80FD\u4E3A\u7A7A +qcloud.region.require=\u6240\u5C5E\u5730\u533A\u4E0D\u80FD\u4E3A\u7A7A + +qiniu.domain.require=\u4E03\u725B\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +qiniu.domain.url=\u4E03\u725B\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E +qiniu.accesskey.require=\u4E03\u725BAccessKey\u4E0D\u80FD\u4E3A\u7A7A +qiniu.secretkey.require=\u4E03\u725BSecretKey\u4E0D\u80FD\u4E3A\u7A7A +qiniu.bucketname.require=\u4E03\u725B\u7A7A\u95F4\u540D\u4E0D\u80FD\u4E3A\u7A7A +qiniu.templateId.require=\u4E03\u725B\u6A21\u677FID\u4E0D\u80FD\u4E3A\u7A7A + +fastdfs.domain.require=FastDFS\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +fastdfs.domain.url=FastDFS\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E + +local.domain.require=\u672C\u5730\u4E0A\u4F20\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +local.domain.url=\u672C\u5730\u4E0A\u4F20\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E +local.path.url=\u5B58\u50A8\u76EE\u5F55\u4E0D\u80FD\u4E3A\u7A7A + +minio.endPoint.require=Minio EndPoint\u4E0D\u80FD\u4E3A\u7A7A +minio.accesskey.require=Minio AccessKey\u4E0D\u80FD\u4E3A\u7A7A +minio.secretkey.require=Minio SecretKey\u4E0D\u80FD\u4E3A\u7A7A +minio.bucketname.require=Minio BucketName\u4E0D\u80FD\u4E3A\u7A7A + +sms.platform.range=\u5E73\u53F0\u7C7B\u578B\u53D6\u503C\u8303\u56F41~2 +email.smtp.require=SMTP\u4E0D\u80FD\u4E3A\u7A7A +email.port.require=\u7AEF\u53E3\u53F7\u4E0D\u80FD\u4E3A\u7A7A +email.username.require=\u90AE\u7BB1\u8D26\u53F7\u4E0D\u80FD\u4E3A\u7A7A +email.password.require=\u90AE\u7BB1\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A + +mail.name.require=\u6A21\u677F\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A +mail.subject.require=\u90AE\u4EF6\u4E3B\u9898\u4E0D\u80FD\u4E3A\u7A7A +mail.content.require=\u90AE\u4EF6\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A + +model.name.require=\u6A21\u578B\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A +model.key.require=\u6A21\u578B\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A + +news.title.require=\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A +news.content.require=\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A +news.pubdate.require=\u53D1\u5E03\u65F6\u95F4\u4E0D\u80FD\u4E3A\u7A7A + +region.id.require=\u533A\u57DF\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A +region.pid.require=\u4E0A\u7EA7\u533A\u57DF\u4E0D\u80FD\u4E3A\u7A7A +region.name.require=\u533A\u57DF\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A + +processBizRoute.procDefId.require=\u6D41\u7A0B\u5B9A\u4E49ID\u4E0D\u80FD\u4E3A\u7A7A +processBizRoute.bizRoute.require=\u4E1A\u52A1\u8DEF\u7531\u4E0D\u80FD\u4E3A\u7A7A +processBizRoute.procDefKey.require=\u6D41\u7A0B\u5B9A\u4E49KEY\u4E0D\u80FD\u4E3A\u7A7A +processBizRoute.version.require=\u6D41\u7A0B\u5B9A\u4E49\u7248\u672C\u53F7\u4E0D\u80FD\u4E3A\u7A7A + +ProcessStart.processDefinitionKey.require=\u6D41\u7A0B\u5B9A\u4E49KEY\u4E0D\u80FD\u4E3A\u7A7A +ProcessStart.businessKey.require=\u4E1A\u52A1KEY\u4E0D\u80FD\u4E3A\u7A7A \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation_en_US.properties b/main/manager-api/src/main/resources/i18n/validation_en_US.properties new file mode 100644 index 000000000..2de9b22cc --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/validation_en_US.properties @@ -0,0 +1,110 @@ +#English +id.require=ID can not be empty +id.null=ID has to be empty +pid.require=Parent ID, cannot be empty +sort.number=The sort value cannot be less than 0 + +sysparams.paramcode.require=Parameter encoding cannot be empty +sysparams.paramvalue.require=Parameter values cannot be empty + +sysuser.username.require=The username cannot be empty +sysuser.password.require=The password cannot be empty +sysuser.realname.require=The realname cannot be empty +sysuser.gender.range=Gender ranges from 0 to 2 +sysuser.email.require=Mailbox cannot be empty +sysuser.email.error=Incorrect email format +sysuser.mobile.require=The phone number cannot be empty +sysuser.deptId.require=Departments cannot be empty +sysuser.superadmin.range=Super administrator values range from 0 to 1 +sysuser.status.range=State ranges from 0 to 1 +sysuser.captcha.require=The captcha cannot be empty +sysuser.uuid.require=The unique identifier cannot be empty + +sysmenu.pid.require=Please select superior menu +sysmenu.name.require=Menu name cannot be empty +sysmenu.type.range=Menu type ranges from 0 to 1 +sysmenu.openstyle.range=Menu open style ranges from 0 to 1 + +sysdept.pid.require=Please select superior department +sysdept.name.require=The department name cannot be empty + +sysrole.name.require=The role name cannot be empty + +sysdict.type.require=The dictionary type cannot be empty +sysdict.name.require=The dictionary name cannot be empty +sysdict.label.require=Dictionary tag cannot be empty + +schedule.status.range=Status ranges from 0 to 1 +schedule.cron.require=Cron expression cannot be empty +schedule.bean.require=Bean name cannot be empty + +oss.type.range=Type ranges from 1 to 5 + +aliyun.accesskeyid.require=Aliyun AccessKeyId cannot be empty +aliyun.accesskeysecret.require=Aliyun AccessKeySecret cannot be empty +aliyun.signname.require=Aliyun message signature cannot be empty +aliyun.templatecode.require=Aliyun message template cannot be empty +aliyun.domain.require=Aliyun bound domain name cannot be empty +aliyun.domain.url=Aliyun binding domain name format is incorrect +aliyun.endPoint.require=The aliyun EndPoint cannot be empty +aliyun.bucketname.require=Aliyun BucketName cannot be empty + +qcloud.appid.require=Tencent cloud AppId cannot be empty +qcloud.appkey.require=Tencent cloud AppKey cannot be empty +qcloud.secretId.require=Tencent cloud SecretId cannot be empty +qcloud.secretkey.require=Tencent cloud SecretKey cannot be empty +qcloud.signname.require=Tencent cloud SMS signature cannot be empty +qcloud.templateid.require=Tencent cloud SMS template ID cannot be empty +qcloud.domain.require=Tencent cloud bound domain name cannot be empty +qcloud.domain.url=Tencent cloud binding domain name format is incorrect +qcloud.bucketname.require=Tencent cloud BucketName cannot be empty +qcloud.region.require=The region cannot be empty + +qiniu.domain.require=Bound domain name cannot be empty +qiniu.domain.url=Binding domain name format is incorrect +qiniu.accesskey.require=The AccessKey cannot be empty +qiniu.secretkey.require=The SecretKey of seven cows cannot be empty +qiniu.bucketname.require=Space names cannot be empty +qiniu.templateId.require=Template ID cannot be empty + +fastdfs.domain.require=FastDFS bound domain name cannot be empty +fastdfs.domain.url=FastDFS bound domain name format is incorrect + +local.domain.require=Local upload bound domain name cannot be empty +local.domain.url=The domain name bound for local upload is not formatted correctly +local.path.url=The storage directory cannot be empty + +minio.endPoint.require=Minio EndPoint cannot be empty +minio.accesskey.require=Minio AccessKey cannot be empty +minio.secretkey.require=Minio SecretKey cannot be empty +minio.bucketname.require=Minio BucketName cannot be empty + +sms.platform.range=Platform type ranges from 1 to 2 + +email.smtp.require=SMTP cannot be empty +email.port.require=Port number cannot be empty +email.username.require=The email account cannot be empty +email.password.require=The password cannot be empty + +mail.name.require=The template name cannot be empty +mail.subject.require=Mail subject cannot be empty +mail.content.require=Message text cannot be empty + +model.name.require=The model name cannot be empty +model.key.require=The model key cannot be empty + +news.title.require=The title cannot be empty +news.content.require=Content cannot be empty +news.pubdate.require=The release time cannot be empty + +region.id.require=Region ID cannot be empty +region.pid.require=Upper area cannot be empty +region.name.require=Region name cannot be empty + +processBizRoute.procDefId.require=Process Definition ID cannot be empty +processBizRoute.bizRoute.require=Service routing cannot be empty +processBizRoute.procDefKey.require=Process Definition KEY cannot be empty +processBizRoute.version.require=Process Definition Version number cannot be empty + +ProcessStart.processDefinitionKey.require=Process Definition KEY cannot be empty +ProcessStart.businessKey.require=Business KEY cannot be empty \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties b/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties new file mode 100644 index 000000000..66d95744e --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/validation_zh_CN.properties @@ -0,0 +1,109 @@ +#\u7B80\u4F53\u4E2D\u6587 +id.require=ID\u4E0D\u80FD\u4E3A\u7A7A +id.null=ID\u5FC5\u987B\u4E3A\u7A7A +pid.require=\u4E0A\u7EA7ID\uFF0C\u4E0D\u80FD\u4E3A\u7A7A +sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u4E8E0 + +sysparams.paramcode.require=\u53C2\u6570\u7F16\u7801\u4E0D\u80FD\u4E3A\u7A7A +sysparams.paramvalue.require=\u53C2\u6570\u503C\u4E0D\u80FD\u4E3A\u7A7A + +sysuser.username.require=\u7528\u6237\u540D\u4E0D\u80FD\u4E3A\u7A7A +sysuser.password.require=\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A +sysuser.realname.require=\u59D3\u540D\u4E0D\u80FD\u4E3A\u7A7A +sysuser.gender.range=\u6027\u522B\u53D6\u503C\u8303\u56F40~2 +sysuser.email.require=\u90AE\u7BB1\u4E0D\u80FD\u4E3A\u7A7A +sysuser.email.error=\u90AE\u7BB1\u683C\u5F0F\u4E0D\u6B63\u786E +sysuser.mobile.require=\u624B\u673A\u53F7\u4E0D\u80FD\u4E3A\u7A7A +sysuser.deptId.require=\u90E8\u95E8\u4E0D\u80FD\u4E3A\u7A7A +sysuser.superadmin.range=\u8D85\u7EA7\u7BA1\u7406\u5458\u53D6\u503C\u8303\u56F40~1 +sysuser.status.range=\u72B6\u6001\u53D6\u503C\u8303\u56F40~1 +sysuser.captcha.require=\u9A8C\u8BC1\u7801\u4E0D\u80FD\u4E3A\u7A7A +sysuser.uuid.require=\u552F\u4E00\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A + +sysmenu.pid.require=\u8BF7\u9009\u62E9\u4E0A\u7EA7\u83DC\u5355 +sysmenu.name.require=\u83DC\u5355\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A +sysmenu.type.range=\u83DC\u5355\u7C7B\u578B\u53D6\u503C\u8303\u56F40~1 +sysmenu.openstyle.range=\u83DC\u5355\u6253\u5F00\u65B9\u5F0F\u53D6\u503C\u8303\u56F40~1 + +sysdept.pid.require=\u8BF7\u9009\u62E9\u4E0A\u7EA7\u90E8\u95E8 +sysdept.name.require=\u90E8\u95E8\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A + +sysrole.name.require=\u89D2\u8272\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A + +sysdict.type.require=\u5B57\u5178\u7C7B\u578B\u4E0D\u80FD\u4E3A\u7A7A +sysdict.name.require=\u5B57\u5178\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A +sysdict.label.require=\u5B57\u5178\u6807\u7B7E\u4E0D\u80FD\u4E3A\u7A7A + +schedule.status.range=\u72B6\u6001\u53D6\u503C\u8303\u56F40~1 +schedule.cron.require=cron\u8868\u8FBE\u5F0F\u4E0D\u80FD\u4E3A\u7A7A +schedule.bean.require=bean\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A + +oss.type.range=\u7C7B\u578B\u53D6\u503C\u8303\u56F41~5 + +aliyun.accesskeyid.require=\u963F\u91CC\u4E91AccessKeyId\u4E0D\u80FD\u4E3A\u7A7A +aliyun.accesskeysecret.require=\u963F\u91CC\u4E91AccessKeySecret\u4E0D\u80FD\u4E3A\u7A7A +aliyun.signname.require=\u963F\u91CC\u4E91\u77ED\u4FE1\u7B7E\u540D\u4E0D\u80FD\u4E3A\u7A7A +aliyun.templatecode.require=\u963F\u91CC\u4E91\u77ED\u4FE1\u6A21\u677F\u4E0D\u80FD\u4E3A\u7A7A +aliyun.domain.require=\u963F\u91CC\u4E91\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +aliyun.domain.url=\u963F\u91CC\u4E91\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E +aliyun.endPoint.require=\u963F\u91CC\u4E91EndPoint\u4E0D\u80FD\u4E3A\u7A7A +aliyun.bucketname.require=\u963F\u91CC\u4E91BucketName\u4E0D\u80FD\u4E3A\u7A7A + +qcloud.appid.require=\u817E\u8BAF\u4E91AppId\u4E0D\u80FD\u4E3A\u7A7A +qcloud.appkey.require=\u817E\u8BAF\u4E91AppKey\u4E0D\u80FD\u4E3A\u7A7A +qcloud.secretId.require=\u817E\u8BAF\u4E91SecretId\u4E0D\u80FD\u4E3A\u7A7A +qcloud.secretkey.require=\u817E\u8BAF\u4E91SecretKey\u4E0D\u80FD\u4E3A\u7A7A +qcloud.signname.require=\u817E\u8BAF\u4E91\u77ED\u4FE1\u7B7E\u540D\u4E0D\u80FD\u4E3A\u7A7A +qcloud.templateid.require=\u817E\u8BAF\u4E91\u77ED\u4FE1\u6A21\u677FID\u4E0D\u80FD\u4E3A\u7A7A +qcloud.domain.require=\u817E\u8BAF\u4E91\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +qcloud.domain.url=\u817E\u8BAF\u4E91\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E +qcloud.bucketname.require=\u817E\u8BAF\u4E91BucketName\u4E0D\u80FD\u4E3A\u7A7A +qcloud.region.require=\u6240\u5C5E\u5730\u533A\u4E0D\u80FD\u4E3A\u7A7A + +qiniu.domain.require=\u4E03\u725B\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +qiniu.domain.url=\u4E03\u725B\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E +qiniu.accesskey.require=\u4E03\u725BAccessKey\u4E0D\u80FD\u4E3A\u7A7A +qiniu.secretkey.require=\u4E03\u725BSecretKey\u4E0D\u80FD\u4E3A\u7A7A +qiniu.bucketname.require=\u4E03\u725B\u7A7A\u95F4\u540D\u4E0D\u80FD\u4E3A\u7A7A +qiniu.templateId.require=\u4E03\u725B\u6A21\u677FID\u4E0D\u80FD\u4E3A\u7A7A + +fastdfs.domain.require=FastDFS\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +fastdfs.domain.url=FastDFS\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E + +local.domain.require=\u672C\u5730\u4E0A\u4F20\u7ED1\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u4E3A\u7A7A +local.domain.url=\u672C\u5730\u4E0A\u4F20\u7ED1\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u786E +local.path.url=\u5B58\u50A8\u76EE\u5F55\u4E0D\u80FD\u4E3A\u7A7A + +minio.endPoint.require=Minio EndPoint\u4E0D\u80FD\u4E3A\u7A7A +minio.accesskey.require=Minio AccessKey\u4E0D\u80FD\u4E3A\u7A7A +minio.secretkey.require=Minio SecretKey\u4E0D\u80FD\u4E3A\u7A7A +minio.bucketname.require=Minio BucketName\u4E0D\u80FD\u4E3A\u7A7A + +sms.platform.range=\u5E73\u53F0\u7C7B\u578B\u53D6\u503C\u8303\u56F41~2 +email.smtp.require=SMTP\u4E0D\u80FD\u4E3A\u7A7A +email.port.require=\u7AEF\u53E3\u53F7\u4E0D\u80FD\u4E3A\u7A7A +email.username.require=\u90AE\u7BB1\u8D26\u53F7\u4E0D\u80FD\u4E3A\u7A7A +email.password.require=\u90AE\u7BB1\u5BC6\u7801\u4E0D\u80FD\u4E3A\u7A7A + +mail.name.require=\u6A21\u677F\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A +mail.subject.require=\u90AE\u4EF6\u4E3B\u9898\u4E0D\u80FD\u4E3A\u7A7A +mail.content.require=\u90AE\u4EF6\u6B63\u6587\u4E0D\u80FD\u4E3A\u7A7A + +model.name.require=\u6A21\u578B\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A +model.key.require=\u6A21\u578B\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A + +news.title.require=\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A +news.content.require=\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A +news.pubdate.require=\u53D1\u5E03\u65F6\u95F4\u4E0D\u80FD\u4E3A\u7A7A + +region.id.require=\u533A\u57DF\u6807\u8BC6\u4E0D\u80FD\u4E3A\u7A7A +region.pid.require=\u4E0A\u7EA7\u533A\u57DF\u4E0D\u80FD\u4E3A\u7A7A +region.name.require=\u533A\u57DF\u540D\u79F0\u4E0D\u80FD\u4E3A\u7A7A + +processBizRoute.procDefId.require=\u6D41\u7A0B\u5B9A\u4E49ID\u4E0D\u80FD\u4E3A\u7A7A +processBizRoute.bizRoute.require=\u4E1A\u52A1\u8DEF\u7531\u4E0D\u80FD\u4E3A\u7A7A +processBizRoute.procDefKey.require=\u6D41\u7A0B\u5B9A\u4E49KEY\u4E0D\u80FD\u4E3A\u7A7A +processBizRoute.version.require=\u6D41\u7A0B\u5B9A\u4E49\u7248\u672C\u53F7\u4E0D\u80FD\u4E3A\u7A7A + +ProcessStart.processDefinitionKey.require=\u6D41\u7A0B\u5B9A\u4E49KEY\u4E0D\u80FD\u4E3A\u7A7A +ProcessStart.businessKey.require=\u4E1A\u52A1KEY\u4E0D\u80FD\u4E3A\u7A7A \ No newline at end of file diff --git a/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties b/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties new file mode 100644 index 000000000..6680e10ac --- /dev/null +++ b/main/manager-api/src/main/resources/i18n/validation_zh_TW.properties @@ -0,0 +1,110 @@ +#\u7E41\u4F53\u4E2D\u6587 +id.require=ID\u4E0D\u80FD\u70BA\u7A7A +id.null=ID\u5FC5\u9808\u70BA\u7A7A +pid.require=\u4E0A\u7D1AID\uFF0C\u4E0D\u80FD\u70BA\u7A7A +sort.number=\u6392\u5E8F\u503C\u4E0D\u80FD\u5C0F\u65BC0 + +sysparams.paramcode.require=\u53C3\u6578\u7DE8\u78BC\u4E0D\u80FD\u70BA\u7A7A +sysparams.paramvalue.require=\u53C3\u6578\u503C\u4E0D\u80FD\u70BA\u7A7A + +sysuser.username.require=\u7528\u6236\u540D\u4E0D\u80FD\u70BA\u7A7A +sysuser.password.require=\u5BC6\u78BC\u4E0D\u80FD\u70BA\u7A7A +sysuser.realname.require=\u59D3\u540D\u4E0D\u80FD\u70BA\u7A7A +sysuser.gender.range=\u6027\u5225\u53D6\u503C\u7BC4\u570D0~2 +sysuser.email.require=\u90F5\u7BB1\u4E0D\u80FD\u70BA\u7A7A +sysuser.email.error=\u90F5\u7BB1\u683C\u5F0F\u4E0D\u6B63\u78BA +sysuser.mobile.require=\u624B\u6A5F\u865F\u4E0D\u80FD\u70BA\u7A7A +sysuser.deptId.require=\u90E8\u9580\u4E0D\u80FD\u70BA\u7A7A +sysuser.superadmin.range=\u8D85\u7D1A\u7BA1\u7406\u54E1\u53D6\u503C\u7BC4\u570D0~1 +sysuser.status.range=\u72C0\u614B\u53D6\u503C\u7BC4\u570D0~1 +sysuser.captcha.require=\u9A57\u8B49\u78BC\u4E0D\u80FD\u70BA\u7A7A +sysuser.uuid.require=\u552F\u4E00\u6A19\u8B58\u4E0D\u80FD\u70BA\u7A7A + +sysmenu.pid.require=\u8ACB\u9078\u64C7\u4E0A\u7D1A\u83DC\u55AE +sysmenu.name.require=\u83DC\u55AE\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A +sysmenu.type.range=\u83DC\u55AE\u985E\u578B\u53D6\u503C\u7BC4\u570D0~1 +sysmenu.openstyle.range=\u83DC\u55AE\u6253\u958B\u65B9\u5F0F\u53D6\u503C\u7BC4\u570D0~1 + +sysdept.pid.require=\u8ACB\u9078\u64C7\u4E0A\u7D1A\u90E8\u9580 +sysdept.name.require=\u90E8\u9580\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A + +sysrole.name.require=\u89D2\u8272\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A + +sysdict.type.require=\u5B57\u5178\u985E\u578B\u4E0D\u80FD\u70BA\u7A7A +sysdict.name.require=\u5B57\u5178\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A +sysdict.label.require=\u5B57\u5178\u6A19\u7C64\u4E0D\u80FD\u70BA\u7A7A + +schedule.status.range=\u72C0\u614B\u53D6\u503C\u7BC4\u570D0~1 +schedule.cron.require=cron\u8868\u9054\u5F0F\u4E0D\u80FD\u70BA\u7A7A +schedule.bean.require=bean\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A + +oss.type.range=\u985E\u578B\u53D6\u503C\u7BC4\u570D1~5 + +aliyun.accesskeyid.require=\u963F\u91CC\u96F2AccessKeyId\u4E0D\u80FD\u70BA\u7A7A +aliyun.accesskeysecret.require=\u963F\u91CC\u96F2AccessKeySecret\u4E0D\u80FD\u70BA\u7A7A +aliyun.signname.require=\u963F\u91CC\u96F2\u77ED\u4FE1\u7C3D\u540D\u4E0D\u80FD\u70BA\u7A7A +aliyun.templatecode.require=\u963F\u91CC\u96F2\u77ED\u4FE1\u6A21\u677F\u4E0D\u80FD\u70BA\u7A7A +aliyun.domain.require=\u963F\u91CC\u96F2\u7D81\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u70BA\u7A7A +aliyun.domain.url=\u963F\u91CC\u96F2\u7D81\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u78BA +aliyun.endPoint.require=\u963F\u91CC\u96F2EndPoint\u4E0D\u80FD\u70BA\u7A7A +aliyun.bucketname.require=\u963F\u91CC\u96F2BucketName\u4E0D\u80FD\u70BA\u7A7A + +qcloud.appid.require=\u9A30\u8A0A\u96F2AppId\u4E0D\u80FD\u70BA\u7A7A +qcloud.appkey.require=\u9A30\u8A0A\u96F2AppKey\u4E0D\u80FD\u70BA\u7A7A +qcloud.secretId.require=\u9A30\u8A0A\u96F2SecretId\u4E0D\u80FD\u70BA\u7A7A +qcloud.secretkey.require=\u9A30\u8A0A\u96F2SecretKey\u4E0D\u80FD\u70BA\u7A7A +qcloud.signname.require=\u9A30\u8A0A\u96F2\u77ED\u4FE1\u7C3D\u540D\u4E0D\u80FD\u70BA\u7A7A +qcloud.templateid.require=\u9A30\u8A0A\u96F2\u77ED\u4FE1\u6A21\u677FID\u4E0D\u80FD\u70BA\u7A7A +qcloud.domain.require=\u9A30\u8A0A\u96F2\u7D81\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u70BA\u7A7A +qcloud.domain.url=\u9A30\u8A0A\u96F2\u7D81\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u78BA +qcloud.bucketname.require=\u9A30\u8A0A\u96F2BucketName\u4E0D\u80FD\u70BA\u7A7A +qcloud.region.require=\u6240\u5C6C\u5730\u5340\u4E0D\u80FD\u70BA\u7A7A + +qiniu.domain.require=\u4E03\u725B\u7D81\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u70BA\u7A7A +qiniu.domain.url=\u4E03\u725B\u7D81\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u78BA +qiniu.accesskey.require=\u4E03\u725BAccessKey\u4E0D\u80FD\u70BA\u7A7A +qiniu.secretkey.require=\u4E03\u725BSecretKey\u4E0D\u80FD\u70BA\u7A7A +qiniu.bucketname.require=\u4E03\u725B\u7A7A\u9593\u540D\u4E0D\u80FD\u70BA\u7A7A +qiniu.templateId.require=\u4E03\u725B\u6A21\u677FID\u4E0D\u80FD\u70BA\u7A7A + +fastdfs.domain.require=FastDFS\u7D81\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u70BA\u7A7A +fastdfs.domain.url=FastDFS\u7D81\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u78BA + +local.domain.require=\u672C\u5730\u4E0A\u50B3\u7D81\u5B9A\u7684\u57DF\u540D\u4E0D\u80FD\u70BA\u7A7A +local.domain.url=\u672C\u5730\u4E0A\u50B3\u7D81\u5B9A\u7684\u57DF\u540D\u683C\u5F0F\u4E0D\u6B63\u78BA +local.path.url=\u5B58\u5132\u76EE\u9304\u4E0D\u80FD\u70BA\u7A7A + +minio.endPoint.require=Minio EndPoint\u4E0D\u80FD\u70BA\u7A7A +minio.accesskey.require=Minio AccessKey\u4E0D\u80FD\u70BA\u7A7A +minio.secretkey.require=Minio SecretKey\u4E0D\u80FD\u70BA\u7A7A +minio.bucketname.require=Minio BucketName\u4E0D\u80FD\u70BA\u7A7A + +sms.platform.range=\u5E73\u53F0\u985E\u578B\u53D6\u503C\u7BC4\u570D1~2 + +email.smtp.require=SMTP\u4E0D\u80FD\u70BA\u7A7A +email.port.require=\u7AEF\u53E3\u865F\u4E0D\u80FD\u70BA\u7A7A +email.username.require=\u90F5\u7BB1\u8CEC\u865F\u4E0D\u80FD\u70BA\u7A7A +email.password.require=\u90F5\u7BB1\u5BC6\u78BC\u4E0D\u80FD\u70BA\u7A7A + +mail.name.require=\u6A21\u677F\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A +mail.subject.require=\u90F5\u4EF6\u4E3B\u984C\u4E0D\u80FD\u70BA\u7A7A +mail.content.require=\u90F5\u4EF6\u6B63\u6587\u4E0D\u80FD\u70BA\u7A7A + +model.name.require=\u6A21\u578B\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A +model.key.require=\u6A21\u578B\u6A19\u8B58\u4E0D\u80FD\u70BA\u7A7A + +news.title.require=\u6A19\u984C\u4E0D\u80FD\u70BA\u7A7A +news.content.require=\u5167\u5BB9\u4E0D\u80FD\u70BA\u7A7A +news.pubdate.require=\u767C\u4F48\u6642\u9593\u4E0D\u80FD\u70BA\u7A7A + +region.id.require=\u5340\u57DF\u6A19\u8B58\u4E0D\u80FD\u70BA\u7A7A +region.pid.require=\u4E0A\u7D1A\u5340\u57DF\u4E0D\u80FD\u70BA\u7A7A +region.name.require=\u5340\u57DF\u540D\u7A31\u4E0D\u80FD\u70BA\u7A7A + +processBizRoute.procDefId.require=\u6D41\u7A0B\u5B9A\u7FA9ID\u4E0D\u80FD\u70BA\u7A7A +processBizRoute.bizRoute.require=\u696D\u52D9\u8DEF\u7531\u4E0D\u80FD\u70BA\u7A7A +processBizRoute.procDefKey.require=\u6D41\u7A0B\u5B9A\u7FA9KEY\u4E0D\u80FD\u70BA\u7A7A +processBizRoute.version.require=\u6D41\u7A0B\u5B9A\u7FA9\u7248\u672C\u865F\u4E0D\u80FD\u70BA\u7A7A + +ProcessStart.processDefinitionKey.require=\u6D41\u7A0B\u5B9A\u7FA9KEY\u4E0D\u80FD\u70BA\u7A7A +ProcessStart.businessKey.require=\u696D\u52D9KEY\u4E0D\u80FD\u70BA\u7A7A \ No newline at end of file diff --git a/main/manager-api/src/main/resources/logback-spring.xml b/main/manager-api/src/main/resources/logback-spring.xml new file mode 100644 index 000000000..68ea4cf60 --- /dev/null +++ b/main/manager-api/src/main/resources/logback-spring.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + + + /system/logs/admin.%d{yyyy-MM-dd}.%i.log + + 1MB + + 7 + + + + %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n + + + + + + + + \ No newline at end of file diff --git a/main/manager-api/src/main/resources/mapper/sys/SysDictDataDao.xml b/main/manager-api/src/main/resources/mapper/sys/SysDictDataDao.xml new file mode 100644 index 000000000..7ea5e4293 --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/sys/SysDictDataDao.xml @@ -0,0 +1,13 @@ + + + + + + + + + \ No newline at end of file diff --git a/main/manager-api/src/main/resources/mapper/sys/SysDictTypeDao.xml b/main/manager-api/src/main/resources/mapper/sys/SysDictTypeDao.xml new file mode 100644 index 000000000..11887552b --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/sys/SysDictTypeDao.xml @@ -0,0 +1,10 @@ + + + + + + + + \ No newline at end of file diff --git a/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml b/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml new file mode 100644 index 000000000..3d19352ee --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/sys/SysParamsDao.xml @@ -0,0 +1,23 @@ + + + + + + + + + + + + + + update sys_params set param_value = #{paramValue} where param_code = #{paramCode} + + \ No newline at end of file diff --git a/main/manager-api/src/main/resources/mapper/sys/SysUserDao.xml b/main/manager-api/src/main/resources/mapper/sys/SysUserDao.xml new file mode 100644 index 000000000..1ecf05fec --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/sys/SysUserDao.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + update sys_user set password = #{newPassword} where id = #{id} + + + + + + + \ No newline at end of file diff --git a/main/manager-api/src/main/resources/mapper/sys/SysUserTokenDao.xml b/main/manager-api/src/main/resources/mapper/sys/SysUserTokenDao.xml new file mode 100644 index 000000000..2aca0ab89 --- /dev/null +++ b/main/manager-api/src/main/resources/mapper/sys/SysUserTokenDao.xml @@ -0,0 +1,17 @@ + + + + + + + + + + + update sys_user_token set expire_date = #{expireDate} where user_id = #{userId} + + \ No newline at end of file diff --git a/main/manager-api/src/test/java/xiaozhi/DbEncTest.java b/main/manager-api/src/test/java/xiaozhi/DbEncTest.java new file mode 100755 index 000000000..f3b18309f --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/DbEncTest.java @@ -0,0 +1,25 @@ +package xiaozhi; + +import org.jasypt.encryption.StringEncryptor; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * 单元测试 + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class DbEncTest { + + @Autowired + StringEncryptor stringEncryptor; + + @Test + public void jiami() { + System.out.println("username:" + stringEncryptor.encrypt("07e43e8d669fb946e31ccd4ef5f32c9f2287619c79b766a5985d2c99ad7b7c7e")); + System.out.println("password:" + stringEncryptor.encrypt("042e94093fd2c2765ea45cf13ddbfd38e93026df4b6d5e4206ea5ac90956d63ab73e8b82c6daf7829f9aea7e27e1db5bb0a90944c4c4985af44db0ef49c46d6ad6")); + } +} diff --git a/main/manager-api/src/test/java/xiaozhi/RedisTest.java b/main/manager-api/src/test/java/xiaozhi/RedisTest.java new file mode 100644 index 000000000..3fe5384a8 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/RedisTest.java @@ -0,0 +1,27 @@ +package xiaozhi; + +import xiaozhi.common.redis.RedisUtils; +import xiaozhi.modules.sys.entity.SysUserEntity; +import jakarta.annotation.Resource; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +public class RedisTest { + @Resource + private RedisUtils redisUtils; + + @Test + public void contextLoads() { + SysUserEntity user = new SysUserEntity(); + user.setEmail("123456@qq.com"); + redisUtils.set("user", user); + + System.out.println(ToStringBuilder.reflectionToString(redisUtils.get("user"))); + } + +} \ No newline at end of file diff --git a/main/manager-api/src/test/java/xiaozhi/service/DynamicDataSourceTestService.java b/main/manager-api/src/test/java/xiaozhi/service/DynamicDataSourceTestService.java new file mode 100644 index 000000000..9b4f18141 --- /dev/null +++ b/main/manager-api/src/test/java/xiaozhi/service/DynamicDataSourceTestService.java @@ -0,0 +1,24 @@ +package xiaozhi.service; + +import xiaozhi.modules.sys.dao.SysUserDao; +import xiaozhi.modules.sys.entity.SysUserEntity; +import jakarta.annotation.Resource; +import org.springframework.stereotype.Service; + +/** + * 测试多数据源 + */ +@Service +public class DynamicDataSourceTestService { + @Resource + private SysUserDao sysUserDao; + + //@Transactional + public void updateUser(Long id) { + SysUserEntity user = new SysUserEntity(); + user.setId(id); + user.setMobile("13500000000"); + //sysUserDao.updateById(user); + System.out.println(sysUserDao.selectById(id)); + } +} \ No newline at end of file diff --git a/web/vue/README.md b/main/manager-web/README.md similarity index 100% rename from web/vue/README.md rename to main/manager-web/README.md diff --git a/web/vue/jsconfig.json b/main/manager-web/jsconfig.json similarity index 100% rename from web/vue/jsconfig.json rename to main/manager-web/jsconfig.json diff --git a/web/vue/package-lock.json b/main/manager-web/package-lock.json similarity index 100% rename from web/vue/package-lock.json rename to main/manager-web/package-lock.json diff --git a/web/vue/package.json b/main/manager-web/package.json similarity index 100% rename from web/vue/package.json rename to main/manager-web/package.json diff --git a/web/vue/public/favicon.ico b/main/manager-web/public/favicon.ico similarity index 100% rename from web/vue/public/favicon.ico rename to main/manager-web/public/favicon.ico diff --git a/web/vue/public/index.html b/main/manager-web/public/index.html similarity index 100% rename from web/vue/public/index.html rename to main/manager-web/public/index.html diff --git a/web/vue/src/App.vue b/main/manager-web/src/App.vue similarity index 100% rename from web/vue/src/App.vue rename to main/manager-web/src/App.vue diff --git a/web/vue/src/assets/home/avatar.png b/main/manager-web/src/assets/home/avatar.png similarity index 100% rename from web/vue/src/assets/home/avatar.png rename to main/manager-web/src/assets/home/avatar.png diff --git a/web/vue/src/assets/home/background.png b/main/manager-web/src/assets/home/background.png similarity index 100% rename from web/vue/src/assets/home/background.png rename to main/manager-web/src/assets/home/background.png diff --git a/web/vue/src/assets/home/close.png b/main/manager-web/src/assets/home/close.png similarity index 100% rename from web/vue/src/assets/home/close.png rename to main/manager-web/src/assets/home/close.png diff --git a/web/vue/src/assets/home/delete.png b/main/manager-web/src/assets/home/delete.png similarity index 100% rename from web/vue/src/assets/home/delete.png rename to main/manager-web/src/assets/home/delete.png diff --git a/web/vue/src/assets/home/equipment.png b/main/manager-web/src/assets/home/equipment.png similarity index 100% rename from web/vue/src/assets/home/equipment.png rename to main/manager-web/src/assets/home/equipment.png diff --git a/web/vue/src/assets/home/info.png b/main/manager-web/src/assets/home/info.png similarity index 100% rename from web/vue/src/assets/home/info.png rename to main/manager-web/src/assets/home/info.png diff --git a/web/vue/src/assets/home/main-top-bg.png b/main/manager-web/src/assets/home/main-top-bg.png similarity index 100% rename from web/vue/src/assets/home/main-top-bg.png rename to main/manager-web/src/assets/home/main-top-bg.png diff --git a/web/vue/src/assets/home/red-info.png b/main/manager-web/src/assets/home/red-info.png similarity index 100% rename from web/vue/src/assets/home/red-info.png rename to main/manager-web/src/assets/home/red-info.png diff --git a/web/vue/src/assets/home/search.png b/main/manager-web/src/assets/home/search.png similarity index 100% rename from web/vue/src/assets/home/search.png rename to main/manager-web/src/assets/home/search.png diff --git a/web/vue/src/assets/home/setting-user.png b/main/manager-web/src/assets/home/setting-user.png similarity index 100% rename from web/vue/src/assets/home/setting-user.png rename to main/manager-web/src/assets/home/setting-user.png diff --git a/web/vue/src/assets/login/background.png b/main/manager-web/src/assets/login/background.png similarity index 100% rename from web/vue/src/assets/login/background.png rename to main/manager-web/src/assets/login/background.png diff --git a/web/vue/src/assets/login/down-arrow.png b/main/manager-web/src/assets/login/down-arrow.png similarity index 100% rename from web/vue/src/assets/login/down-arrow.png rename to main/manager-web/src/assets/login/down-arrow.png diff --git a/web/vue/src/assets/login/hi.png b/main/manager-web/src/assets/login/hi.png similarity index 100% rename from web/vue/src/assets/login/hi.png rename to main/manager-web/src/assets/login/hi.png diff --git a/web/vue/src/assets/login/password.png b/main/manager-web/src/assets/login/password.png similarity index 100% rename from web/vue/src/assets/login/password.png rename to main/manager-web/src/assets/login/password.png diff --git a/web/vue/src/assets/login/phone.png b/main/manager-web/src/assets/login/phone.png similarity index 100% rename from web/vue/src/assets/login/phone.png rename to main/manager-web/src/assets/login/phone.png diff --git a/web/vue/src/assets/login/shield.png b/main/manager-web/src/assets/login/shield.png similarity index 100% rename from web/vue/src/assets/login/shield.png rename to main/manager-web/src/assets/login/shield.png diff --git a/web/vue/src/assets/login/username.png b/main/manager-web/src/assets/login/username.png similarity index 100% rename from web/vue/src/assets/login/username.png rename to main/manager-web/src/assets/login/username.png diff --git a/web/vue/src/assets/logo.png b/main/manager-web/src/assets/logo.png similarity index 100% rename from web/vue/src/assets/logo.png rename to main/manager-web/src/assets/logo.png diff --git a/web/vue/src/assets/welcome/background.png b/main/manager-web/src/assets/welcome/background.png similarity index 100% rename from web/vue/src/assets/welcome/background.png rename to main/manager-web/src/assets/welcome/background.png diff --git a/web/vue/src/assets/welcome/github.png b/main/manager-web/src/assets/welcome/github.png similarity index 100% rename from web/vue/src/assets/welcome/github.png rename to main/manager-web/src/assets/welcome/github.png diff --git a/web/vue/src/assets/welcome/more.png b/main/manager-web/src/assets/welcome/more.png similarity index 100% rename from web/vue/src/assets/welcome/more.png rename to main/manager-web/src/assets/welcome/more.png diff --git a/web/vue/src/assets/welcome/questions.png b/main/manager-web/src/assets/welcome/questions.png similarity index 100% rename from web/vue/src/assets/welcome/questions.png rename to main/manager-web/src/assets/welcome/questions.png diff --git a/web/vue/src/assets/xiaozhi-ai.png b/main/manager-web/src/assets/xiaozhi-ai.png similarity index 100% rename from web/vue/src/assets/xiaozhi-ai.png rename to main/manager-web/src/assets/xiaozhi-ai.png diff --git a/web/vue/src/assets/xiaozhi-logo.png b/main/manager-web/src/assets/xiaozhi-logo.png similarity index 100% rename from web/vue/src/assets/xiaozhi-logo.png rename to main/manager-web/src/assets/xiaozhi-logo.png diff --git a/web/vue/src/components/HelloWorld.vue b/main/manager-web/src/components/HelloWorld.vue similarity index 100% rename from web/vue/src/components/HelloWorld.vue rename to main/manager-web/src/components/HelloWorld.vue diff --git a/web/vue/src/main.js b/main/manager-web/src/main.js similarity index 100% rename from web/vue/src/main.js rename to main/manager-web/src/main.js diff --git a/web/vue/src/router/index.js b/main/manager-web/src/router/index.js similarity index 100% rename from web/vue/src/router/index.js rename to main/manager-web/src/router/index.js diff --git a/web/vue/src/store/index.js b/main/manager-web/src/store/index.js similarity index 100% rename from web/vue/src/store/index.js rename to main/manager-web/src/store/index.js diff --git a/web/vue/src/views/home.vue b/main/manager-web/src/views/home.vue similarity index 100% rename from web/vue/src/views/home.vue rename to main/manager-web/src/views/home.vue diff --git a/web/vue/src/views/login.vue b/main/manager-web/src/views/login.vue similarity index 100% rename from web/vue/src/views/login.vue rename to main/manager-web/src/views/login.vue diff --git a/web/vue/src/views/welcome.vue b/main/manager-web/src/views/welcome.vue similarity index 100% rename from web/vue/src/views/welcome.vue rename to main/manager-web/src/views/welcome.vue diff --git a/.dockerignore b/main/xiaozhi-server/.dockerignore similarity index 92% rename from .dockerignore rename to main/xiaozhi-server/.dockerignore index 26d30488e..c64944ead 100644 --- a/.dockerignore +++ b/main/xiaozhi-server/.dockerignore @@ -3,7 +3,7 @@ __pycache__ *.pyc .env Dockerfile -docs/ +../docs/ tmp/ data/ LICENSE diff --git a/Dockerfile b/main/xiaozhi-server/Dockerfile similarity index 100% rename from Dockerfile rename to main/xiaozhi-server/Dockerfile diff --git a/Dockerfile-pip b/main/xiaozhi-server/Dockerfile-pip similarity index 100% rename from Dockerfile-pip rename to main/xiaozhi-server/Dockerfile-pip diff --git a/app.py b/main/xiaozhi-server/app.py similarity index 100% rename from app.py rename to main/xiaozhi-server/app.py diff --git a/config.yaml b/main/xiaozhi-server/config.yaml similarity index 100% rename from config.yaml rename to main/xiaozhi-server/config.yaml diff --git a/config/logger.py b/main/xiaozhi-server/config/logger.py similarity index 100% rename from config/logger.py rename to main/xiaozhi-server/config/logger.py diff --git a/config/private_config.py b/main/xiaozhi-server/config/private_config.py similarity index 100% rename from config/private_config.py rename to main/xiaozhi-server/config/private_config.py diff --git a/config/settings.py b/main/xiaozhi-server/config/settings.py similarity index 100% rename from config/settings.py rename to main/xiaozhi-server/config/settings.py diff --git a/core/auth.py b/main/xiaozhi-server/core/auth.py similarity index 100% rename from core/auth.py rename to main/xiaozhi-server/core/auth.py diff --git a/core/connection.py b/main/xiaozhi-server/core/connection.py similarity index 100% rename from core/connection.py rename to main/xiaozhi-server/core/connection.py diff --git a/core/handle/abortHandle.py b/main/xiaozhi-server/core/handle/abortHandle.py similarity index 100% rename from core/handle/abortHandle.py rename to main/xiaozhi-server/core/handle/abortHandle.py diff --git a/core/handle/helloHandle.py b/main/xiaozhi-server/core/handle/helloHandle.py similarity index 100% rename from core/handle/helloHandle.py rename to main/xiaozhi-server/core/handle/helloHandle.py diff --git a/core/handle/iotHandle.py b/main/xiaozhi-server/core/handle/iotHandle.py similarity index 100% rename from core/handle/iotHandle.py rename to main/xiaozhi-server/core/handle/iotHandle.py diff --git a/core/handle/musicHandler.py b/main/xiaozhi-server/core/handle/musicHandler.py similarity index 100% rename from core/handle/musicHandler.py rename to main/xiaozhi-server/core/handle/musicHandler.py diff --git a/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py similarity index 100% rename from core/handle/receiveAudioHandle.py rename to main/xiaozhi-server/core/handle/receiveAudioHandle.py diff --git a/core/handle/sendAudioHandle.py b/main/xiaozhi-server/core/handle/sendAudioHandle.py similarity index 100% rename from core/handle/sendAudioHandle.py rename to main/xiaozhi-server/core/handle/sendAudioHandle.py diff --git a/core/handle/textHandle.py b/main/xiaozhi-server/core/handle/textHandle.py similarity index 100% rename from core/handle/textHandle.py rename to main/xiaozhi-server/core/handle/textHandle.py diff --git a/core/providers/asr/base.py b/main/xiaozhi-server/core/providers/asr/base.py similarity index 100% rename from core/providers/asr/base.py rename to main/xiaozhi-server/core/providers/asr/base.py diff --git a/core/providers/asr/doubao.py b/main/xiaozhi-server/core/providers/asr/doubao.py similarity index 100% rename from core/providers/asr/doubao.py rename to main/xiaozhi-server/core/providers/asr/doubao.py diff --git a/core/providers/asr/fun_local.py b/main/xiaozhi-server/core/providers/asr/fun_local.py similarity index 100% rename from core/providers/asr/fun_local.py rename to main/xiaozhi-server/core/providers/asr/fun_local.py diff --git a/core/providers/llm/base.py b/main/xiaozhi-server/core/providers/llm/base.py similarity index 100% rename from core/providers/llm/base.py rename to main/xiaozhi-server/core/providers/llm/base.py diff --git a/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py similarity index 100% rename from core/providers/llm/coze/coze.py rename to main/xiaozhi-server/core/providers/llm/coze/coze.py diff --git a/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py similarity index 100% rename from core/providers/llm/dify/dify.py rename to main/xiaozhi-server/core/providers/llm/dify/dify.py diff --git a/core/providers/llm/gemini/gemini.py b/main/xiaozhi-server/core/providers/llm/gemini/gemini.py similarity index 100% rename from core/providers/llm/gemini/gemini.py rename to main/xiaozhi-server/core/providers/llm/gemini/gemini.py diff --git a/core/providers/llm/homeassistant/homeassistant.py b/main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py similarity index 100% rename from core/providers/llm/homeassistant/homeassistant.py rename to main/xiaozhi-server/core/providers/llm/homeassistant/homeassistant.py diff --git a/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py similarity index 100% rename from core/providers/llm/ollama/ollama.py rename to main/xiaozhi-server/core/providers/llm/ollama/ollama.py diff --git a/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py similarity index 100% rename from core/providers/llm/openai/openai.py rename to main/xiaozhi-server/core/providers/llm/openai/openai.py diff --git a/core/providers/tts/aliyun.py b/main/xiaozhi-server/core/providers/tts/aliyun.py similarity index 100% rename from core/providers/tts/aliyun.py rename to main/xiaozhi-server/core/providers/tts/aliyun.py diff --git a/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py similarity index 100% rename from core/providers/tts/base.py rename to main/xiaozhi-server/core/providers/tts/base.py diff --git a/core/providers/tts/cozecn.py b/main/xiaozhi-server/core/providers/tts/cozecn.py similarity index 100% rename from core/providers/tts/cozecn.py rename to main/xiaozhi-server/core/providers/tts/cozecn.py diff --git a/core/providers/tts/doubao.py b/main/xiaozhi-server/core/providers/tts/doubao.py similarity index 100% rename from core/providers/tts/doubao.py rename to main/xiaozhi-server/core/providers/tts/doubao.py diff --git a/core/providers/tts/edge.py b/main/xiaozhi-server/core/providers/tts/edge.py similarity index 100% rename from core/providers/tts/edge.py rename to main/xiaozhi-server/core/providers/tts/edge.py diff --git a/core/providers/tts/fishspeech.py b/main/xiaozhi-server/core/providers/tts/fishspeech.py similarity index 100% rename from core/providers/tts/fishspeech.py rename to main/xiaozhi-server/core/providers/tts/fishspeech.py diff --git a/core/providers/tts/gpt_sovits_v2.py b/main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py similarity index 100% rename from core/providers/tts/gpt_sovits_v2.py rename to main/xiaozhi-server/core/providers/tts/gpt_sovits_v2.py diff --git a/core/providers/tts/minimax.py b/main/xiaozhi-server/core/providers/tts/minimax.py similarity index 100% rename from core/providers/tts/minimax.py rename to main/xiaozhi-server/core/providers/tts/minimax.py diff --git a/core/providers/tts/siliconflow.py b/main/xiaozhi-server/core/providers/tts/siliconflow.py similarity index 100% rename from core/providers/tts/siliconflow.py rename to main/xiaozhi-server/core/providers/tts/siliconflow.py diff --git a/core/utils/asr.py b/main/xiaozhi-server/core/utils/asr.py similarity index 100% rename from core/utils/asr.py rename to main/xiaozhi-server/core/utils/asr.py diff --git a/core/utils/auth_code_gen.py b/main/xiaozhi-server/core/utils/auth_code_gen.py similarity index 100% rename from core/utils/auth_code_gen.py rename to main/xiaozhi-server/core/utils/auth_code_gen.py diff --git a/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py similarity index 100% rename from core/utils/dialogue.py rename to main/xiaozhi-server/core/utils/dialogue.py diff --git a/core/utils/llm.py b/main/xiaozhi-server/core/utils/llm.py similarity index 100% rename from core/utils/llm.py rename to main/xiaozhi-server/core/utils/llm.py diff --git a/core/utils/lock_manager.py b/main/xiaozhi-server/core/utils/lock_manager.py similarity index 100% rename from core/utils/lock_manager.py rename to main/xiaozhi-server/core/utils/lock_manager.py diff --git a/core/utils/p3.py b/main/xiaozhi-server/core/utils/p3.py similarity index 100% rename from core/utils/p3.py rename to main/xiaozhi-server/core/utils/p3.py diff --git a/core/utils/tts.py b/main/xiaozhi-server/core/utils/tts.py similarity index 100% rename from core/utils/tts.py rename to main/xiaozhi-server/core/utils/tts.py diff --git a/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py similarity index 100% rename from core/utils/util.py rename to main/xiaozhi-server/core/utils/util.py diff --git a/core/utils/vad.py b/main/xiaozhi-server/core/utils/vad.py similarity index 100% rename from core/utils/vad.py rename to main/xiaozhi-server/core/utils/vad.py diff --git a/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py similarity index 100% rename from core/websocket_server.py rename to main/xiaozhi-server/core/websocket_server.py diff --git a/main/xiaozhi-server/data/.config.yaml b/main/xiaozhi-server/data/.config.yaml new file mode 100644 index 000000000..0ca5e40ca --- /dev/null +++ b/main/xiaozhi-server/data/.config.yaml @@ -0,0 +1,360 @@ +# 如果您是一名开发者,建议阅读以下内容。如果不是开发者,可以忽略这部分内容。 +# 在开发中,在项目根目录创建data目录,将【config.yaml】复制一份,改成【.config.yaml】,放进data目录中 +# 系统会优先读取【data/.config.yaml】文件的配置。 +# 这样做,可以避免在提交代码的时候,错误地提交密钥信息,保护您的密钥安全。 + +# 服务器基础配置(Basic server configuration) +server: + # 服务器监听地址和端口(Server listening address and port) + ip: 0.0.0.0 + port: 8000 + # 认证配置 + auth: + # 是否启用认证 + enabled: false + # 设备的token,可以在编译固件的环节,写入你自己定义的token + # 固件上的token和以下的token如果能对应,才能连接本服务端 + tokens: + - token: "your-token1" # 设备1的token + name: "your-device-name1" # 设备1标识 + - token: "your-token2" # 设备2的token + name: "your-device-name2" # 设备2标识 + # 可选:设备白名单,如果设置了白名单,那么白名单的机器无论是什么token都可以连接。 + allowed_devices: + - "24:0A:C4:1D:3B:F0" # MAC地址列表 +manager: + # 是否启用管理后台 + # 目前这个模块还在开发中,建议:不要修改enabled选项 + # 改了大概率报错,报错就会对这个项目失去信心,所以不建议修改 + enabled: false + ip: 0.0.0.0 + port: 8002 +log: + # 设置控制台输出的日志格式,时间、日志级别、标签、消息 + log_format: "{time:YY-MM-DD HH:mm:ss}[{extra[tag]}] - {level} - {message}" + # 设置日志文件输出的格式,时间、日志级别、标签、消息 + log_format_simple: "{time:YYYY-MM-DD HH:mm:ss} - {name} - {level} - {extra[tag]} - {message}" + # 设置日志等级:INFO、DEBUG + log_level: INFO + # 设置日志路径 + log_dir: tmp + # 设置日志文件 + log_file: "server.log" + # 设置数据文件路径 + data_dir: data +iot: + Speaker: + volume: 80 +xiaozhi: + type: hello + version: 1 + transport: websocket + audio_params: + format: opus + sample_rate: 16000 + channels: 1 + frame_duration: 60 +prompt: | + 你是一个叫小智/小志的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。 + 请注意,要像一个人一样说话,请不要回复表情符号、代码、和xml标签。 + 当前时间是:{date_time},现在我正在和你进行语音聊天,我们开始吧。 + 如果用户希望结束对话,请在最后说“拜拜”或“再见”。 + +# 使用完声音文件后删除文件(Delete the sound file when you are done using it) +delete_audio: true + +# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒 +close_connection_no_voice_time: 120 + +# 是否启用私有配置(Enable private configuration),启用后可以每个设备有不同的配置 +# 目前这个模块还在开发中,建议:不要修改use_private_config选项 +# 改了大概率报错,报错就会对这个项目失去信心,所以不建议修改 +use_private_config: false + +CMD_exit: + - "退出" + - "关闭" + +# 具体处理时选择的模块(The module selected for specific processing) +selected_module: + ASR: FunASR + VAD: SileroVAD + # 将根据配置名称对应的type调用实际的LLM适配器 + LLM: AliLLM + # TTS将根据配置名称对应的type调用实际的TTS适配器 + TTS: TTS302AI + Memory: mem0ai + +Memory: + mem0ai: + type: mem0ai + # https://app.mem0.ai/dashboard/api-keys,注册可获得试用credits + api_key: m0-U3TwP324tCYC1GjJA0t1W093Y1pPdwIoLbnx27X8 +ASR: + FunASR: + type: fun_local + model_dir: models/SenseVoiceSmall + output_dir: tmp/ + DoubaoASR: + # 服务地址 https://console.volcengine.com/speech/service/15 + # 服务名称 一句话识别,需要点击开通,初次开通后有2万次额度 + type: doubao + appid: 2632373421 + access_token: 9B8nGVynfy3J9Hd5-jrjKuGRxXK8R32Z + cluster: volcengine_input_common + output_dir: tmp/ + +VAD: + SileroVAD: + threshold: 0.5 + model_dir: models/snakers4_silero-vad + min_silence_duration_ms: 700 # 如果说话停顿比较长,可以把这个值设置大一些 + +LLM: + # 当前支持的type为openai、dify、ollama,可自行适配 + AliLLM: + # 定义LLM API类型 + type: openai + # 可在这里找到你的 api_key https://bailian.console.aliyun.com/?apiKey=1#/api-key + base_url: https://dashscope.aliyuncs.com/compatible-mode/v1 + model_name: qwen-turbo + api_key: sk-26dd86613b974adb948d78a7f2d867e4 + DeepSeekLLM: + # 定义LLM API类型 + type: openai + # 可在这里找到你的api key https://platform.deepseek.com/ + model_name: deepseek-reasoner + url: https://api.deepseek.com + api_key: sk-e038d66049fb4b96a7162ed1b20b3041 + ChatGLMLLM: + # 定义LLM API类型 + type: openai + # glm-4-flash 是免费的,但是还是需要注册填写api_key的 + # 可在这里找到你的api key https://bigmodel.cn/usercenter/proj-mgmt/apikeys + model_name: glm-4-flash + url: https://open.bigmodel.cn/api/paas/v4/ + api_key: 49f04ea584d30a620327803a5845b778.C9Aklsr39vBOqxeR + OllamaLLM: + # 定义LLM API类型 + type: ollama + model_name: qwen2.5 # 使用的模型名称,需要预先使用ollama pull下载 + base_url: http://localhost:11434 # Ollama服务地址 + DifyLLM: + # 定义LLM API类型 + type: dify + # 建议使用本地部署的dify接口,国内部分区域访问dify公有云接口可能会受限 + # 如果使用DifyLLM,配置文件里prompt(提示词)是无效的,需要在dify控制台设置提示词 + base_url: https://api.dify.cn/v1 + api_key: 你的DifyLLM web key + GeminiLLM: + type: gemini + # 谷歌Gemini API,需要先在Google Cloud控制台创建API密钥并获取api_key + # 若在中国境内使用,请遵守《生成式人工智能服务管理暂行办法》 + # token申请地址: https://aistudio.google.com/apikey + # 若部署地无法访问接口,需要开启科学上网 + api_key: 你的gemini web key + model_name: "gemini-1.5-pro" # gemini-1.5-pro 是免费的 + CozeLLM: + # 定义LLM API类型 + type: coze + bot_id: 你的bot_id + user_id: 你的user_id + base_url: "https://api.coze.cn/open_api/v2/chat" # 服务地址 + personal_access_token: 你的coze个人令牌 + LMStudioLLM: + # 定义LLM API类型 + type: openai + model_name: deepseek-r1-distill-llama-8b@q4_k_m # 使用的模型名称,需要预先在社区下载 + url: http://localhost:1234/v1 # LM Studio服务地址 + api_key: lm-studio # LM Studio服务的固定API Key + HomeAssistant: + # 定义LLM API类型 + type: homeassistant + base_url: http://homeassistant.local:8123 + agent_id: conversation.chatgpt + api_key: 你的home assistant api访问令牌 +TTS: + # 当前支持的type为edge、doubao,可自行适配 + EdgeTTS: + # 定义TTS API类型 + type: edge + voice: zh-CN-XiaoxiaoNeural + output_file: tmp/ + DoubaoTTS: + # 定义TTS API类型 + type: doubao + # 火山引擎语音合成服务,需要先在火山引擎控制台创建应用并获取appid和access_token + # 山引擎语音一定要购买花钱,起步价30元,就有100并发了。如果用免费的只有2个并发,会经常报tts错误 + # 购买服务后,购买免费的音色后,可能要等半小时左右,才能使用。 + # 地址:https://console.volcengine.com/speech/service/8 + api_url: https://openspeech.bytedance.com/api/v1/tts + voice: BV213_streaming + output_file: tmp/ + appid: 2632373421 + authorization: "Bearer;" + access_token: 9B8nGVynfy3J9Hd5-jrjKuGRxXK8R32Z + cluster: volcano_tts + TTS302AI: + # 默认使用湾湾小何语音 + # 302AI语音合成服务,需要先在302平台创建账户充值,并获取登录信息 + # 获取api_keyn路径:https://dash.302.ai/apis/list + # 价格,$35/百万字符。火山原版¥450元/百万字符。 + type: doubao + api_url: https://api.302ai.cn/doubao/tts_hd + voice: "zh_female_wanwanxiaohe_moon_bigtts" + output_file: tmp/ + authorization: "Bearer " + access_token: sk-q7dqFE21r57mrCwM7gKBlDdXCPAcCjw9eGD5XdHJhiNzCpZ2 + CosyVoiceSiliconflow: + type: siliconflow + # 硅基流动TTS + # token申请地址 https://cloud.siliconflow.cn/account/ak + model: FunAudioLLM/CosyVoice2-0.5B + voice: FunAudioLLM/CosyVoice2-0.5B:alex + output_file: tmp/ + access_token: sk-iyqvupoqdouokqdqvulgvdsqiwmoxmostuxonntmvpnhxyej + response_format: wav + CozeCnTTS: + type: cozecn + # COZECN TTS + # token申请地址 https://www.coze.cn/open/oauth/pats + voice: 7426720361733046281 + output_file: tmp/ + access_token: 你的coze web key + response_format: wav + FishSpeech: + # 定义TTS API类型 + #启动tts方法: + #python -m tools.api_server + #--listen 0.0.0.0:8080 + #--llama-checkpoint-path "checkpoints/fish-speech-1.5" + #--decoder-checkpoint-path "checkpoints/fish-speech-1.5/firefly-gan-vq-fsq-8x1024-21hz-generator.pth" + #--decoder-config-name firefly_gan_vq + #--compile + type: fishspeech + output_file: tmp/ + response_format: wav + reference_id: null + reference_audio: [ "/tmp/test.wav", ] + reference_text: [ "你弄来这些吟词宴曲来看,还是这些混话来欺负我。", ] + normalize: true + max_new_tokens: 1024 + chunk_length: 200 + top_p: 0.7 + repetition_penalty: 1.2 + temperature: 0.7 + streaming: false + use_memory_cache: "on" + seed: null + channels: 1 + rate: 44100 + api_key: "你的api_key" + api_url: "http://127.0.0.1:8080/v1/tts" + GPT_SOVITS_V2: + # 定义TTS API类型 + #启动tts方法: + #python api_v2.py -a 127.0.0.1 -p 9880 -c GPT_SoVITS/configs/caixukun.yaml + type: gpt_sovits_v2 + url: "http://127.0.0.1:9880/tts" + output_file: tmp/ + text_lang: "auto" + ref_audio_path: "caixukun.wav" + prompt_text: "" + prompt_lang: "zh" + top_k: 5 + top_p: 1 + temperature: 1 + text_split_method: "cut0" + batch_size: 1 + batch_threshold: 0.75 + split_bucket: true + return_fragment: false + speed_factor: 1.0 + streaming_mode: false + seed: -1 + parallel_infer: true + repetition_penalty: 1.35 + aux_ref_audio_paths: [ ] + MinimaxTTS: + # Minimax语音合成服务,需要先在minimax平台创建账户充值,并获取登录信息 + # 平台地址:https://platform.minimaxi.com/ + # 充值地址:https://platform.minimaxi.com/user-center/payment/balance + # group_id地址:https://platform.minimaxi.com/user-center/basic-information + # api_key地址:https://platform.minimaxi.com/user-center/basic-information/interface-key + # 定义TTS API类型 + type: minimax + output_file: tmp/ + group_id: 你的minimax平台groupID + api_key: 你的minimax平台接口密钥 + model: "speech-01-turbo" + # 此处设置将优先于voice_setting中voice_id的设置;如都不设置,默认为 female-shaonv + voice_id: "female-shaonv" + # 以下可不用设置,使用默认设置 + # voice_setting: + # voice_id: "male-qn-qingse" + # speed: 1 + # vol: 1 + # pitch: 0 + # emotion: "happy" + # pronunciation_dict: + # tone: + # - "处理/(chu3)(li3)" + # - "危险/dangerous" + # audio_setting: + # sample_rate: 32000 + # bitrate: 128000 + # format: "mp3" + # channel: 1 + # timber_weights: + # - + # voice_id: male-qn-qingse + # weight: 1 + # - + # voice_id: female-shaonv + # weight: 1 + # language_boost: auto + AliyunTTS: + # 阿里云智能语音交互服务,需要先在阿里云平台开通服务,然后获取验证信息 + # 平台地址:https://nls-portal.console.aliyun.com/ + # appkey地址:https://nls-portal.console.aliyun.com/applist + # token地址:https://nls-portal.console.aliyun.com/overview + # 定义TTS API类型 + type: aliyun + output_file: tmp/ + appkey: 你的阿里云智能语音交互服务项目Appkey + token: 你的阿里云智能语音交互服务AccessToken + voice: xiaoyun + # 以下可不用设置,使用默认设置 + # format: wav + # sample_rate: 16000 + # volume: 50 + # speech_rate: 0 + # pitch_rate: 0 +# 模块测试配置 +module_test: + test_sentences: # 自定义测试语句 + - "你好,请介绍一下你自己" + - "What's the weather like today?" + - "请用100字概括量子计算的基本原理和应用前景" + +# 本地音乐播放配置 +# 本地音乐播放配置 +music: + music_commands: + - "来一首歌" + - "唱一首歌" + - "播放音乐" + - "来点音乐" + - "背景音乐" + - "放首歌" + - "播放歌曲" + - "来点背景音乐" + - "我想听歌" + - "我要听歌" + - "放点音乐" + music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件 + music_ext: # 音乐文件类型,p3格式效率最高 + - ".mp3" + - ".wav" + - ".p3" + refresh_time: 300 # 刷新音乐列表的时间间隔,单位为秒 \ No newline at end of file diff --git a/docker-compose.yml b/main/xiaozhi-server/docker-compose.yml similarity index 100% rename from docker-compose.yml rename to main/xiaozhi-server/docker-compose.yml diff --git a/models/SenseVoiceSmall/chn_jpn_yue_eng_ko_spectok.bpe.model b/main/xiaozhi-server/models/SenseVoiceSmall/chn_jpn_yue_eng_ko_spectok.bpe.model similarity index 100% rename from models/SenseVoiceSmall/chn_jpn_yue_eng_ko_spectok.bpe.model rename to main/xiaozhi-server/models/SenseVoiceSmall/chn_jpn_yue_eng_ko_spectok.bpe.model diff --git a/models/SenseVoiceSmall/config.yaml b/main/xiaozhi-server/models/SenseVoiceSmall/config.yaml similarity index 100% rename from models/SenseVoiceSmall/config.yaml rename to main/xiaozhi-server/models/SenseVoiceSmall/config.yaml diff --git a/models/SenseVoiceSmall/configuration.json b/main/xiaozhi-server/models/SenseVoiceSmall/configuration.json similarity index 100% rename from models/SenseVoiceSmall/configuration.json rename to main/xiaozhi-server/models/SenseVoiceSmall/configuration.json diff --git a/models/SenseVoiceSmall/demo.py b/main/xiaozhi-server/models/SenseVoiceSmall/demo.py similarity index 100% rename from models/SenseVoiceSmall/demo.py rename to main/xiaozhi-server/models/SenseVoiceSmall/demo.py diff --git a/models/SenseVoiceSmall/example/en.mp3 b/main/xiaozhi-server/models/SenseVoiceSmall/example/en.mp3 similarity index 100% rename from models/SenseVoiceSmall/example/en.mp3 rename to main/xiaozhi-server/models/SenseVoiceSmall/example/en.mp3 diff --git a/models/SenseVoiceSmall/example/ja.mp3 b/main/xiaozhi-server/models/SenseVoiceSmall/example/ja.mp3 similarity index 100% rename from models/SenseVoiceSmall/example/ja.mp3 rename to main/xiaozhi-server/models/SenseVoiceSmall/example/ja.mp3 diff --git a/models/SenseVoiceSmall/example/ko.mp3 b/main/xiaozhi-server/models/SenseVoiceSmall/example/ko.mp3 similarity index 100% rename from models/SenseVoiceSmall/example/ko.mp3 rename to main/xiaozhi-server/models/SenseVoiceSmall/example/ko.mp3 diff --git a/models/SenseVoiceSmall/example/yue.mp3 b/main/xiaozhi-server/models/SenseVoiceSmall/example/yue.mp3 similarity index 100% rename from models/SenseVoiceSmall/example/yue.mp3 rename to main/xiaozhi-server/models/SenseVoiceSmall/example/yue.mp3 diff --git a/models/SenseVoiceSmall/example/zh.mp3 b/main/xiaozhi-server/models/SenseVoiceSmall/example/zh.mp3 similarity index 100% rename from models/SenseVoiceSmall/example/zh.mp3 rename to main/xiaozhi-server/models/SenseVoiceSmall/example/zh.mp3 diff --git a/models/snakers4_silero-vad/hubconf.py b/main/xiaozhi-server/models/snakers4_silero-vad/hubconf.py similarity index 100% rename from models/snakers4_silero-vad/hubconf.py rename to main/xiaozhi-server/models/snakers4_silero-vad/hubconf.py diff --git a/models/snakers4_silero-vad/src/silero_vad/__init__.py b/main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/__init__.py similarity index 100% rename from models/snakers4_silero-vad/src/silero_vad/__init__.py rename to main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/__init__.py diff --git a/models/snakers4_silero-vad/src/silero_vad/data/__init__.py b/main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/__init__.py similarity index 100% rename from models/snakers4_silero-vad/src/silero_vad/data/__init__.py rename to main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/__init__.py diff --git a/models/snakers4_silero-vad/src/silero_vad/data/silero_vad.jit b/main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/silero_vad.jit similarity index 100% rename from models/snakers4_silero-vad/src/silero_vad/data/silero_vad.jit rename to main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/silero_vad.jit diff --git a/models/snakers4_silero-vad/src/silero_vad/data/silero_vad.onnx b/main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/silero_vad.onnx similarity index 100% rename from models/snakers4_silero-vad/src/silero_vad/data/silero_vad.onnx rename to main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/silero_vad.onnx diff --git a/models/snakers4_silero-vad/src/silero_vad/data/silero_vad_16k_op15.onnx b/main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/silero_vad_16k_op15.onnx similarity index 100% rename from models/snakers4_silero-vad/src/silero_vad/data/silero_vad_16k_op15.onnx rename to main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/silero_vad_16k_op15.onnx diff --git a/models/snakers4_silero-vad/src/silero_vad/data/silero_vad_half.onnx b/main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/silero_vad_half.onnx similarity index 100% rename from models/snakers4_silero-vad/src/silero_vad/data/silero_vad_half.onnx rename to main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/data/silero_vad_half.onnx diff --git a/models/snakers4_silero-vad/src/silero_vad/model.py b/main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/model.py similarity index 100% rename from models/snakers4_silero-vad/src/silero_vad/model.py rename to main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/model.py diff --git a/models/snakers4_silero-vad/src/silero_vad/utils_vad.py b/main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/utils_vad.py similarity index 100% rename from models/snakers4_silero-vad/src/silero_vad/utils_vad.py rename to main/xiaozhi-server/models/snakers4_silero-vad/src/silero_vad/utils_vad.py diff --git a/music/一念千年_国风版.mp3 b/main/xiaozhi-server/music/一念千年_国风版.mp3 similarity index 100% rename from music/一念千年_国风版.mp3 rename to main/xiaozhi-server/music/一念千年_国风版.mp3 diff --git a/music/中秋月.mp3 b/main/xiaozhi-server/music/中秋月.mp3 similarity index 100% rename from music/中秋月.mp3 rename to main/xiaozhi-server/music/中秋月.mp3 diff --git a/music/廉波老矣,尚能饭否.mp3 b/main/xiaozhi-server/music/廉波老矣,尚能饭否.mp3 similarity index 100% rename from music/廉波老矣,尚能饭否.mp3 rename to main/xiaozhi-server/music/廉波老矣,尚能饭否.mp3 diff --git a/performance_tester.py b/main/xiaozhi-server/performance_tester.py similarity index 100% rename from performance_tester.py rename to main/xiaozhi-server/performance_tester.py diff --git a/poetry.lock b/main/xiaozhi-server/poetry.lock similarity index 100% rename from poetry.lock rename to main/xiaozhi-server/poetry.lock diff --git a/pyproject.toml b/main/xiaozhi-server/pyproject.toml similarity index 100% rename from pyproject.toml rename to main/xiaozhi-server/pyproject.toml diff --git a/web/__init__.py b/web/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/web/api/__init__.py b/web/api/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/web/api/admin/__init__.py b/web/api/admin/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/web/api/admin/admin.py b/web/api/admin/admin.py deleted file mode 100644 index 5c3d3fd54..000000000 --- a/web/api/admin/admin.py +++ /dev/null @@ -1,122 +0,0 @@ -# web/admin/admin.py -from fastapi import APIRouter, Depends, HTTPException, status -from sqlalchemy.orm import Session -from typing import List - -from web.api.auth import models, security -from web.api.db.database import get_db -from web.api.db import models as db_models - -router = APIRouter() - -def get_current_admin_user(db: Session = Depends(get_db), token: str = Depends(security.oauth2_scheme)): - """ - 获取当前登录的管理员用户 - """ - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) - try: - payload = security.decode_access_token(token) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - except Exception: - raise credentials_exception - - user = db.query(db_models.User).filter(db_models.User.username == username).first() - if user is None or user.id != 1: # 默认第一个注册的是管理员 - raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not enough permissions") - - return user - -@router.get("/check", response_model=dict) -def check_admin(db: Session = Depends(get_db), current_user: db_models.User = Depends(get_current_admin_user)): - """ - 检查当前用户是否为管理员 - """ - if current_user.id == 1: # 默认第一个注册的是管理员 - return {"isAdmin": True} - else: - return {"isAdmin": False} - -@router.get("/users", response_model=List[models.UserResponse]) -def list_users(db: Session = Depends(get_db), current_user: db_models.User = Depends(get_current_admin_user)): - """ - 获取所有用户信息 - """ - users = db.query(db_models.User).all() - return users - -@router.post("/users", response_model=models.UserResponse) -def create_user(user: models.UserCreate, db: Session = Depends(get_db), current_user: db_models.User = Depends(get_current_admin_user)): - """ - 创建新用户 - """ - existing_user = db.query(db_models.User).filter(db_models.User.username == user.username).first() - if existing_user: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Username already registered" - ) - hashed_password = security.get_password_hash(user.password) - new_user = db_models.User( - username=user.username, - email=user.email, - full_name=user.full_name, - hashed_password=hashed_password, - disabled=False - ) - db.add(new_user) - db.commit() - db.refresh(new_user) - return new_user - -@router.delete("/users/{user_id}", response_model=models.UserResponse) -def delete_user(user_id: int, db: Session = Depends(get_db), current_user: db_models.User = Depends(get_current_admin_user)): - """ - 删除用户 - """ - user = db.query(db_models.User).filter(db_models.User.id == user_id).first() - if not user: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="User not found" - ) - db.delete(user) - db.commit() - return user - -@router.put("/users/{user_id}/disable", response_model=models.UserResponse) -def disable_user(user_id: int, db: Session = Depends(get_db), current_user: db_models.User = Depends(get_current_admin_user)): - """ - 禁用用户 - """ - user = db.query(db_models.User).filter(db_models.User.id == user_id).first() - if not user: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="User not found" - ) - user.disabled = True - db.commit() - db.refresh(user) - return user - -@router.put("/users/{user_id}/enable", response_model=models.UserResponse) -def enable_user(user_id: int, db: Session = Depends(get_db), current_user: db_models.User = Depends(get_current_admin_user)): - """ - 启用用户 - """ - user = db.query(db_models.User).filter(db_models.User.id == user_id).first() - if not user: - raise HTTPException( - status_code=status.HTTP_404_NOT_FOUND, - detail="User not found" - ) - user.disabled = False - db.commit() - db.refresh(user) - return user diff --git a/web/api/auth/__init__.py b/web/api/auth/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/web/api/auth/auth.py b/web/api/auth/auth.py deleted file mode 100644 index b43d22d2d..000000000 --- a/web/api/auth/auth.py +++ /dev/null @@ -1,66 +0,0 @@ -# web/auth/auth.py -from fastapi import APIRouter, Depends, HTTPException, status -from fastapi.security import OAuth2PasswordRequestForm -from sqlalchemy.orm import Session -from datetime import timedelta - -from web.api.auth import models, security -from web.api.db.database import get_db -from web.api.db import models as db_models - -router = APIRouter() - -@router.post("/register", response_model=models.UserResponse) -def register(user: models.UserCreate, db: Session = Depends(get_db)): - """ - 用户注册接口 - 检查用户名是否存在,若不存在则对密码进行 bcrypt 哈希处理后保存到数据库 - """ - # 检查用户名是否已存在 - existing_user = db.query(db_models.User).filter(db_models.User.username == user.username).first() - if existing_user: - raise HTTPException( - status_code=status.HTTP_400_BAD_REQUEST, - detail="Username already registered" - ) - # 对密码进行 bcrypt 哈希处理 - hashed_password = security.get_password_hash(user.password) - # 创建新用户记录 - new_user = db_models.User( - username=user.username, - email=user.email, - full_name=user.full_name, - hashed_password=hashed_password, - disabled=False - ) - db.add(new_user) - db.commit() - db.refresh(new_user) - return new_user - -@router.post("/login", response_model=models.Token) -def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)): - """ - 用户登录接口 - 通过 OAuth2PasswordRequestForm 获取表单中的 username 和 password, - 查询数据库,验证密码后生成 JWT 令牌返回 - """ - # 从数据库中查询用户 - user = db.query(db_models.User).filter(db_models.User.username == form_data.username).first() - if not user: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect username or password", - headers={"WWW-Authenticate": "Bearer"} - ) - if not security.verify_password(form_data.password, user.hashed_password): - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect username or password", - headers={"WWW-Authenticate": "Bearer"} - ) - access_token_expires = timedelta(minutes=security.ACCESS_TOKEN_EXPIRE_MINUTES) - access_token = security.create_access_token( - data={"sub": user.username}, expires_delta=access_token_expires - ) - return {"access_token": access_token, "token_type": "bearer"} diff --git a/web/api/auth/dependencies.py b/web/api/auth/dependencies.py deleted file mode 100644 index aea32783d..000000000 --- a/web/api/auth/dependencies.py +++ /dev/null @@ -1,59 +0,0 @@ -# web/auth/dependencies.py -from fastapi import Depends, HTTPException, status -from fastapi.security import OAuth2PasswordBearer -from jose import JWTError, jwt -from sqlalchemy.orm import Session - -from web.api.auth import security -from web.api.db.database import get_db -from web.api.db import models as db_models - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login") - -def get_user(db: Session, username: str): - """ - 获取用户(从数据库中查询) - """ - return db.query(db_models.User).filter(db_models.User.username == username).first() - -def authenticate_user(db: Session, username: str, password: str): - """ - 验证用户凭证 - 使用数据库中的用户数据进行验证 - """ - user = get_user(db, username) - if not user: - return None - if not security.verify_password(password, user.hashed_password): - return None - return user - -async def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)): - """ - 从 JWT 令牌中解析用户,并从数据库中获取该用户 - """ - credentials_exception = HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Could not validate credentials", - headers={"WWW-Authenticate": "Bearer"}, - ) - try: - payload = jwt.decode(token, security.SECRET_KEY, algorithms=[security.ALGORITHM]) - username: str = payload.get("sub") - if username is None: - raise credentials_exception - except JWTError: - raise credentials_exception - - user = get_user(db, username) - if user is None: - raise credentials_exception - return user - -async def get_current_active_user(current_user: db_models.User = Depends(get_current_user)): - """ - 检查当前用户是否处于激活状态 - """ - if current_user.disabled: - raise HTTPException(status_code=400, detail="Inactive user") - return current_user diff --git a/web/api/auth/models.py b/web/api/auth/models.py deleted file mode 100644 index 32adb42be..000000000 --- a/web/api/auth/models.py +++ /dev/null @@ -1,37 +0,0 @@ -# web/auth/models.py -from pydantic import BaseModel -from typing import Optional - -class Token(BaseModel): - access_token: str - token_type: str - -class TokenData(BaseModel): - username: Optional[str] = None - -class User(BaseModel): - username: str - email: Optional[str] = None - full_name: Optional[str] = None - disabled: Optional[bool] = None - -class UserInDB(User): - hashed_password: str - -# 用户注册时请求数据模型 -class UserCreate(BaseModel): - username: str - email: Optional[str] = None - full_name: Optional[str] = None - password: str - -# 用户响应数据模型(不返回密码) -class UserResponse(BaseModel): - id: int - username: str - email: Optional[str] = None - full_name: Optional[str] = None - disabled: Optional[bool] = None - - class Config: - orm_mode = True diff --git a/web/api/auth/security.py b/web/api/auth/security.py deleted file mode 100644 index ad307e6e1..000000000 --- a/web/api/auth/security.py +++ /dev/null @@ -1,51 +0,0 @@ -# web/auth/security.py -import bcrypt -from datetime import datetime, timedelta -from jose import JWTError, jwt -from fastapi.security import OAuth2PasswordBearer - -oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login") - -# JWT 配置 -SECRET_KEY = "9f24447481c6012c3ee0217fa252dd1692af0f67c5eab78b5c19eab87f196215" # 建议放到环境变量中 -ALGORITHM = "HS256" -ACCESS_TOKEN_EXPIRE_MINUTES = 30 - -def get_password_hash(password: str) -> str: - """ - 生成密码哈希 - 获取密码hash - """ - # 生成盐并计算密码哈希 - hashed = bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()) - return hashed.decode('utf-8') - -def verify_password(plain_password: str, hashed_password: str) -> bool: - """ - 校验密码 - 校验密码是否匹配 - """ - return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8')) - -def create_access_token(data: dict, expires_delta: timedelta = None) -> str: - """ - 生成 JWT 令牌 - """ - to_encode = data.copy() - if expires_delta: - expire = datetime.utcnow() + expires_delta - else: - expire = datetime.utcnow() + timedelta(minutes=15) - to_encode.update({"exp": expire}) - encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt - -def decode_access_token(token: str) -> dict: - """ - 解码 JWT 令牌并返回 payload 数据 - """ - try: - payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) - return payload # payload 是一个字典,包含 "sub" 等数据 - except JWTError: - return None # 令牌无效时返回 None diff --git a/web/api/db/__init__.py b/web/api/db/__init__.py deleted file mode 100644 index e69de29bb..000000000 diff --git a/web/api/db/database.py b/web/api/db/database.py deleted file mode 100644 index d7b33cfa7..000000000 --- a/web/api/db/database.py +++ /dev/null @@ -1,31 +0,0 @@ -# web/db/database.py -import os -from sqlalchemy import create_engine -from sqlalchemy.ext.declarative import declarative_base -from sqlalchemy.orm import sessionmaker - -# 获取数据库连接 URL,可通过环境变量设置,例如: -# SQLite: sqlite:///./data/sql_app.db -# PostgreSQL: postgresql+asyncpg://user:password@localhost/dbname -# MySQL: mysql+pymysql://user:password@localhost/dbname -DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./data/sql_app.db") - -if DATABASE_URL.startswith("sqlite"): - engine = create_engine( - DATABASE_URL, connect_args={"check_same_thread": False} - ) -else: - engine = create_engine(DATABASE_URL) - -SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) -Base = declarative_base() - -def get_db(): - """ - 获取数据库会话 - """ - db = SessionLocal() - try: - yield db - finally: - db.close() diff --git a/web/api/db/models.py b/web/api/db/models.py deleted file mode 100644 index c3989cc3a..000000000 --- a/web/api/db/models.py +++ /dev/null @@ -1,13 +0,0 @@ -# web/db/models.py -from sqlalchemy import Column, Integer, String, Boolean -from web.api.db.database import Base - -class User(Base): - __tablename__ = "users" - - id = Column(Integer, primary_key=True, index=True) - username = Column(String(50), unique=True, index=True, nullable=False) - email = Column(String(100), unique=True, index=True, nullable=True) - full_name = Column(String(100), nullable=True) - hashed_password = Column(String, nullable=False) - disabled = Column(Boolean, default=False) diff --git a/web/app.py b/web/app.py deleted file mode 100644 index 7e924f655..000000000 --- a/web/app.py +++ /dev/null @@ -1,60 +0,0 @@ -import os -import sys -from contextlib import asynccontextmanager # 新增导入 - -current_dir = os.path.dirname(os.path.abspath(__file__)) -root_dir = os.path.dirname(current_dir) -sys.path.append(root_dir) - -from fastapi import FastAPI, Depends -from fastapi.middleware.cors import CORSMiddleware -from web.api.admin import admin -from web.api.auth import auth as auth_router -from web.api.auth.dependencies import get_current_active_user - -# 新增 lifespan 处理器 -@asynccontextmanager -async def lifespan(app: FastAPI): - # 启动时逻辑 - from web.api.db import models, database - models.Base.metadata.create_all(bind=database.engine) - print("数据库表检查完成,如果不存在则已创建!") - yield # 这里之后是关闭时逻辑(如果需要可以添加) - -app = FastAPI( - lifespan=lifespan, # 添加 lifespan 参数 - title="App", - description="", - summary="你好小智", - version="0.0.1", - contact={ - "name": "xiaozhi-esp32-server", - "url": "https://github.com/xinnan-tech/xiaozhi-esp32-server", - }, - license_info={ - "name": "MIT", - "url": "https://github.com/xinnan-tech/xiaozhi-esp32-server/blob/main/LICENSE", - }, -) - -# 允许所有域名跨域 -app.add_middleware( - CORSMiddleware, - allow_origins=["*"], # 允许所有域名 - allow_credentials=True, # 允许携带 Cookies - allow_methods=["*"], # 允许所有 HTTP 方法 - allow_headers=["*"], # 允许所有请求头 -) - -# 注册认证路由 -app.include_router(auth_router.router, prefix="/web/v1/user", tags=["user"]) -app.include_router(admin.router, prefix="/web/v1/admin", tags=["admin"]) - -# 示例:受保护接口,需要 Bearer Token 验证 -@app.get("/users/me") -async def read_users_me(current_user = Depends(get_current_active_user)): - return current_user - -# 挂载 React 静态文件 -# app.mount("/", StaticFiles(directory="dist", html=True), name="dist") -