From ff51ea78af0e025773d911708084df77ecd9497a Mon Sep 17 00:00:00 2001 From: "zhuangpeng.li" <908349383@qq.com> Date: Thu, 17 Apr 2025 09:44:10 +0800 Subject: [PATCH 01/18] =?UTF-8?q?feat(ruoyi=E7=89=88=E6=9C=AC=E5=90=8C?= =?UTF-8?q?=E6=AD=A5):=20ruoyi-3.8.9=E7=89=88=E6=9C=AC=E5=90=8C=E6=AD=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- springboot/fastbee-admin/pom.xml | 2 +- .../system/SysConfigController.java | 6 +- .../controller/system/SysDeptController.java | 6 +- .../system/SysDictTypeController.java | 6 +- .../controller/system/SysLoginController.java | 47 +- .../controller/system/SysMenuController.java | 8 +- .../controller/system/SysPostController.java | 10 +- .../system/SysProfileController.java | 4 +- .../controller/system/SysRoleController.java | 12 +- .../controller/system/SysUserController.java | 76 +-- .../com/fastbee/common/annotation/Excel.java | 31 +- .../com/fastbee/common/annotation/Log.java | 16 +- .../fastbee/common/constant/Constants.java | 40 +- .../common/constant/UserConstants.java | 10 +- .../com/fastbee/common/core/text/Convert.java | 47 +- .../common/enums/DesensitizedType.java | 60 ++ .../common/utils/DesensitizedUtil.java | 49 ++ .../com/fastbee/common/utils/DictUtils.java | 94 ++- .../fastbee/common/utils/SecurityUtils.java | 71 ++- .../com/fastbee/common/utils/StringUtils.java | 564 +++++++++-------- .../com/fastbee/common/utils/ip/IpUtils.java | 141 ++++- .../common/utils/poi/ExcelHandlerAdapter.java | 11 +- .../fastbee/common/utils/poi/ExcelUtil.java | 578 +++++++++++------- .../com/fastbee/common/utils/sql/SqlUtil.java | 13 +- .../fastbee/framework/aspectj/LogAspect.java | 90 ++- .../fastbee/framework/config/DruidConfig.java | 33 +- .../config/FastJson2JsonRedisSerializer.java | 15 +- .../framework/config/FilterConfig.java | 13 +- .../framework/config/SecurityConfig.java | 130 ++-- .../framework/config/ServerConfig.java | 9 +- .../web/service/SysRegisterService.java | 10 +- .../fastbee-iot-service/pom.xml | 7 +- .../iot/oauth/AuthorizationServerConfig.java | 119 ---- .../iot/oauth/ResourceServerConfig.java | 50 -- .../iot/oauth/SpeakerApprovalHandler.java | 83 --- .../oauth/api/ConfirmAccessController.java | 49 -- .../iot/oauth/api/LoginController.java | 55 -- .../iot/oauth/api/SpeakerController.java | 33 - .../iot/service/impl/ToolServiceImpl.java | 10 +- .../com/fastbee/system/domain/SysOperLog.java | 21 +- .../system/mapper/SysOperLogMapper.java | 10 +- .../fastbee/system/mapper/SysRoleMapper.java | 29 +- .../system/service/ISysConfigService.java | 23 +- .../system/service/ISysDeptService.java | 35 +- .../system/service/ISysDictTypeService.java | 25 +- .../system/service/ISysMenuService.java | 36 +- .../system/service/ISysOperLogService.java | 13 +- .../system/service/ISysPostService.java | 31 +- .../system/service/ISysRoleService.java | 55 +- .../system/service/ISysUserService.java | 6 +- .../service/impl/SysConfigServiceImpl.java | 33 +- .../service/impl/SysDeptServiceImpl.java | 51 +- .../service/impl/SysDictTypeServiceImpl.java | 39 +- .../service/impl/SysMenuServiceImpl.java | 54 +- .../service/impl/SysOperLogServiceImpl.java | 17 +- .../service/impl/SysPostServiceImpl.java | 35 +- .../service/impl/SysRoleServiceImpl.java | 78 +-- .../service/impl/SysUserServiceImpl.java | 29 +- .../mapper/system/SysOperLogMapper.xml | 30 +- .../resources/mapper/system/SysRoleMapper.xml | 38 +- .../resources/mapper/system/SysUserMapper.xml | 43 +- springboot/pom.xml | 54 +- 62 files changed, 1814 insertions(+), 1579 deletions(-) create mode 100644 springboot/fastbee-common/src/main/java/com/fastbee/common/enums/DesensitizedType.java create mode 100644 springboot/fastbee-common/src/main/java/com/fastbee/common/utils/DesensitizedUtil.java delete mode 100644 springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/AuthorizationServerConfig.java delete mode 100644 springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/ResourceServerConfig.java delete mode 100644 springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/SpeakerApprovalHandler.java delete mode 100644 springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/ConfirmAccessController.java delete mode 100644 springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/LoginController.java delete mode 100644 springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/SpeakerController.java diff --git a/springboot/fastbee-admin/pom.xml b/springboot/fastbee-admin/pom.xml index 66c386a4..770fa7c8 100644 --- a/springboot/fastbee-admin/pom.xml +++ b/springboot/fastbee-admin/pom.xml @@ -84,7 +84,7 @@ org.springframework.boot spring-boot-maven-plugin - 2.1.1.RELEASE + 2.5.15 true diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysConfigController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysConfigController.java index c7e38561..d6584b31 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysConfigController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysConfigController.java @@ -28,7 +28,7 @@ import com.fastbee.system.service.ISysConfigService; /** * 参数配置 信息操作处理 - * + * * @author ruoyi */ @Api(tags = "参数设置") @@ -93,7 +93,7 @@ public class SysConfigController extends BaseController @PostMapping public AjaxResult add(@Validated @RequestBody SysConfig config) { - if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) + if (configService.checkConfigKeyUnique(config)) { return error("新增参数'" + config.getConfigName() + "'失败,参数键名已存在"); } @@ -110,7 +110,7 @@ public class SysConfigController extends BaseController @PutMapping public AjaxResult edit(@Validated @RequestBody SysConfig config) { - if (UserConstants.NOT_UNIQUE.equals(configService.checkConfigKeyUnique(config))) + if (configService.checkConfigKeyUnique(config)) { return error("修改参数'" + config.getConfigName() + "'失败,参数键名已存在"); } diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDeptController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDeptController.java index 25775982..4c610555 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDeptController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDeptController.java @@ -27,7 +27,7 @@ import com.fastbee.system.service.ISysDeptService; /** * 部门信息 - * + * * @author ruoyi */ @Api(tags = "部门管理") @@ -84,7 +84,7 @@ public class SysDeptController extends BaseController @PostMapping public AjaxResult add(@Validated @RequestBody SysDept dept) { - if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) + if (deptService.checkDeptNameUnique(dept)) { return error("新增部门'" + dept.getDeptName() + "'失败,部门名称已存在"); } @@ -103,7 +103,7 @@ public class SysDeptController extends BaseController { Long deptId = dept.getDeptId(); deptService.checkDeptDataScope(deptId); - if (UserConstants.NOT_UNIQUE.equals(deptService.checkDeptNameUnique(dept))) + if (deptService.checkDeptNameUnique(dept)) { return error("修改部门'" + dept.getDeptName() + "'失败,部门名称已存在"); } diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDictTypeController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDictTypeController.java index 3ca77c31..5bc0309c 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDictTypeController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysDictTypeController.java @@ -28,7 +28,7 @@ import com.fastbee.system.service.ISysDictTypeService; /** * 数据字典信息 - * + * * @author ruoyi */ @Api(tags = "字典管理") @@ -80,7 +80,7 @@ public class SysDictTypeController extends BaseController @PostMapping public AjaxResult add(@Validated @RequestBody SysDictType dict) { - if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) + if (dictTypeService.checkDictTypeUnique(dict)) { return error("新增字典'" + dict.getDictName() + "'失败,字典类型已存在"); } @@ -97,7 +97,7 @@ public class SysDictTypeController extends BaseController @PutMapping public AjaxResult edit(@Validated @RequestBody SysDictType dict) { - if (UserConstants.NOT_UNIQUE.equals(dictTypeService.checkDictTypeUnique(dict))) + if (dictTypeService.checkDictTypeUnique(dict)) { return error("修改字典'" + dict.getDictName() + "'失败,字典类型已存在"); } diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysLoginController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysLoginController.java index a11308b7..75a9a8c9 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysLoginController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysLoginController.java @@ -1,32 +1,30 @@ package com.fastbee.web.controller.system; -import java.util.List; -import java.util.Set; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -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 com.fastbee.common.constant.Constants; import com.fastbee.common.core.domain.AjaxResult; import com.fastbee.common.core.domain.entity.SysMenu; import com.fastbee.common.core.domain.entity.SysUser; import com.fastbee.common.core.domain.model.LoginBody; +import com.fastbee.common.core.domain.model.LoginUser; import com.fastbee.common.utils.SecurityUtils; import com.fastbee.framework.web.service.SysLoginService; import com.fastbee.framework.web.service.SysPermissionService; +import com.fastbee.framework.web.service.TokenService; import com.fastbee.system.service.ISysMenuService; +import org.springframework.beans.factory.annotation.Autowired; +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 java.util.List; +import java.util.Set; /** * 登录验证 - * + * * @author ruoyi */ -@Api(tags = "登录验证") @RestController public class SysLoginController { @@ -38,16 +36,16 @@ public class SysLoginController @Autowired private SysPermissionService permissionService; - @Value("${server.broker.enabled}") - private Boolean enabled; + + @Autowired + private TokenService tokenService; /** * 登录方法 - * + * * @param loginBody 登录信息 * @return 结果 */ - @ApiOperation("用户登录") @PostMapping("/login") public AjaxResult login(@RequestBody LoginBody loginBody) { @@ -61,32 +59,35 @@ public class SysLoginController /** * 获取用户信息 - * + * * @return 用户信息 */ - @ApiOperation("获取用户信息") @GetMapping("getInfo") public AjaxResult getInfo() { - SysUser user = SecurityUtils.getLoginUser().getUser(); + LoginUser loginUser = SecurityUtils.getLoginUser(); + SysUser user = loginUser.getUser(); // 角色集合 Set roles = permissionService.getRolePermission(user); // 权限集合 Set permissions = permissionService.getMenuPermission(user); + if (!loginUser.getPermissions().equals(permissions)) + { + loginUser.setPermissions(permissions); + tokenService.refreshToken(loginUser); + } AjaxResult ajax = AjaxResult.success(); ajax.put("user", user); ajax.put("roles", roles); ajax.put("permissions", permissions); - ajax.put("mqtt",enabled); return ajax; } /** * 获取路由信息 - * + * * @return 路由信息 */ - @ApiOperation("获取路由信息") @GetMapping("getRouters") public AjaxResult getRouters() { diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysMenuController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysMenuController.java index f63493e0..6ae981a6 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysMenuController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysMenuController.java @@ -26,7 +26,7 @@ import com.fastbee.system.service.ISysMenuService; /** * 菜单信息 - * + * * @author ruoyi */ @Api(tags = "菜单管理") @@ -94,7 +94,7 @@ public class SysMenuController extends BaseController @PostMapping public AjaxResult add(@Validated @RequestBody SysMenu menu) { - if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) + if (menuService.checkMenuNameUnique(menu)) { return error("新增菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } @@ -115,7 +115,7 @@ public class SysMenuController extends BaseController @PutMapping public AjaxResult edit(@Validated @RequestBody SysMenu menu) { - if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) + if (menuService.checkMenuNameUnique(menu)) { return error("修改菜单'" + menu.getMenuName() + "'失败,菜单名称已存在"); } @@ -150,4 +150,4 @@ public class SysMenuController extends BaseController } return toAjax(menuService.deleteMenuById(menuId)); } -} \ No newline at end of file +} diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysPostController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysPostController.java index 29b3f2c1..068c3c94 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysPostController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysPostController.java @@ -28,7 +28,7 @@ import com.fastbee.system.service.ISysPostService; /** * 岗位信息操作处理 - * + * * @author ruoyi */ @Api(tags = "岗位管理") @@ -83,11 +83,11 @@ public class SysPostController extends BaseController @PostMapping public AjaxResult add(@Validated @RequestBody SysPost post) { - if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) + if (postService.checkPostNameUnique(post)) { return error("新增岗位'" + post.getPostName() + "'失败,岗位名称已存在"); } - else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) + else if (postService.checkPostCodeUnique(post)) { return error("新增岗位'" + post.getPostName() + "'失败,岗位编码已存在"); } @@ -104,11 +104,11 @@ public class SysPostController extends BaseController @PutMapping public AjaxResult edit(@Validated @RequestBody SysPost post) { - if (UserConstants.NOT_UNIQUE.equals(postService.checkPostNameUnique(post))) + if (postService.checkPostNameUnique(post)) { return error("修改岗位'" + post.getPostName() + "'失败,岗位名称已存在"); } - else if (UserConstants.NOT_UNIQUE.equals(postService.checkPostCodeUnique(post))) + else if (postService.checkPostCodeUnique(post)) { return error("修改岗位'" + post.getPostName() + "'失败,岗位编码已存在"); } diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysProfileController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysProfileController.java index 8b3a257f..700e3c29 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysProfileController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysProfileController.java @@ -81,12 +81,12 @@ public class SysProfileController extends BaseController SysUser sysUser = loginUser.getUser(); user.setUserName(sysUser.getUserName()); if (StringUtils.isNotEmpty(user.getPhonenumber()) - && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) + && userService.checkPhoneUnique(user)) { return error("修改用户'" + user.getUserName() + "'失败,手机号码已存在"); } if (StringUtils.isNotEmpty(user.getEmail()) - && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) + && userService.checkEmailUnique(user)) { return error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在"); } diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysRoleController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysRoleController.java index 0ddef4bf..7edc24ce 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysRoleController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysRoleController.java @@ -37,7 +37,7 @@ import com.fastbee.system.service.ISysUserService; /** * 角色信息 - * + * * @author ruoyi */ @Api(tags = "角色管理") @@ -102,11 +102,11 @@ public class SysRoleController extends BaseController @PostMapping public AjaxResult add(@Validated @RequestBody SysRole role) { - if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) + if (roleService.checkRoleNameUnique(role)) { return error("新增角色'" + role.getRoleName() + "'失败,角色名称已存在"); } - else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) + else if (roleService.checkRoleKeyUnique(role)) { return error("新增角色'" + role.getRoleName() + "'失败,角色权限已存在"); } @@ -126,16 +126,16 @@ public class SysRoleController extends BaseController { roleService.checkRoleAllowed(role); roleService.checkRoleDataScope(role.getRoleId()); - if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleNameUnique(role))) + if (roleService.checkRoleNameUnique(role)) { return error("修改角色'" + role.getRoleName() + "'失败,角色名称已存在"); } - else if (UserConstants.NOT_UNIQUE.equals(roleService.checkRoleKeyUnique(role))) + else if (roleService.checkRoleKeyUnique(role)) { return error("修改角色'" + role.getRoleName() + "'失败,角色权限已存在"); } role.setUpdateBy(getUsername()); - + if (roleService.updateRole(role) > 0) { // 更新缓存用户权限 diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysUserController.java b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysUserController.java index 09c534c3..8f5a27c2 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysUserController.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/web/controller/system/SysUserController.java @@ -1,26 +1,6 @@ package com.fastbee.web.controller.system; -import java.util.List; -import java.util.stream.Collectors; -import javax.servlet.http.HttpServletResponse; - -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import org.apache.commons.lang3.ArrayUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; import com.fastbee.common.annotation.Log; -import com.fastbee.common.constant.UserConstants; import com.fastbee.common.core.controller.BaseController; import com.fastbee.common.core.domain.AjaxResult; import com.fastbee.common.core.domain.entity.SysDept; @@ -35,13 +15,22 @@ import com.fastbee.system.service.ISysDeptService; import com.fastbee.system.service.ISysPostService; import com.fastbee.system.service.ISysRoleService; import com.fastbee.system.service.ISysUserService; +import org.apache.commons.lang3.ArrayUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletResponse; +import java.util.List; +import java.util.stream.Collectors; /** * 用户信息 - * + * * @author ruoyi */ -@Api(tags = "用户管理") @RestController @RequestMapping("/system/user") public class SysUserController extends BaseController @@ -61,7 +50,6 @@ public class SysUserController extends BaseController /** * 获取用户列表 */ - @ApiOperation("获取用户分页列表") @PreAuthorize("@ss.hasPermi('system:user:list')") @GetMapping("/list") public TableDataInfo list(SysUser user) @@ -71,7 +59,6 @@ public class SysUserController extends BaseController return getDataTable(list); } - @ApiOperation("导出用户列表") @Log(title = "用户管理", businessType = BusinessType.EXPORT) @PreAuthorize("@ss.hasPermi('system:user:export')") @PostMapping("/export") @@ -82,7 +69,6 @@ public class SysUserController extends BaseController util.exportExcel(response, list, "用户数据"); } - @ApiOperation("批量导入用户") @Log(title = "用户管理", businessType = BusinessType.IMPORT) @PreAuthorize("@ss.hasPermi('system:user:import')") @PostMapping("/importData") @@ -95,8 +81,6 @@ public class SysUserController extends BaseController return success(message); } - - @ApiOperation("下载用户导入模板") @PostMapping("/importTemplate") public void importTemplate(HttpServletResponse response) { @@ -107,46 +91,44 @@ public class SysUserController extends BaseController /** * 根据用户编号获取详细信息 */ - @ApiOperation("根据用户编号获取详细信息") @PreAuthorize("@ss.hasPermi('system:user:query')") @GetMapping(value = { "/", "/{userId}" }) public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) { - userService.checkUserDataScope(userId); AjaxResult ajax = AjaxResult.success(); - List roles = roleService.selectRoleAll(); - ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList())); - ajax.put("posts", postService.selectPostAll()); if (StringUtils.isNotNull(userId)) { + userService.checkUserDataScope(userId); SysUser sysUser = userService.selectUserById(userId); ajax.put(AjaxResult.DATA_TAG, sysUser); ajax.put("postIds", postService.selectPostListByUserId(userId)); ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList())); } + List roles = roleService.selectRoleAll(); + ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList())); + ajax.put("posts", postService.selectPostAll()); return ajax; } /** * 新增用户 */ - @ApiOperation("新增用户") @PreAuthorize("@ss.hasPermi('system:user:add')") @Log(title = "用户管理", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add(@Validated @RequestBody SysUser user) { - if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) + deptService.checkDeptDataScope(user.getDeptId()); + roleService.checkRoleDataScope(user.getRoleIds()); + if (!userService.checkUserNameUnique(user)) { return error("新增用户'" + user.getUserName() + "'失败,登录账号已存在"); } - else if (StringUtils.isNotEmpty(user.getPhonenumber()) - && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) + else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) { return error("新增用户'" + user.getUserName() + "'失败,手机号码已存在"); } - else if (StringUtils.isNotEmpty(user.getEmail()) - && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) + else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) { return error("新增用户'" + user.getUserName() + "'失败,邮箱账号已存在"); } @@ -158,7 +140,6 @@ public class SysUserController extends BaseController /** * 修改用户 */ - @ApiOperation("修改用户") @PreAuthorize("@ss.hasPermi('system:user:edit')") @Log(title = "用户管理", businessType = BusinessType.UPDATE) @PutMapping @@ -166,17 +147,17 @@ public class SysUserController extends BaseController { userService.checkUserAllowed(user); userService.checkUserDataScope(user.getUserId()); - if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) + deptService.checkDeptDataScope(user.getDeptId()); + roleService.checkRoleDataScope(user.getRoleIds()); + if (!userService.checkUserNameUnique(user)) { return error("修改用户'" + user.getUserName() + "'失败,登录账号已存在"); } - else if (StringUtils.isNotEmpty(user.getPhonenumber()) - && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) + else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) { return error("修改用户'" + user.getUserName() + "'失败,手机号码已存在"); } - else if (StringUtils.isNotEmpty(user.getEmail()) - && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) + else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) { return error("修改用户'" + user.getUserName() + "'失败,邮箱账号已存在"); } @@ -187,7 +168,6 @@ public class SysUserController extends BaseController /** * 删除用户 */ - @ApiOperation("删除用户") @PreAuthorize("@ss.hasPermi('system:user:remove')") @Log(title = "用户管理", businessType = BusinessType.DELETE) @DeleteMapping("/{userIds}") @@ -203,7 +183,6 @@ public class SysUserController extends BaseController /** * 重置密码 */ - @ApiOperation("重置用户密码") @PreAuthorize("@ss.hasPermi('system:user:resetPwd')") @Log(title = "用户管理", businessType = BusinessType.UPDATE) @PutMapping("/resetPwd") @@ -219,7 +198,6 @@ public class SysUserController extends BaseController /** * 状态修改 */ - @ApiOperation("修改用户状态") @PreAuthorize("@ss.hasPermi('system:user:edit')") @Log(title = "用户管理", businessType = BusinessType.UPDATE) @PutMapping("/changeStatus") @@ -234,7 +212,6 @@ public class SysUserController extends BaseController /** * 根据用户编号获取授权角色 */ - @ApiOperation("根据用户编号获取授权角色") @PreAuthorize("@ss.hasPermi('system:user:query')") @GetMapping("/authRole/{userId}") public AjaxResult authRole(@PathVariable("userId") Long userId) @@ -250,13 +227,13 @@ public class SysUserController extends BaseController /** * 用户授权角色 */ - @ApiOperation("为用户授权角色") @PreAuthorize("@ss.hasPermi('system:user:edit')") @Log(title = "用户管理", businessType = BusinessType.GRANT) @PutMapping("/authRole") public AjaxResult insertAuthRole(Long userId, Long[] roleIds) { userService.checkUserDataScope(userId); + roleService.checkRoleDataScope(roleIds); userService.insertUserAuth(userId, roleIds); return success(); } @@ -264,7 +241,6 @@ public class SysUserController extends BaseController /** * 获取部门树列表 */ - @ApiOperation("获取部门树列表") @PreAuthorize("@ss.hasPermi('system:user:list')") @GetMapping("/deptTree") public AjaxResult deptTree(SysDept dept) diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/annotation/Excel.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/annotation/Excel.java index 157c8825..7b4c044b 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/annotation/Excel.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/annotation/Excel.java @@ -1,17 +1,18 @@ package com.fastbee.common.annotation; +import com.fastbee.common.utils.poi.ExcelHandlerAdapter; +import org.apache.poi.ss.usermodel.HorizontalAlignment; +import org.apache.poi.ss.usermodel.IndexedColors; + import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.math.BigDecimal; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import com.fastbee.common.utils.poi.ExcelHandlerAdapter; /** * 自定义导出Excel数据注解 - * + * * @author ruoyi */ @Retention(RetentionPolicy.RUNTIME) @@ -59,12 +60,12 @@ public @interface Excel public int roundingMode() default BigDecimal.ROUND_HALF_EVEN; /** - * 导出时在excel中每个列的高度 单位为字符 + * 导出时在excel中每个列的高度 */ public double height() default 14; /** - * 导出时在excel中每个列的宽 单位为字符 + * 导出时在excel中每个列的宽度 */ public double width() default 16; @@ -83,11 +84,21 @@ public @interface Excel */ public String prompt() default ""; + /** + * 是否允许内容换行 + */ + public boolean wrapText() default false; + /** * 设置只能选择不能输入的列内容. */ public String[] combo() default {}; + /** + * 是否从字典读数据到combo,默认不读取,如读取需要设置dictType注解. + */ + public boolean comboReadDict() default false; + /** * 是否需要纵向合并单元格,应对需求:含有list集合单元格) */ @@ -114,7 +125,7 @@ public @interface Excel public ColumnType cellType() default ColumnType.STRING; /** - * 导出列头背景色 + * 导出列头背景颜色 */ public IndexedColors headerBackgroundColor() default IndexedColors.GREY_50_PERCENT; @@ -124,7 +135,7 @@ public @interface Excel public IndexedColors headerColor() default IndexedColors.WHITE; /** - * 导出单元格背景色 + * 导出单元格背景颜色 */ public IndexedColors backgroundColor() default IndexedColors.WHITE; @@ -171,7 +182,7 @@ public @interface Excel public enum ColumnType { - NUMERIC(0), STRING(1), IMAGE(2); + NUMERIC(0), STRING(1), IMAGE(2), TEXT(3); private final int value; ColumnType(int value) @@ -184,4 +195,4 @@ public @interface Excel return this.value; } } -} \ No newline at end of file +} diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/annotation/Log.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/annotation/Log.java index 2526dd45..a86216cf 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/annotation/Log.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/annotation/Log.java @@ -1,16 +1,13 @@ package com.fastbee.common.annotation; -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; import com.fastbee.common.enums.BusinessType; import com.fastbee.common.enums.OperatorType; +import java.lang.annotation.*; + /** * 自定义操作日志记录注解 - * + * * @author ruoyi * */ @@ -20,7 +17,7 @@ import com.fastbee.common.enums.OperatorType; public @interface Log { /** - * 模块 + * 模块 */ public String title() default ""; @@ -43,4 +40,9 @@ public @interface Log * 是否保存响应的参数 */ public boolean isSaveResponseData() default true; + + /** + * 排除指定的请求参数 + */ + public String[] excludeParamNames() default {}; } diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/constant/Constants.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/constant/Constants.java index c3b5ed04..6c226573 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/constant/Constants.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/constant/Constants.java @@ -2,9 +2,11 @@ package com.fastbee.common.constant; import io.jsonwebtoken.Claims; +import java.util.Locale; + /** * 通用常量信息 - * + * * @author ruoyi */ public class Constants @@ -19,6 +21,11 @@ public class Constants */ public static final String GBK = "GBK"; + /** + * 系统语言 + */ + public static final Locale DEFAULT_LOCALE = Locale.SIMPLIFIED_CHINESE; + /** * www主域 */ @@ -63,7 +70,27 @@ public class Constants * 登录失败 */ public static final String LOGIN_FAIL = "Error"; - + + /** + * 所有权限标识 + */ + public static final String ALL_PERMISSION = "*:*:*"; + + /** + * 管理员角色权限标识 + */ + public static final String SUPER_ADMIN = "admin"; + + /** + * 角色权限分隔符 + */ + public static final String ROLE_DELIMETER = ","; + + /** + * 权限标识分隔符 + */ + public static final String PERMISSION_DELIMETER = ","; + /** * 验证码有效期(分钟) */ @@ -129,14 +156,19 @@ public class Constants */ public static final String LOOKUP_LDAPS = "ldaps:"; + /** + * 自动识别json对象白名单配置(仅允许解析的包名,范围越小越安全) + */ + public static final String[] JSON_WHITELIST_STR = { "org.springframework", "com.ruoyi" }; + /** * 定时任务白名单配置(仅允许访问的包名,如其他需要可以自行添加) */ - public static final String[] JOB_WHITELIST_STR = { "com.fastbee" }; + public static final String[] JOB_WHITELIST_STR = { "com.ruoyi.quartz.task" }; /** * 定时任务违规的字符 */ public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml", - "org.springframework", "org.apache", "com.fastbee.common.utils.file", "com.fastbee.common.config" }; + "org.springframework", "org.apache", "com.ruoyi.common.utils.file", "com.ruoyi.common.config", "com.ruoyi.generator" }; } diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/constant/UserConstants.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/constant/UserConstants.java index ad6f4a3d..ee1193e4 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/constant/UserConstants.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/constant/UserConstants.java @@ -2,7 +2,7 @@ package com.fastbee.common.constant; /** * 用户常量信息 - * + * * @author ruoyi */ public class UserConstants @@ -53,16 +53,16 @@ public class UserConstants /** Layout组件标识 */ public final static String LAYOUT = "Layout"; - + /** ParentView组件标识 */ public final static String PARENT_VIEW = "ParentView"; /** InnerLink组件标识 */ public final static String INNER_LINK = "InnerLink"; - /** 校验返回结果码 */ - public final static String UNIQUE = "0"; - public final static String NOT_UNIQUE = "1"; + /** 校验是否唯一的返回标识 */ + public final static boolean UNIQUE = true; + public final static boolean NOT_UNIQUE = false; /** * 用户名长度限制 diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/core/text/Convert.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/core/text/Convert.java index 528b19b4..0da5f274 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/core/text/Convert.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/core/text/Convert.java @@ -1,13 +1,14 @@ package com.fastbee.common.core.text; +import com.fastbee.common.utils.StringUtils; + import java.math.BigDecimal; import java.math.BigInteger; +import java.math.RoundingMode; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.text.NumberFormat; import java.util.Set; -import com.fastbee.common.utils.StringUtils; -import org.apache.commons.lang3.ArrayUtils; /** * 类型转换器 @@ -364,6 +365,10 @@ public class Convert */ public static String[] toStrArray(String str) { + if (StringUtils.isEmpty(str)) + { + return new String[] {}; + } return toStrArray(",", str); } @@ -536,7 +541,7 @@ public class Convert /** * 转换为boolean
- * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
+ * String支持的值为:true、false、yes、ok、no、1、0、是、否, 如果给定的值为空,或者转换失败,返回默认值
* 转换失败不会报错 * * @param value 被转换的值 @@ -565,10 +570,12 @@ public class Convert case "yes": case "ok": case "1": + case "是": return true; case "false": case "no": case "0": + case "否": return false; default: return defaultValue; @@ -791,14 +798,23 @@ public class Convert { return (String) obj; } - else if (obj instanceof byte[]) + else if (obj instanceof byte[] || obj instanceof Byte[]) { - return str((byte[]) obj, charset); - } - else if (obj instanceof Byte[]) - { - byte[] bytes = ArrayUtils.toPrimitive((Byte[]) obj); - return str(bytes, charset); + if (obj instanceof byte[]) + { + return str((byte[]) obj, charset); + } + else + { + Byte[] bytes = (Byte[]) obj; + int length = bytes.length; + byte[] dest = new byte[length]; + for (int i = 0; i < length; i++) + { + dest[i] = bytes[i]; + } + return str(dest, charset); + } } else if (obj instanceof ByteBuffer) { @@ -954,9 +970,7 @@ public class Convert c[i] = (char) (c[i] - 65248); } } - String returnString = new String(c); - - return returnString; + return new String(c); } /** @@ -977,7 +991,12 @@ public class Convert String s = ""; for (int i = 0; i < fraction.length; i++) { - s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""); + // 优化double计算精度丢失问题 + BigDecimal nNum = new BigDecimal(n); + BigDecimal decimal = new BigDecimal(10); + BigDecimal scale = nNum.multiply(decimal).setScale(2, RoundingMode.HALF_EVEN); + double d = scale.doubleValue(); + s += (digit[(int) (Math.floor(d * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""); } if (s.length() < 1) { diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/enums/DesensitizedType.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/enums/DesensitizedType.java new file mode 100644 index 00000000..4d0551c9 --- /dev/null +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/enums/DesensitizedType.java @@ -0,0 +1,60 @@ +package com.fastbee.common.enums; + +import com.fastbee.common.utils.DesensitizedUtil; + +import java.util.function.Function; + +/** + * 脱敏类型 + * + * @author ruoyi + */ +public enum DesensitizedType +{ + /** + * 姓名,第2位星号替换 + */ + USERNAME(s -> s.replaceAll("(\\S)\\S(\\S*)", "$1*$2")), + + /** + * 密码,全部字符都用*代替 + */ + PASSWORD(DesensitizedUtil::password), + + /** + * 身份证,中间10位星号替换 + */ + ID_CARD(s -> s.replaceAll("(\\d{4})\\d{10}(\\d{3}[Xx]|\\d{4})", "$1** **** ****$2")), + + /** + * 手机号,中间4位星号替换 + */ + PHONE(s -> s.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2")), + + /** + * 电子邮箱,仅显示第一个字母和@后面的地址显示,其他星号替换 + */ + EMAIL(s -> s.replaceAll("(^.)[^@]*(@.*$)", "$1****$2")), + + /** + * 银行卡号,保留最后4位,其他星号替换 + */ + BANK_CARD(s -> s.replaceAll("\\d{15}(\\d{3})", "**** **** **** **** $1")), + + /** + * 车牌号码,包含普通车辆、新能源车辆 + */ + CAR_LICENSE(DesensitizedUtil::carLicense); + + private final Function desensitizer; + + DesensitizedType(Function desensitizer) + { + this.desensitizer = desensitizer; + } + + public Function desensitizer() + { + return desensitizer; + } +} diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/DesensitizedUtil.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/DesensitizedUtil.java new file mode 100644 index 00000000..8bca6b01 --- /dev/null +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/DesensitizedUtil.java @@ -0,0 +1,49 @@ +package com.fastbee.common.utils; + +/** + * 脱敏工具类 + * + * @author ruoyi + */ +public class DesensitizedUtil +{ + /** + * 密码的全部字符都用*代替,比如:****** + * + * @param password 密码 + * @return 脱敏后的密码 + */ + public static String password(String password) + { + if (StringUtils.isBlank(password)) + { + return StringUtils.EMPTY; + } + return StringUtils.repeat('*', password.length()); + } + + /** + * 车牌中间用*代替,如果是错误的车牌,不处理 + * + * @param carLicense 完整的车牌号 + * @return 脱敏后的车牌 + */ + public static String carLicense(String carLicense) + { + if (StringUtils.isBlank(carLicense)) + { + return StringUtils.EMPTY; + } + // 普通车牌 + if (carLicense.length() == 7) + { + carLicense = StringUtils.hide(carLicense, 3, 6); + } + else if (carLicense.length() == 8) + { + // 新能源车牌 + carLicense = StringUtils.hide(carLicense, 3, 7); + } + return carLicense; + } +} diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/DictUtils.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/DictUtils.java index c849fad0..c81adad0 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/DictUtils.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/DictUtils.java @@ -1,13 +1,14 @@ package com.fastbee.common.utils; -import java.util.Collection; -import java.util.List; import com.alibaba.fastjson2.JSONArray; import com.fastbee.common.constant.CacheConstants; import com.fastbee.common.core.domain.entity.SysDictData; import com.fastbee.common.core.redis.RedisCache; import com.fastbee.common.utils.spring.SpringUtils; +import java.util.Collection; +import java.util.List; + /** * 字典工具类 * @@ -56,6 +57,10 @@ public class DictUtils */ public static String getDictLabel(String dictType, String dictValue) { + if (StringUtils.isEmpty(dictValue)) + { + return StringUtils.EMPTY; + } return getDictLabel(dictType, dictValue, SEPARATOR); } @@ -68,6 +73,10 @@ public class DictUtils */ public static String getDictValue(String dictType, String dictLabel) { + if (StringUtils.isEmpty(dictLabel)) + { + return StringUtils.EMPTY; + } return getDictValue(dictType, dictLabel, SEPARATOR); } @@ -83,31 +92,31 @@ public class DictUtils { StringBuilder propertyString = new StringBuilder(); List datas = getDictCache(dictType); - - if (StringUtils.isNotNull(datas)) + if (StringUtils.isNull(datas)) { - if (StringUtils.containsAny(separator, dictValue)) + return StringUtils.EMPTY; + } + if (StringUtils.containsAny(separator, dictValue)) + { + for (SysDictData dict : datas) { - for (SysDictData dict : datas) + for (String value : dictValue.split(separator)) { - for (String value : dictValue.split(separator)) + if (value.equals(dict.getDictValue())) { - if (value.equals(dict.getDictValue())) - { - propertyString.append(dict.getDictLabel()).append(separator); - break; - } + propertyString.append(dict.getDictLabel()).append(separator); + break; } } } - else + } + else + { + for (SysDictData dict : datas) { - for (SysDictData dict : datas) + if (dictValue.equals(dict.getDictValue())) { - if (dictValue.equals(dict.getDictValue())) - { - return dict.getDictLabel(); - } + return dict.getDictLabel(); } } } @@ -126,8 +135,11 @@ public class DictUtils { StringBuilder propertyString = new StringBuilder(); List datas = getDictCache(dictType); - - if (StringUtils.containsAny(separator, dictLabel) && StringUtils.isNotEmpty(datas)) + if (StringUtils.isNull(datas)) + { + return StringUtils.EMPTY; + } + if (StringUtils.containsAny(separator, dictLabel)) { for (SysDictData dict : datas) { @@ -154,6 +166,48 @@ public class DictUtils return StringUtils.stripEnd(propertyString.toString(), separator); } + /** + * 根据字典类型获取字典所有值 + * + * @param dictType 字典类型 + * @return 字典值 + */ + public static String getDictValues(String dictType) + { + StringBuilder propertyString = new StringBuilder(); + List datas = getDictCache(dictType); + if (StringUtils.isNull(datas)) + { + return StringUtils.EMPTY; + } + for (SysDictData dict : datas) + { + propertyString.append(dict.getDictValue()).append(SEPARATOR); + } + return StringUtils.stripEnd(propertyString.toString(), SEPARATOR); + } + + /** + * 根据字典类型获取字典所有标签 + * + * @param dictType 字典类型 + * @return 字典值 + */ + public static String getDictLabels(String dictType) + { + StringBuilder propertyString = new StringBuilder(); + List datas = getDictCache(dictType); + if (StringUtils.isNull(datas)) + { + return StringUtils.EMPTY; + } + for (SysDictData dict : datas) + { + propertyString.append(dict.getDictLabel()).append(SEPARATOR); + } + return StringUtils.stripEnd(propertyString.toString(), SEPARATOR); + } + /** * 删除指定字典缓存 * diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/SecurityUtils.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/SecurityUtils.java index dd3e1470..6a9a25cc 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/SecurityUtils.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/SecurityUtils.java @@ -1,19 +1,27 @@ package com.fastbee.common.utils; +import com.fastbee.common.constant.Constants; +import com.fastbee.common.constant.HttpStatus; +import com.fastbee.common.core.domain.entity.SysRole; +import com.fastbee.common.core.domain.model.LoginUser; +import com.fastbee.common.exception.ServiceException; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import com.fastbee.common.constant.HttpStatus; -import com.fastbee.common.core.domain.model.LoginUser; -import com.fastbee.common.exception.ServiceException; +import org.springframework.util.PatternMatchUtils; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; /** * 安全服务工具类 - * + * * @author ruoyi */ public class SecurityUtils { + /** * 用户ID **/ @@ -43,7 +51,7 @@ public class SecurityUtils throw new ServiceException("获取部门ID异常", HttpStatus.UNAUTHORIZED); } } - + /** * 获取用户账户 **/ @@ -109,7 +117,7 @@ public class SecurityUtils /** * 是否为管理员 - * + * * @param userId 用户ID * @return 结果 */ @@ -117,4 +125,55 @@ public class SecurityUtils { return userId != null && 1L == userId; } + + /** + * 验证用户是否具备某权限 + * + * @param permission 权限字符串 + * @return 用户是否具备某权限 + */ + public static boolean hasPermi(String permission) + { + return hasPermi(getLoginUser().getPermissions(), permission); + } + + /** + * 判断是否包含权限 + * + * @param authorities 权限列表 + * @param permission 权限字符串 + * @return 用户是否具备某权限 + */ + public static boolean hasPermi(Collection authorities, String permission) + { + return authorities.stream().filter(StringUtils::hasText) + .anyMatch(x -> Constants.ALL_PERMISSION.equals(x) || PatternMatchUtils.simpleMatch(x, permission)); + } + + /** + * 验证用户是否拥有某个角色 + * + * @param role 角色标识 + * @return 用户是否具备某角色 + */ + public static boolean hasRole(String role) + { + List roleList = getLoginUser().getUser().getRoles(); + Collection roles = roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet()); + return hasRole(roles, role); + } + + /** + * 判断是否包含角色 + * + * @param roles 角色列表 + * @param role 角色 + * @return 用户是否具备某角色权限 + */ + public static boolean hasRole(Collection roles, String role) + { + return roles.stream().filter(StringUtils::hasText) + .anyMatch(x -> Constants.SUPER_ADMIN.equals(x) || PatternMatchUtils.simpleMatch(x, role)); + } + } diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/StringUtils.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/StringUtils.java index b6e6742e..fe855364 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/StringUtils.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/StringUtils.java @@ -1,43 +1,35 @@ package com.fastbee.common.utils; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufUtil; -import org.springframework.util.AntPathMatcher; import com.fastbee.common.constant.Constants; import com.fastbee.common.core.text.StrFormatter; +import org.springframework.util.AntPathMatcher; + +import java.util.*; /** * 字符串工具类 * * @author ruoyi */ -public class StringUtils extends org.apache.commons.lang3.StringUtils { - /** - * 空字符串 - */ +public class StringUtils extends org.apache.commons.lang3.StringUtils +{ + /** 空字符串 */ private static final String NULLSTR = ""; - /** - * 下划线 - */ + /** 下划线 */ private static final char SEPARATOR = '_'; + /** 星号 */ + private static final char ASTERISK = '*'; + /** * 获取参数不为空值 * * @param value defaultValue 要判断的value * @return value 返回值 */ - public static T nvl(T value, T defaultValue) { + public static T nvl(T value, T defaultValue) + { return value != null ? value : defaultValue; } @@ -47,7 +39,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param coll 要判断的Collection * @return true:为空 false:非空 */ - public static boolean isEmpty(Collection coll) { + public static boolean isEmpty(Collection coll) + { return isNull(coll) || coll.isEmpty(); } @@ -57,7 +50,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param coll 要判断的Collection * @return true:非空 false:空 */ - public static boolean isNotEmpty(Collection coll) { + public static boolean isNotEmpty(Collection coll) + { return !isEmpty(coll); } @@ -65,9 +59,10 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * * 判断一个对象数组是否为空 * * @param objects 要判断的对象数组 - * * @return true:为空 false:非空 + ** @return true:为空 false:非空 */ - public static boolean isEmpty(Object[] objects) { + public static boolean isEmpty(Object[] objects) + { return isNull(objects) || (objects.length == 0); } @@ -77,7 +72,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param objects 要判断的对象数组 * @return true:非空 false:空 */ - public static boolean isNotEmpty(Object[] objects) { + public static boolean isNotEmpty(Object[] objects) + { return !isEmpty(objects); } @@ -87,7 +83,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param map 要判断的Map * @return true:为空 false:非空 */ - public static boolean isEmpty(Map map) { + public static boolean isEmpty(Map map) + { return isNull(map) || map.isEmpty(); } @@ -97,7 +94,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param map 要判断的Map * @return true:非空 false:空 */ - public static boolean isNotEmpty(Map map) { + public static boolean isNotEmpty(Map map) + { return !isEmpty(map); } @@ -107,7 +105,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param str String * @return true:为空 false:非空 */ - public static boolean isEmpty(String str) { + public static boolean isEmpty(String str) + { return isNull(str) || NULLSTR.equals(str.trim()); } @@ -117,7 +116,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param str String * @return true:非空串 false:空串 */ - public static boolean isNotEmpty(String str) { + public static boolean isNotEmpty(String str) + { return !isEmpty(str); } @@ -127,7 +127,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param object Object * @return true:为空 false:非空 */ - public static boolean isNull(Object object) { + public static boolean isNull(Object object) + { return object == null; } @@ -137,7 +138,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param object Object * @return true:非空 false:空 */ - public static boolean isNotNull(Object object) { + public static boolean isNotNull(Object object) + { return !isNull(object); } @@ -147,37 +149,87 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param object 对象 * @return true:是数组 false:不是数组 */ - public static boolean isArray(Object object) { + public static boolean isArray(Object object) + { return isNotNull(object) && object.getClass().isArray(); } /** * 去空格 */ - public static String trim(String str) { + public static String trim(String str) + { return (str == null ? "" : str.trim()); } + /** + * 替换指定字符串的指定区间内字符为"*" + * + * @param str 字符串 + * @param startInclude 开始位置(包含) + * @param endExclude 结束位置(不包含) + * @return 替换后的字符串 + */ + public static String hide(CharSequence str, int startInclude, int endExclude) + { + if (isEmpty(str)) + { + return NULLSTR; + } + final int strLength = str.length(); + if (startInclude > strLength) + { + return NULLSTR; + } + if (endExclude > strLength) + { + endExclude = strLength; + } + if (startInclude > endExclude) + { + // 如果起始位置大于结束位置,不替换 + return NULLSTR; + } + final char[] chars = new char[strLength]; + for (int i = 0; i < strLength; i++) + { + if (i >= startInclude && i < endExclude) + { + chars[i] = ASTERISK; + } + else + { + chars[i] = str.charAt(i); + } + } + return new String(chars); + } + /** * 截取字符串 * - * @param str 字符串 + * @param str 字符串 * @param start 开始 * @return 结果 */ - public static String substring(final String str, int start) { - if (str == null) { + public static String substring(final String str, int start) + { + if (str == null) + { return NULLSTR; } - if (start < 0) { + if (start < 0) + { start = str.length() + start; } - if (start < 0) { + if (start < 0) + { start = 0; } - if (start > str.length()) { + if (start > str.length()) + { return NULLSTR; } @@ -187,41 +239,99 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { /** * 截取字符串 * - * @param str 字符串 + * @param str 字符串 * @param start 开始 - * @param end 结束 + * @param end 结束 * @return 结果 */ - public static String substring(final String str, int start, int end) { - if (str == null) { + public static String substring(final String str, int start, int end) + { + if (str == null) + { return NULLSTR; } - if (end < 0) { + if (end < 0) + { end = str.length() + end; } - if (start < 0) { + if (start < 0) + { start = str.length() + start; } - if (end > str.length()) { + if (end > str.length()) + { end = str.length(); } - if (start > end) { + if (start > end) + { return NULLSTR; } - if (start < 0) { + if (start < 0) + { start = 0; } - if (end < 0) { + if (end < 0) + { end = 0; } return str.substring(start, end); } + /** + * 在字符串中查找第一个出现的 `open` 和最后一个出现的 `close` 之间的子字符串 + * + * @param str 要截取的字符串 + * @param open 起始字符串 + * @param close 结束字符串 + * @return 截取结果 + */ + public static String substringBetweenLast(final String str, final String open, final String close) + { + if (isEmpty(str) || isEmpty(open) || isEmpty(close)) + { + return NULLSTR; + } + final int start = str.indexOf(open); + if (start != INDEX_NOT_FOUND) + { + final int end = str.lastIndexOf(close); + if (end != INDEX_NOT_FOUND) + { + return str.substring(start + open.length(), end); + } + } + return NULLSTR; + } + + /** + * 判断是否为空,并且不是空白字符 + * + * @param str 要判断的value + * @return 结果 + */ + public static boolean hasText(String str) + { + return (str != null && !str.isEmpty() && containsText(str)); + } + + private static boolean containsText(CharSequence str) + { + int strLen = str.length(); + for (int i = 0; i < strLen; i++) + { + if (!Character.isWhitespace(str.charAt(i))) + { + return true; + } + } + return false; + } + /** * 格式化文本, {} 表示占位符
* 此方法只是简单将占位符 {} 按照顺序替换为参数
@@ -232,11 +342,13 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
* * @param template 文本模板,被替换的部分用 {} 表示 - * @param params 参数值 + * @param params 参数值 * @return 格式化后的文本 */ - public static String format(String template, Object... params) { - if (isEmpty(params) || isEmpty(template)) { + public static String format(String template, Object... params) + { + if (isEmpty(params) || isEmpty(template)) + { return template; } return StrFormatter.format(template, params); @@ -248,7 +360,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param link 链接 * @return 结果 */ - public static boolean ishttp(String link) { + public static boolean ishttp(String link) + { return StringUtils.startsWithAny(link, Constants.HTTP, Constants.HTTPS); } @@ -259,35 +372,42 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param sep 分隔符 * @return set集合 */ - public static final Set str2Set(String str, String sep) { + public static final Set str2Set(String str, String sep) + { return new HashSet(str2List(str, sep, true, false)); } /** * 字符串转list * - * @param str 字符串 - * @param sep 分隔符 + * @param str 字符串 + * @param sep 分隔符 * @param filterBlank 过滤纯空白 - * @param trim 去掉首尾空白 + * @param trim 去掉首尾空白 * @return list集合 */ - public static final List str2List(String str, String sep, boolean filterBlank, boolean trim) { + public static final List str2List(String str, String sep, boolean filterBlank, boolean trim) + { List list = new ArrayList(); - if (StringUtils.isEmpty(str)) { + if (StringUtils.isEmpty(str)) + { return list; } // 过滤空白字符串 - if (filterBlank && StringUtils.isBlank(str)) { + if (filterBlank && StringUtils.isBlank(str)) + { return list; } String[] split = str.split(sep); - for (String string : split) { - if (filterBlank && StringUtils.isBlank(string)) { + for (String string : split) + { + if (filterBlank && StringUtils.isBlank(string)) + { continue; } - if (trim) { + if (trim) + { string = string.trim(); } list.add(string); @@ -297,18 +417,24 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { } /** - * 判断给定的set列表中是否包含数组array 判断给定的数组array中是否包含给定的元素value + * 判断给定的collection列表中是否包含数组array 判断给定的数组array中是否包含给定的元素value * - * @param set 给定的集合 + * @param collection 给定的集合 * @param array 给定的数组 * @return boolean 结果 */ - public static boolean containsAny(Collection collection, String... array) { - if (isEmpty(collection) || isEmpty(array)) { + public static boolean containsAny(Collection collection, String... array) + { + if (isEmpty(collection) || isEmpty(array)) + { return false; - } else { - for (String str : array) { - if (collection.contains(str)) { + } + else + { + for (String str : array) + { + if (collection.contains(str)) + { return true; } } @@ -319,16 +445,20 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { /** * 查找指定字符串是否包含指定字符串列表中的任意一个字符串同时串忽略大小写 * - * @param cs 指定字符串 + * @param cs 指定字符串 * @param searchCharSequences 需要检查的字符串数组 * @return 是否包含任意一个字符串 */ - public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) { - if (isEmpty(cs) || isEmpty(searchCharSequences)) { + public static boolean containsAnyIgnoreCase(CharSequence cs, CharSequence... searchCharSequences) + { + if (isEmpty(cs) || isEmpty(searchCharSequences)) + { return false; } - for (CharSequence testStr : searchCharSequences) { - if (containsIgnoreCase(cs, testStr)) { + for (CharSequence testStr : searchCharSequences) + { + if (containsIgnoreCase(cs, testStr)) + { return true; } } @@ -338,8 +468,10 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { /** * 驼峰转下划线命名 */ - public static String toUnderScoreCase(String str) { - if (str == null) { + public static String toUnderScoreCase(String str) + { + if (str == null) + { return null; } StringBuilder sb = new StringBuilder(); @@ -349,23 +481,31 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { boolean curreCharIsUpperCase = true; // 下一字符是否大写 boolean nexteCharIsUpperCase = true; - for (int i = 0; i < str.length(); i++) { + for (int i = 0; i < str.length(); i++) + { char c = str.charAt(i); - if (i > 0) { + if (i > 0) + { preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1)); - } else { + } + else + { preCharIsUpperCase = false; } curreCharIsUpperCase = Character.isUpperCase(c); - if (i < (str.length() - 1)) { + if (i < (str.length() - 1)) + { nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); } - if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) { + if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) + { sb.append(SEPARATOR); - } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) { + } + else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) + { sb.append(SEPARATOR); } sb.append(Character.toLowerCase(c)); @@ -377,14 +517,18 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { /** * 是否包含字符串 * - * @param str 验证字符串 + * @param str 验证字符串 * @param strs 字符串组 * @return 包含返回true */ - public static boolean inStringIgnoreCase(String str, String... strs) { - if (str != null && strs != null) { - for (String s : strs) { - if (str.equalsIgnoreCase(trim(s))) { + public static boolean inStringIgnoreCase(String str, String... strs) + { + if (str != null && strs != null) + { + for (String s : strs) + { + if (str.equalsIgnoreCase(trim(s))) + { return true; } } @@ -398,21 +542,27 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * @param name 转换前的下划线大写方式命名的字符串 * @return 转换后的驼峰式命名的字符串 */ - public static String convertToCamelCase(String name) { + public static String convertToCamelCase(String name) + { StringBuilder result = new StringBuilder(); // 快速检查 - if (name == null || name.isEmpty()) { + if (name == null || name.isEmpty()) + { // 没必要转换 return ""; - } else if (!name.contains("_")) { + } + else if (!name.contains("_")) + { // 不含下划线,仅将首字母大写 return name.substring(0, 1).toUpperCase() + name.substring(1); } // 用下划线将原始字符串分割 String[] camels = name.split("_"); - for (String camel : camels) { + for (String camel : camels) + { // 跳过原始字符串中开头、结尾的下换线或双重下划线 - if (camel.isEmpty()) { + if (camel.isEmpty()) + { continue; } // 首字母大写 @@ -423,24 +573,37 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { } /** - * 驼峰式命名法 例如:user_name->userName + * 驼峰式命名法 + * 例如:user_name->userName */ - public static String toCamelCase(String s) { - if (s == null) { + public static String toCamelCase(String s) + { + if (s == null) + { return null; } + if (s.indexOf(SEPARATOR) == -1) + { + return s; + } s = s.toLowerCase(); StringBuilder sb = new StringBuilder(s.length()); boolean upperCase = false; - for (int i = 0; i < s.length(); i++) { + for (int i = 0; i < s.length(); i++) + { char c = s.charAt(i); - if (c == SEPARATOR) { + if (c == SEPARATOR) + { upperCase = true; - } else if (upperCase) { + } + else if (upperCase) + { sb.append(Character.toUpperCase(c)); upperCase = false; - } else { + } + else + { sb.append(c); } } @@ -450,16 +613,20 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { /** * 查找指定字符串是否匹配指定字符串列表中的任意一个字符串 * - * @param str 指定字符串 + * @param str 指定字符串 * @param strs 需要检查的字符串数组 * @return 是否匹配 */ - public static boolean matches(String str, List strs) { - if (isEmpty(str) || isEmpty(strs)) { + public static boolean matches(String str, List strs) + { + if (isEmpty(str) || isEmpty(strs)) + { return false; } - for (String pattern : strs) { - if (isMatch(pattern, str)) { + for (String pattern : strs) + { + if (isMatch(pattern, str)) + { return true; } } @@ -473,202 +640,67 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils { * ** 表示任意层路径; * * @param pattern 匹配规则 - * @param url 需要匹配的url + * @param url 需要匹配的url * @return */ - public static boolean isMatch(String pattern, String url) { + public static boolean isMatch(String pattern, String url) + { AntPathMatcher matcher = new AntPathMatcher(); return matcher.match(pattern, url); } @SuppressWarnings("unchecked") - public static T cast(Object obj) { + public static T cast(Object obj) + { return (T) obj; } /** * 数字左边补齐0,使之达到指定长度。注意,如果数字转换为字符串后,长度大于size,则只保留 最后size个字符。 * - * @param num 数字对象 + * @param num 数字对象 * @param size 字符串指定长度 * @return 返回数字的字符串格式,该字符串为指定长度。 */ - public static final String padl(final Number num, final int size) { + public static final String padl(final Number num, final int size) + { return padl(num.toString(), size, '0'); } /** * 字符串左补齐。如果原始字符串s长度大于size,则只保留最后size个字符。 * - * @param s 原始字符串 + * @param s 原始字符串 * @param size 字符串指定长度 - * @param c 用于补齐的字符 + * @param c 用于补齐的字符 * @return 返回指定长度的字符串,由原字符串左补齐或截取得到。 */ - public static final String padl(final String s, final int size, final char c) { + public static final String padl(final String s, final int size, final char c) + { final StringBuilder sb = new StringBuilder(size); - if (s != null) { + if (s != null) + { final int len = s.length(); - if (s.length() <= size) { - for (int i = size - len; i > 0; i--) { + if (s.length() <= size) + { + for (int i = size - len; i > 0; i--) + { sb.append(c); } sb.append(s); - } else { + } + else + { return s.substring(len - size, len); } - } else { - for (int i = size; i > 0; i--) { + } + else + { + for (int i = size; i > 0; i--) + { sb.append(c); } } return sb.toString(); } - - /*将字符串转小写,首字母大写,其他小写*/ - public static String upperCase(String str) { - char[] ch = str.toLowerCase().toCharArray(); - if (ch[0] >= 'a' && ch[0] <= 'z') { - ch[0] = (char) (ch[0] - 32); - } - return new String(ch); - } - - public static String toString(Object value) { - if (value == null) { - return "null"; - } - if (value instanceof ByteBuf) { - return ByteBufUtil.hexDump((ByteBuf) value); - } - if (!value.getClass().isArray()) { - return value.toString(); - } - - StringBuilder root = new StringBuilder(32); - toString(value, root); - return root.toString(); - } - - public static StringBuilder toString(Object value, StringBuilder builder) { - if (value == null) { - return builder; - } - - builder.append('['); - int start = builder.length(); - - if (value instanceof long[]) { - long[] array = (long[]) value; - for (long t : array) { - builder.append(t).append(','); - } - - } else if (value instanceof int[]) { - int[] array = (int[]) value; - for (int t : array) { - builder.append(t).append(','); - } - - } else if (value instanceof short[]) { - short[] array = (short[]) value; - for (short t : array) { - builder.append(t).append(','); - } - - } else if (value instanceof byte[]) { - byte[] array = (byte[]) value; - for (byte t : array) { - builder.append(t).append(','); - } - - } else if (value instanceof char[]) { - char[] array = (char[]) value; - for (char t : array) { - builder.append(t).append(','); - } - - } else if (value instanceof double[]) { - double[] array = (double[]) value; - for (double t : array) { - builder.append(t).append(','); - } - - } else if (value instanceof float[]) { - float[] array = (float[]) value; - for (float t : array) { - builder.append(t).append(','); - } - - } else if (value instanceof boolean[]) { - boolean[] array = (boolean[]) value; - for (boolean t : array) { - builder.append(t).append(','); - } - - } else if (value instanceof String[]) { - String[] array = (String[]) value; - for (String t : array) { - builder.append(t).append(','); - } - - } else if (isArray1(value)) { - Object[] array = (Object[]) value; - for (Object t : array) { - toString(t, builder).append(','); - } - - } else if (value instanceof Object[]) { - Object[] array = (Object[]) value; - for (Object t : array) { - builder.append(t).append(','); - } - } - - int end = builder.length(); - if (end <= start) { - builder.append(']'); - } else { - builder.setCharAt(end - 1, ']'); - } - return builder; - } - - private static boolean isArray1(Object value) { - Class componentType = value.getClass().getComponentType(); - if (componentType == null) { - return false; - } - return componentType.isArray(); - } - - public static String leftPad(String str, int size, char ch) { - int length = str.length(); - int pads = size - length; - if (pads > 0) { - char[] result = new char[size]; - str.getChars(0, length, result, pads); - while (pads > 0) { - result[--pads] = ch; - } - return new String(result); - } - return str; - } - - /** - * 获取字符串中的数字 - * @param str - * @return - */ - public static Integer matcherNum(String str){ - Pattern pattern = Pattern.compile("\\d+"); - Matcher matcher = pattern.matcher(str); - while (matcher.find()){ - return Integer.parseInt(matcher.group()); - } - return 0; - } - - } diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/ip/IpUtils.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/ip/IpUtils.java index 6aea1506..d1456b04 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/ip/IpUtils.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/ip/IpUtils.java @@ -1,20 +1,39 @@ package com.fastbee.common.utils.ip; +import com.fastbee.common.utils.ServletUtils; +import com.fastbee.common.utils.StringUtils; + +import javax.servlet.http.HttpServletRequest; import java.net.InetAddress; import java.net.UnknownHostException; -import javax.servlet.http.HttpServletRequest; -import com.fastbee.common.utils.StringUtils; /** * 获取IP方法 - * + * * @author ruoyi */ public class IpUtils { + public final static String REGX_0_255 = "(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)"; + // 匹配 ip + public final static String REGX_IP = "((" + REGX_0_255 + "\\.){3}" + REGX_0_255 + ")"; + public final static String REGX_IP_WILDCARD = "(((\\*\\.){3}\\*)|(" + REGX_0_255 + "(\\.\\*){3})|(" + REGX_0_255 + "\\." + REGX_0_255 + ")(\\.\\*){2}" + "|((" + REGX_0_255 + "\\.){3}\\*))"; + // 匹配网段 + public final static String REGX_IP_SEG = "(" + REGX_IP + "\\-" + REGX_IP + ")"; + /** * 获取客户端IP - * + * + * @return IP地址 + */ + public static String getIpAddr() + { + return getIpAddr(ServletUtils.getRequest()); + } + + /** + * 获取客户端IP + * * @param request 请求对象 * @return IP地址 */ @@ -52,7 +71,7 @@ public class IpUtils /** * 检查是否为内部IP地址 - * + * * @param ip IP地址 * @return 结果 */ @@ -64,7 +83,7 @@ public class IpUtils /** * 检查是否为内部IP地址 - * + * * @param addr byte地址 * @return 结果 */ @@ -107,7 +126,7 @@ public class IpUtils /** * 将IPv4地址转换成字节 - * + * * @param text IPv4地址 * @return byte 字节 */ @@ -195,7 +214,7 @@ public class IpUtils /** * 获取IP地址 - * + * * @return 本地IP地址 */ public static String getHostIp() @@ -212,7 +231,7 @@ public class IpUtils /** * 获取主机名 - * + * * @return 本地主机名 */ public static String getHostName() @@ -248,7 +267,7 @@ public class IpUtils } } } - return ip; + return StringUtils.substring(ip, 0, 255); } /** @@ -261,4 +280,104 @@ public class IpUtils { return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString); } -} \ No newline at end of file + + /** + * 是否为IP + */ + public static boolean isIP(String ip) + { + return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP); + } + + /** + * 是否为IP,或 *为间隔的通配符地址 + */ + public static boolean isIpWildCard(String ip) + { + return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP_WILDCARD); + } + + /** + * 检测参数是否在ip通配符里 + */ + public static boolean ipIsInWildCardNoCheck(String ipWildCard, String ip) + { + String[] s1 = ipWildCard.split("\\."); + String[] s2 = ip.split("\\."); + boolean isMatchedSeg = true; + for (int i = 0; i < s1.length && !s1[i].equals("*"); i++) + { + if (!s1[i].equals(s2[i])) + { + isMatchedSeg = false; + break; + } + } + return isMatchedSeg; + } + + /** + * 是否为特定格式如:“10.10.10.1-10.10.10.99”的ip段字符串 + */ + public static boolean isIPSegment(String ipSeg) + { + return StringUtils.isNotBlank(ipSeg) && ipSeg.matches(REGX_IP_SEG); + } + + /** + * 判断ip是否在指定网段中 + */ + public static boolean ipIsInNetNoCheck(String iparea, String ip) + { + int idx = iparea.indexOf('-'); + String[] sips = iparea.substring(0, idx).split("\\."); + String[] sipe = iparea.substring(idx + 1).split("\\."); + String[] sipt = ip.split("\\."); + long ips = 0L, ipe = 0L, ipt = 0L; + for (int i = 0; i < 4; ++i) + { + ips = ips << 8 | Integer.parseInt(sips[i]); + ipe = ipe << 8 | Integer.parseInt(sipe[i]); + ipt = ipt << 8 | Integer.parseInt(sipt[i]); + } + if (ips > ipe) + { + long t = ips; + ips = ipe; + ipe = t; + } + return ips <= ipt && ipt <= ipe; + } + + /** + * 校验ip是否符合过滤串规则 + * + * @param filter 过滤IP列表,支持后缀'*'通配,支持网段如:`10.10.10.1-10.10.10.99` + * @param ip 校验IP地址 + * @return boolean 结果 + */ + public static boolean isMatchedIp(String filter, String ip) + { + if (StringUtils.isEmpty(filter) || StringUtils.isEmpty(ip)) + { + return false; + } + String[] ips = filter.split(";"); + for (String iStr : ips) + { + if (isIP(iStr) && iStr.equals(ip)) + { + return true; + } + else if (isIpWildCard(iStr) && ipIsInWildCardNoCheck(iStr, ip)) + { + return true; + } + else if (isIPSegment(iStr) && ipIsInNetNoCheck(iStr, ip)) + { + return true; + } + } + return false; + } +} diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/poi/ExcelHandlerAdapter.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/poi/ExcelHandlerAdapter.java index ca8f11d7..6be81acd 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/poi/ExcelHandlerAdapter.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/poi/ExcelHandlerAdapter.java @@ -1,19 +1,24 @@ package com.fastbee.common.utils.poi; +import org.apache.poi.ss.usermodel.Cell; +import org.apache.poi.ss.usermodel.Workbook; + /** * Excel数据格式处理适配器 - * + * * @author ruoyi */ public interface ExcelHandlerAdapter { /** * 格式化 - * + * * @param value 单元格数据值 * @param args excel注解args参数组 + * @param cell 单元格对象 + * @param wb 工作簿对象 * * @return 处理后的值 */ - Object format(Object value, String[] args); + Object format(Object value, String[] args, Cell cell, Workbook wb); } diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/poi/ExcelUtil.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/poi/ExcelUtil.java index 45eca859..a038da09 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/poi/ExcelUtil.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/poi/ExcelUtil.java @@ -1,74 +1,5 @@ package com.fastbee.common.utils.poi; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.lang.reflect.ParameterizedType; -import java.math.BigDecimal; -import java.text.DecimalFormat; -import java.time.LocalDate; -import java.time.LocalDateTime; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Comparator; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.stream.Collectors; -import javax.servlet.http.HttpServletResponse; -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.lang3.RegExUtils; -import org.apache.commons.lang3.reflect.FieldUtils; -import org.apache.poi.hssf.usermodel.HSSFClientAnchor; -import org.apache.poi.hssf.usermodel.HSSFPicture; -import org.apache.poi.hssf.usermodel.HSSFPictureData; -import org.apache.poi.hssf.usermodel.HSSFShape; -import org.apache.poi.hssf.usermodel.HSSFSheet; -import org.apache.poi.hssf.usermodel.HSSFWorkbook; -import org.apache.poi.ooxml.POIXMLDocumentPart; -import org.apache.poi.ss.usermodel.BorderStyle; -import org.apache.poi.ss.usermodel.Cell; -import org.apache.poi.ss.usermodel.CellStyle; -import org.apache.poi.ss.usermodel.CellType; -import org.apache.poi.ss.usermodel.ClientAnchor; -import org.apache.poi.ss.usermodel.DataValidation; -import org.apache.poi.ss.usermodel.DataValidationConstraint; -import org.apache.poi.ss.usermodel.DataValidationHelper; -import org.apache.poi.ss.usermodel.DateUtil; -import org.apache.poi.ss.usermodel.Drawing; -import org.apache.poi.ss.usermodel.FillPatternType; -import org.apache.poi.ss.usermodel.Font; -import org.apache.poi.ss.usermodel.HorizontalAlignment; -import org.apache.poi.ss.usermodel.IndexedColors; -import org.apache.poi.ss.usermodel.Name; -import org.apache.poi.ss.usermodel.PictureData; -import org.apache.poi.ss.usermodel.Row; -import org.apache.poi.ss.usermodel.Sheet; -import org.apache.poi.ss.usermodel.VerticalAlignment; -import org.apache.poi.ss.usermodel.Workbook; -import org.apache.poi.ss.usermodel.WorkbookFactory; -import org.apache.poi.ss.util.CellRangeAddress; -import org.apache.poi.ss.util.CellRangeAddressList; -import org.apache.poi.util.IOUtils; -import org.apache.poi.xssf.streaming.SXSSFWorkbook; -import org.apache.poi.xssf.usermodel.XSSFClientAnchor; -import org.apache.poi.xssf.usermodel.XSSFDataValidation; -import org.apache.poi.xssf.usermodel.XSSFDrawing; -import org.apache.poi.xssf.usermodel.XSSFPicture; -import org.apache.poi.xssf.usermodel.XSSFShape; -import org.apache.poi.xssf.usermodel.XSSFSheet; -import org.apache.poi.xssf.usermodel.XSSFWorkbook; -import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import com.fastbee.common.annotation.Excel; import com.fastbee.common.annotation.Excel.ColumnType; import com.fastbee.common.annotation.Excel.Type; @@ -84,10 +15,36 @@ import com.fastbee.common.utils.file.FileTypeUtils; import com.fastbee.common.utils.file.FileUtils; import com.fastbee.common.utils.file.ImageUtils; import com.fastbee.common.utils.reflect.ReflectUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.RegExUtils; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.poi.hssf.usermodel.*; +import org.apache.poi.ooxml.POIXMLDocumentPart; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddress; +import org.apache.poi.ss.util.CellRangeAddressList; +import org.apache.poi.util.IOUtils; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.*; +import org.openxmlformats.schemas.drawingml.x2006.spreadsheetDrawing.CTMarker; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import javax.servlet.http.HttpServletResponse; +import java.io.*; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.lang.reflect.ParameterizedType; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.util.*; +import java.util.stream.Collectors; /** * Excel相关处理 - * + * * @author ruoyi */ public class ExcelUtil @@ -98,6 +55,11 @@ public class ExcelUtil public static final String[] FORMULA_STR = { "=", "-", "+", "@" }; + /** + * 用于dictType属性数据存储,避免重复查缓存 + */ + public Map sysDictMap = new HashMap(); + /** * Excel sheet最大行数,默认65536 */ @@ -188,6 +150,11 @@ public class ExcelUtil */ public Class clazz; + /** + * 需要显示列属性 + */ + public String[] includeFields; + /** * 需要排除列属性 */ @@ -198,11 +165,20 @@ public class ExcelUtil this.clazz = clazz; } + /** + * 仅在Excel中显示列属性 + * + * @param fields 列属性名 示例[单个"name"/多个"id","name"] + */ + public void showColumn(String... fields) + { + this.includeFields = fields; + } + /** * 隐藏Excel中列属性 * * @param fields 列属性名 示例[单个"name"/多个"id","name"] - * @throws Exception */ public void hideColumn(String... fields) { @@ -232,8 +208,6 @@ public class ExcelUtil { if (StringUtils.isNotEmpty(title)) { - subMergedFirstRowNum++; - subMergedLastRowNum++; int titleLastCol = this.fields.size() - 1; if (isSubList()) { @@ -244,7 +218,7 @@ public class ExcelUtil Cell titleCell = titleRow.createCell(0); titleCell.setCellStyle(styles.get("title")); titleCell.setCellValue(title); - sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), titleRow.getRowNum(), titleLastCol)); + sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(), titleRow.getRowNum(), 0, titleLastCol)); } } @@ -255,23 +229,31 @@ public class ExcelUtil { if (isSubList()) { - subMergedFirstRowNum++; - subMergedLastRowNum++; Row subRow = sheet.createRow(rownum); - int excelNum = 0; + int column = 0; + int subFieldSize = subFields != null ? subFields.size() : 0; for (Object[] objects : fields) { + Field field = (Field) objects[0]; Excel attr = (Excel) objects[1]; - Cell headCell1 = subRow.createCell(excelNum); - headCell1.setCellValue(attr.name()); - headCell1.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor()))); - excelNum++; - } - int headFirstRow = excelNum - 1; - int headLastRow = headFirstRow + subFields.size() - 1; - if (headLastRow > headFirstRow) - { - sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, headFirstRow, headLastRow)); + if (Collection.class.isAssignableFrom(field.getType())) + { + Cell cell = subRow.createCell(column); + cell.setCellValue(attr.name()); + cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor()))); + if (subFieldSize > 1) + { + CellRangeAddress cellAddress = new CellRangeAddress(rownum, rownum, column, column + subFieldSize - 1); + sheet.addMergedRegion(cellAddress); + } + column += subFieldSize; + } + else + { + Cell cell = subRow.createCell(column++); + cell.setCellValue(attr.name()); + cell.setCellStyle(styles.get(StringUtils.format("header_{}_{}", attr.headerColor(), attr.headerBackgroundColor()))); + } } rownum++; } @@ -279,30 +261,44 @@ public class ExcelUtil /** * 对excel表单默认第一个索引名转换成list - * + * * @param is 输入流 * @return 转换后集合 */ - public List importExcel(InputStream is) throws Exception + public List importExcel(InputStream is) { return importExcel(is, 0); } /** * 对excel表单默认第一个索引名转换成list - * + * * @param is 输入流 * @param titleNum 标题占用行数 * @return 转换后集合 */ - public List importExcel(InputStream is, int titleNum) throws Exception + public List importExcel(InputStream is, int titleNum) { - return importExcel(StringUtils.EMPTY, is, titleNum); + List list = null; + try + { + list = importExcel(StringUtils.EMPTY, is, titleNum); + } + catch (Exception e) + { + log.error("导入Excel异常{}", e.getMessage()); + throw new UtilException(e.getMessage()); + } + finally + { + IOUtils.closeQuietly(is); + } + return list; } /** * 对excel表单指定表格索引名转换成list - * + * * @param sheetName 表格索引名 * @param titleNum 标题占用行数 * @param is 输入流 @@ -331,7 +327,6 @@ public class ExcelUtil } // 获取最后一个非空行的行下标,比如总行数为n,则返回的为n-1 int rows = sheet.getLastRowNum(); - if (rows > 0) { // 定义一个map用于存放excel列的序号和field. @@ -446,17 +441,22 @@ public class ExcelUtil { propertyName = field.getName() + "." + attr.targetAttr(); } - else if (StringUtils.isNotEmpty(attr.readConverterExp())) + if (StringUtils.isNotEmpty(attr.readConverterExp())) { val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); } else if (StringUtils.isNotEmpty(attr.dictType())) { - val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator()); + if (!sysDictMap.containsKey(attr.dictType() + val)) + { + String dictValue = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator()); + sysDictMap.put(attr.dictType() + val, dictValue); + } + val = sysDictMap.get(attr.dictType() + val); } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) { - val = dataFormatHandlerAdapter(val, attr); + val = dataFormatHandlerAdapter(val, attr, null); } else if (ColumnType.IMAGE == attr.cellType() && StringUtils.isNotEmpty(pictures)) { @@ -482,7 +482,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param list 导出数据集合 * @param sheetName 工作表的名称 * @return 结果 @@ -494,7 +494,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param list 导出数据集合 * @param sheetName 工作表的名称 * @param title 标题 @@ -508,7 +508,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param response 返回数据 * @param list 导出数据集合 * @param sheetName 工作表的名称 @@ -521,7 +521,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param response 返回数据 * @param list 导出数据集合 * @param sheetName 工作表的名称 @@ -538,7 +538,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param sheetName 工作表的名称 * @return 结果 */ @@ -549,7 +549,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param sheetName 工作表的名称 * @param title 标题 * @return 结果 @@ -562,7 +562,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param sheetName 工作表的名称 * @return 结果 */ @@ -573,7 +573,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @param sheetName 工作表的名称 * @param title 标题 * @return 结果 @@ -588,7 +588,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @return 结果 */ public void exportExcel(HttpServletResponse response) @@ -610,7 +610,7 @@ public class ExcelUtil /** * 对list数据源将其里面的数据导入到excel表单 - * + * * @return 结果 */ public AjaxResult exportExcel() @@ -678,7 +678,7 @@ public class ExcelUtil /** * 填充excel数据 - * + * * @param index 序号 * @param row 单元格行 */ @@ -687,69 +687,96 @@ public class ExcelUtil { int startNo = index * sheetSize; int endNo = Math.min(startNo + sheetSize, list.size()); - int rowNo = (1 + rownum) - startNo; + int currentRowNum = rownum + 1; // 从标题行后开始 + for (int i = startNo; i < endNo; i++) { - rowNo = isSubList() ? (i > 1 ? rowNo + 1 : rowNo + i) : i + 1 + rownum - startNo; - row = sheet.createRow(rowNo); - // 得到导出对象. + row = sheet.createRow(currentRowNum); T vo = (T) list.get(i); - Collection subList = null; - if (isSubList()) - { - if (isSubListValue(vo)) - { - subList = getListCellValue(vo); - subMergedLastRowNum = subMergedLastRowNum + subList.size(); - } - else - { - subMergedFirstRowNum++; - subMergedLastRowNum++; - } - } int column = 0; + int maxSubListSize = getCurrentMaxSubListSize(vo); for (Object[] os : fields) { Field field = (Field) os[0]; Excel excel = (Excel) os[1]; - if (Collection.class.isAssignableFrom(field.getType()) && StringUtils.isNotNull(subList)) + if (Collection.class.isAssignableFrom(field.getType())) { - boolean subFirst = false; - for (Object obj : subList) + try { - if (subFirst) + Collection subList = (Collection) getTargetValue(vo, field, excel); + if (subList != null && !subList.isEmpty()) { - rowNo++; - row = sheet.createRow(rowNo); - } - List subFields = FieldUtils.getFieldsListWithAnnotation(obj.getClass(), Excel.class); - int subIndex = 0; - for (Field subField : subFields) - { - if (subField.isAnnotationPresent(Excel.class)) + int subIndex = 0; + for (Object subVo : subList) { - subField.setAccessible(true); - Excel attr = subField.getAnnotation(Excel.class); - this.addCell(attr, row, (T) obj, subField, column + subIndex); + Row subRow = sheet.getRow(currentRowNum + subIndex); + if (subRow == null) + { + subRow = sheet.createRow(currentRowNum + subIndex); + } + + int subColumn = column; + for (Field subField : subFields) + { + Excel subExcel = subField.getAnnotation(Excel.class); + addCell(subExcel, subRow, (T) subVo, subField, subColumn++); + } + subIndex++; } - subIndex++; + column += subFields.size(); } - subFirst = true; } - this.subMergedFirstRowNum = this.subMergedFirstRowNum + subList.size(); + catch (Exception e) + { + log.error("填充集合数据失败", e); + } } else { - this.addCell(excel, row, vo, field, column++); + // 创建单元格并设置值 + addCell(excel, row, vo, field, column); + if (maxSubListSize > 1 && excel.needMerge()) + { + sheet.addMergedRegion(new CellRangeAddress(currentRowNum, currentRowNum + maxSubListSize - 1, column, column)); + } + column++; } } + currentRowNum += maxSubListSize; } } + /** + * 获取子列表最大数 + */ + private int getCurrentMaxSubListSize(T vo) + { + int maxSubListSize = 1; + for (Object[] os : fields) + { + Field field = (Field) os[0]; + if (Collection.class.isAssignableFrom(field.getType())) + { + try + { + Collection subList = (Collection) getTargetValue(vo, field, (Excel) os[1]); + if (subList != null && !subList.isEmpty()) + { + maxSubListSize = Math.max(maxSubListSize, subList.size()); + } + } + catch (Exception e) + { + log.error("获取集合大小失败", e); + } + } + } + return maxSubListSize; + } + /** * 创建表格样式 - * + * * @param wb 工作薄对象 * @return 样式列表 */ @@ -765,6 +792,8 @@ public class ExcelUtil titleFont.setFontHeightInPoints((short) 16); titleFont.setBold(true); style.setFont(titleFont); + DataFormat dataFormat = wb.createDataFormat(); + style.setDataFormat(dataFormat.getFormat("@")); styles.put("title", style); style = wb.createCellStyle(); @@ -802,7 +831,7 @@ public class ExcelUtil /** * 根据Excel注解创建表格头样式 - * + * * @param wb 工作薄对象 * @return 自定义样式列表 */ @@ -827,6 +856,9 @@ public class ExcelUtil headerFont.setBold(true); headerFont.setColor(excel.headerColor().index); style.setFont(headerFont); + // 设置表格头单元格文本形式 + DataFormat dataFormat = wb.createDataFormat(); + style.setDataFormat(dataFormat.getFormat("@")); headerStyles.put(key, style); } } @@ -835,7 +867,7 @@ public class ExcelUtil /** * 根据Excel注解创建表格列样式 - * + * * @param wb 工作薄对象 * @return 自定义样式列表 */ @@ -844,34 +876,67 @@ public class ExcelUtil Map styles = new HashMap(); for (Object[] os : fields) { + Field field = (Field) os[0]; Excel excel = (Excel) os[1]; - String key = StringUtils.format("data_{}_{}_{}", excel.align(), excel.color(), excel.backgroundColor()); - if (!styles.containsKey(key)) + if (Collection.class.isAssignableFrom(field.getType())) { - CellStyle style = wb.createCellStyle(); - style.setAlignment(excel.align()); - style.setVerticalAlignment(VerticalAlignment.CENTER); - style.setBorderRight(BorderStyle.THIN); - style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setBorderLeft(BorderStyle.THIN); - style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setBorderTop(BorderStyle.THIN); - style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setBorderBottom(BorderStyle.THIN); - style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - style.setFillForegroundColor(excel.backgroundColor().getIndex()); - Font dataFont = wb.createFont(); - dataFont.setFontName("Arial"); - dataFont.setFontHeightInPoints((short) 10); - dataFont.setColor(excel.color().index); - style.setFont(dataFont); - styles.put(key, style); + ParameterizedType pt = (ParameterizedType) field.getGenericType(); + Class subClass = (Class) pt.getActualTypeArguments()[0]; + List subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class); + for (Field subField : subFields) + { + Excel subExcel = subField.getAnnotation(Excel.class); + annotationDataStyles(styles, subField, subExcel); + } + } + else + { + annotationDataStyles(styles, field, excel); } } return styles; } + /** + * 根据Excel注解创建表格列样式 + * + * @param styles 自定义样式列表 + * @param field 属性列信息 + * @param excel 注解信息 + */ + public void annotationDataStyles(Map styles, Field field, Excel excel) + { + String key = StringUtils.format("data_{}_{}_{}_{}_{}", excel.align(), excel.color(), excel.backgroundColor(), excel.cellType(), excel.wrapText()); + if (!styles.containsKey(key)) + { + CellStyle style = wb.createCellStyle(); + style.setAlignment(excel.align()); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setBorderRight(BorderStyle.THIN); + style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderLeft(BorderStyle.THIN); + style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderTop(BorderStyle.THIN); + style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + style.setFillForegroundColor(excel.backgroundColor().getIndex()); + style.setWrapText(excel.wrapText()); + Font dataFont = wb.createFont(); + dataFont.setFontName("Arial"); + dataFont.setFontHeightInPoints((short) 10); + dataFont.setColor(excel.color().index); + style.setFont(dataFont); + if (ColumnType.TEXT == excel.cellType()) + { + DataFormat dataFormat = wb.createDataFormat(); + style.setDataFormat(dataFormat.getFormat("@")); + } + styles.put(key, style); + } + } + /** * 创建单元格 */ @@ -886,7 +951,7 @@ public class ExcelUtil if (isSubList()) { // 填充默认样式,防止合并单元格样式失效 - sheet.setDefaultColumnStyle(column, styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor()))); + sheet.setDefaultColumnStyle(column, styles.get(StringUtils.format("data_{}_{}_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor(), attr.cellType(), attr.wrapText()))); if (attr.needMerge()) { sheet.addMergedRegion(new CellRangeAddress(rownum - 1, rownum, column, column)); @@ -897,14 +962,14 @@ public class ExcelUtil /** * 设置单元格信息 - * + * * @param value 单元格值 * @param attr 注解相关 * @param cell 单元格信息 */ public void setCellVo(Object value, Excel attr, Cell cell) { - if (ColumnType.STRING == attr.cellType()) + if (ColumnType.STRING == attr.cellType() || ColumnType.TEXT == attr.cellType()) { String cellValue = Convert.toStr(value); // 对于任何以表达式触发字符 =-+@开头的单元格,直接使用tab字符作为前缀,防止CSV注入。 @@ -981,17 +1046,28 @@ public class ExcelUtil // 设置列宽 sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256)); } - if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0) + if (StringUtils.isNotEmpty(attr.prompt()) || attr.combo().length > 0 || attr.comboReadDict()) { - if (attr.combo().length > 15 || StringUtils.join(attr.combo()).length() > 255) + String[] comboArray = attr.combo(); + if (attr.comboReadDict()) + { + if (!sysDictMap.containsKey("combo_" + attr.dictType())) + { + String labels = DictUtils.getDictLabels(attr.dictType()); + sysDictMap.put("combo_" + attr.dictType(), labels); + } + String val = sysDictMap.get("combo_" + attr.dictType()); + comboArray = StringUtils.split(val, DictUtils.SEPARATOR); + } + if (comboArray.length > 15 || StringUtils.join(comboArray).length() > 255) { // 如果下拉数大于15或字符串长度大于255,则使用一个新sheet存储,避免生成的模板下拉值获取不到 - setXSSFValidationWithHidden(sheet, attr.combo(), attr.prompt(), 1, 100, column, column); + setXSSFValidationWithHidden(sheet, comboArray, attr.prompt(), 1, 100, column, column); } else { // 提示信息或只能选择不能输入的列内容. - setPromptOrValidation(sheet, attr.combo(), attr.prompt(), 1, 100, column, column); + setPromptOrValidation(sheet, comboArray, attr.prompt(), 1, 100, column, column); } } } @@ -1013,10 +1089,12 @@ public class ExcelUtil cell = row.createCell(column); if (isSubListValue(vo) && getListCellValue(vo).size() > 1 && attr.needMerge()) { - CellRangeAddress cellAddress = new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column); - sheet.addMergedRegion(cellAddress); + if (subMergedLastRowNum >= subMergedFirstRowNum) + { + sheet.addMergedRegion(new CellRangeAddress(subMergedFirstRowNum, subMergedLastRowNum, column, column)); + } } - cell.setCellStyle(styles.get(StringUtils.format("data_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor()))); + cell.setCellStyle(styles.get(StringUtils.format("data_{}_{}_{}_{}_{}", attr.align(), attr.color(), attr.backgroundColor(), attr.cellType(), attr.wrapText()))); // 用于读取对象中的属性 Object value = getTargetValue(vo, field, attr); @@ -1026,6 +1104,7 @@ public class ExcelUtil String dictType = attr.dictType(); if (StringUtils.isNotEmpty(dateFormat) && StringUtils.isNotNull(value)) { + cell.getCellStyle().setDataFormat(this.wb.getCreationHelper().createDataFormat().getFormat(dateFormat)); cell.setCellValue(parseDateToStr(dateFormat, value)); } else if (StringUtils.isNotEmpty(readConverterExp) && StringUtils.isNotNull(value)) @@ -1034,7 +1113,12 @@ public class ExcelUtil } else if (StringUtils.isNotEmpty(dictType) && StringUtils.isNotNull(value)) { - cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator)); + if (!sysDictMap.containsKey(dictType + value)) + { + String lable = convertDictByExp(Convert.toStr(value), dictType, separator); + sysDictMap.put(dictType + value, lable); + } + cell.setCellValue(sysDictMap.get(dictType + value)); } else if (value instanceof BigDecimal && -1 != attr.scale()) { @@ -1042,7 +1126,7 @@ public class ExcelUtil } else if (!attr.handler().equals(ExcelHandlerAdapter.class)) { - cell.setCellValue(dataFormatHandlerAdapter(value, attr)); + cell.setCellValue(dataFormatHandlerAdapter(value, attr, cell)); } else { @@ -1061,7 +1145,7 @@ public class ExcelUtil /** * 设置 POI XSSFSheet 单元格提示或选择框 - * + * * @param sheet 表单 * @param textlist 下拉框显示的内容 * @param promptContent 提示内容 @@ -1098,7 +1182,7 @@ public class ExcelUtil /** * 设置某些列的值只能输入预制的数据,显示下拉框(兼容超出一定数量的下拉框). - * + * * @param sheet 要设置的sheet. * @param textlist 下拉框显示的内容 * @param promptContent 提示内容 @@ -1150,7 +1234,7 @@ public class ExcelUtil /** * 解析导出值 0=男,1=女,2=未知 - * + * * @param propertyValue 参数值 * @param converterExp 翻译注解 * @param separator 分隔符 @@ -1187,7 +1271,7 @@ public class ExcelUtil /** * 反向解析值 男=0,女=1,未知=2 - * + * * @param propertyValue 参数值 * @param converterExp 翻译注解 * @param separator 分隔符 @@ -1224,7 +1308,7 @@ public class ExcelUtil /** * 解析字典值 - * + * * @param dictValue 字典值 * @param dictType 字典类型 * @param separator 分隔符 @@ -1237,7 +1321,7 @@ public class ExcelUtil /** * 反向解析值字典值 - * + * * @param dictLabel 字典标签 * @param dictType 字典类型 * @param separator 分隔符 @@ -1250,18 +1334,18 @@ public class ExcelUtil /** * 数据处理器 - * + * * @param value 数据值 * @param excel 数据注解 * @return */ - public String dataFormatHandlerAdapter(Object value, Excel excel) + public String dataFormatHandlerAdapter(Object value, Excel excel, Cell cell) { try { Object instance = excel.handler().newInstance(); - Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class }); - value = formatMethod.invoke(instance, value, excel.args()); + Method formatMethod = excel.handler().getMethod("format", new Class[] { Object.class, String[].class, Cell.class, Workbook.class }); + value = formatMethod.invoke(instance, value, excel.args(), cell, this.wb); } catch (Exception e) { @@ -1321,13 +1405,12 @@ public class ExcelUtil */ public String encodingFilename(String filename) { - filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx"; - return filename; + return UUID.randomUUID() + "_" + filename + ".xlsx"; } /** * 获取下载路径 - * + * * @param filename 文件名称 */ public String getAbsoluteFile(String filename) @@ -1343,7 +1426,7 @@ public class ExcelUtil /** * 获取bean中的属性值 - * + * * @param vo 实体对象 * @param field 字段 * @param excel 注解 @@ -1352,6 +1435,7 @@ public class ExcelUtil */ private Object getTargetValue(T vo, Field field, Excel excel) throws Exception { + field.setAccessible(true); Object o = field.get(vo); if (StringUtils.isNotEmpty(excel.targetAttr())) { @@ -1374,7 +1458,7 @@ public class ExcelUtil /** * 以类的属性的get方法方法形式获取值 - * + * * @param o * @param name * @return value @@ -1411,45 +1495,83 @@ public class ExcelUtil List tempFields = new ArrayList<>(); tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields())); tempFields.addAll(Arrays.asList(clazz.getDeclaredFields())); - for (Field field : tempFields) + if (StringUtils.isNotEmpty(includeFields)) { - if (!ArrayUtils.contains(this.excludeFields, field.getName())) + for (Field field : tempFields) { - // 单注解 - if (field.isAnnotationPresent(Excel.class)) + if (ArrayUtils.contains(this.includeFields, field.getName()) || field.isAnnotationPresent(Excels.class)) { - Excel attr = field.getAnnotation(Excel.class); - if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) + addField(fields, field); + } + } + } + else if (StringUtils.isNotEmpty(excludeFields)) + { + for (Field field : tempFields) + { + if (!ArrayUtils.contains(this.excludeFields, field.getName())) + { + addField(fields, field); + } + } + } + else + { + for (Field field : tempFields) + { + addField(fields, field); + } + } + return fields; + } + + /** + * 添加字段信息 + */ + public void addField(List fields, Field field) + { + // 单注解 + if (field.isAnnotationPresent(Excel.class)) + { + Excel attr = field.getAnnotation(Excel.class); + if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) + { + fields.add(new Object[] { field, attr }); + } + if (Collection.class.isAssignableFrom(field.getType())) + { + subMethod = getSubMethod(field.getName(), clazz); + ParameterizedType pt = (ParameterizedType) field.getGenericType(); + Class subClass = (Class) pt.getActualTypeArguments()[0]; + this.subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class); + } + } + + // 多注解 + if (field.isAnnotationPresent(Excels.class)) + { + Excels attrs = field.getAnnotation(Excels.class); + Excel[] excels = attrs.value(); + for (Excel attr : excels) + { + if (StringUtils.isNotEmpty(includeFields)) + { + if (ArrayUtils.contains(this.includeFields, field.getName() + "." + attr.targetAttr()) + && (attr != null && (attr.type() == Type.ALL || attr.type() == type))) { - field.setAccessible(true); fields.add(new Object[] { field, attr }); } - if (Collection.class.isAssignableFrom(field.getType())) - { - subMethod = getSubMethod(field.getName(), clazz); - ParameterizedType pt = (ParameterizedType) field.getGenericType(); - Class subClass = (Class) pt.getActualTypeArguments()[0]; - this.subFields = FieldUtils.getFieldsListWithAnnotation(subClass, Excel.class); - } } - - // 多注解 - if (field.isAnnotationPresent(Excels.class)) + else { - Excels attrs = field.getAnnotation(Excels.class); - Excel[] excels = attrs.value(); - for (Excel attr : excels) + if (!ArrayUtils.contains(this.excludeFields, field.getName() + "." + attr.targetAttr()) + && (attr != null && (attr.type() == Type.ALL || attr.type() == type))) { - if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) - { - field.setAccessible(true); - fields.add(new Object[] { field, attr }); - } + fields.add(new Object[] { field, attr }); } } } } - return fields; } /** @@ -1479,7 +1601,7 @@ public class ExcelUtil /** * 创建工作表 - * + * * @param sheetNo sheet数量 * @param index 序号 */ @@ -1496,7 +1618,7 @@ public class ExcelUtil /** * 获取单元格值 - * + * * @param row 获取的行 * @param column 获取单元格列号 * @return 单元格值 @@ -1556,7 +1678,7 @@ public class ExcelUtil /** * 判断是否是空行 - * + * * @param row 判断的行 * @return */ @@ -1598,7 +1720,7 @@ public class ExcelUtil HSSFPicture pic = (HSSFPicture) shape; int pictureIndex = pic.getPictureIndex() - 1; HSSFPictureData picData = pictures.get(pictureIndex); - String picIndex = String.valueOf(anchor.getRow1()) + "_" + String.valueOf(anchor.getCol1()); + String picIndex = anchor.getRow1() + "_" + anchor.getCol1(); sheetIndexPicMap.put(picIndex, picData); } } @@ -1644,7 +1766,7 @@ public class ExcelUtil /** * 格式化不同类型的日期对象 - * + * * @param dateFormat 日期格式 * @param val 被格式化的日期对象 * @return 格式化后的日期字符 @@ -1710,7 +1832,7 @@ public class ExcelUtil /** * 获取对象的子列表方法 - * + * * @param name 名称 * @param pojoClass 类对象 * @return 子列表方法 diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/sql/SqlUtil.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/sql/SqlUtil.java index ddf3bc52..9f056814 100644 --- a/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/sql/SqlUtil.java +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/utils/sql/SqlUtil.java @@ -5,7 +5,7 @@ import com.fastbee.common.utils.StringUtils; /** * sql操作工具类 - * + * * @author ruoyi */ public class SqlUtil @@ -13,13 +13,18 @@ public class SqlUtil /** * 定义常用的 sql关键字 */ - public static String SQL_REGEX = "and |extractvalue|updatexml|exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |or |+|user()"; + public static String SQL_REGEX = "\u000B|and |extractvalue|updatexml|sleep|exec |insert |select |delete |update |drop |count |chr |mid |master |truncate |char |declare |or |union |like |+|/*|user()"; /** * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序) */ public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+"; + /** + * 限制orderBy最大长度 + */ + private static final int ORDER_BY_MAX_LENGTH = 500; + /** * 检查字符,防止注入绕过 */ @@ -29,6 +34,10 @@ public class SqlUtil { throw new UtilException("参数不符合规范,不能进行查询"); } + if (StringUtils.length(value) > ORDER_BY_MAX_LENGTH) + { + throw new UtilException("参数已超过最大限制,不能进行查询"); + } return value; } diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/LogAspect.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/LogAspect.java index bd03f3f7..6611f04f 100644 --- a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/LogAspect.java +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/aspectj/LogAspect.java @@ -1,24 +1,14 @@ package com.fastbee.framework.aspectj; -import java.util.Collection; -import java.util.Map; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import org.aspectj.lang.JoinPoint; -import org.aspectj.lang.annotation.AfterReturning; -import org.aspectj.lang.annotation.AfterThrowing; -import org.aspectj.lang.annotation.Aspect; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.stereotype.Component; -import org.springframework.validation.BindingResult; -import org.springframework.web.multipart.MultipartFile; import com.alibaba.fastjson2.JSON; import com.fastbee.common.annotation.Log; +import com.fastbee.common.core.domain.entity.SysUser; import com.fastbee.common.core.domain.model.LoginUser; +import com.fastbee.common.core.text.Convert; import com.fastbee.common.enums.BusinessStatus; import com.fastbee.common.enums.HttpMethod; import com.fastbee.common.filter.PropertyPreExcludeFilter; +import com.fastbee.common.utils.ExceptionUtil; import com.fastbee.common.utils.SecurityUtils; import com.fastbee.common.utils.ServletUtils; import com.fastbee.common.utils.StringUtils; @@ -26,10 +16,27 @@ import com.fastbee.common.utils.ip.IpUtils; import com.fastbee.framework.manager.AsyncManager; import com.fastbee.framework.manager.factory.AsyncFactory; import com.fastbee.system.domain.SysOperLog; +import org.apache.commons.lang3.ArrayUtils; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.annotation.AfterReturning; +import org.aspectj.lang.annotation.AfterThrowing; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Before; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.NamedThreadLocal; +import org.springframework.stereotype.Component; +import org.springframework.validation.BindingResult; +import org.springframework.web.multipart.MultipartFile; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.Collection; +import java.util.Map; /** * 操作日志记录处理 - * + * * @author ruoyi */ @Aspect @@ -41,6 +48,18 @@ public class LogAspect /** 排除敏感属性字段 */ public static final String[] EXCLUDE_PROPERTIES = { "password", "oldPassword", "newPassword", "confirmPassword" }; + /** 计算操作消耗时间 */ + private static final ThreadLocal TIME_THREADLOCAL = new NamedThreadLocal("Cost Time"); + + /** + * 处理请求前执行 + */ + @Before(value = "@annotation(controllerLog)") + public void doBefore(JoinPoint joinPoint, Log controllerLog) + { + TIME_THREADLOCAL.set(System.currentTimeMillis()); + } + /** * 处理完请求后执行 * @@ -54,7 +73,7 @@ public class LogAspect /** * 拦截异常操作 - * + * * @param joinPoint 切点 * @param e 异常 */ @@ -75,18 +94,23 @@ public class LogAspect SysOperLog operLog = new SysOperLog(); operLog.setStatus(BusinessStatus.SUCCESS.ordinal()); // 请求的地址 - String ip = IpUtils.getIpAddr(ServletUtils.getRequest()); + String ip = IpUtils.getIpAddr(); operLog.setOperIp(ip); operLog.setOperUrl(StringUtils.substring(ServletUtils.getRequest().getRequestURI(), 0, 255)); if (loginUser != null) { operLog.setOperName(loginUser.getUsername()); + SysUser currentUser = loginUser.getUser(); + if (StringUtils.isNotNull(currentUser) && StringUtils.isNotNull(currentUser.getDept())) + { + operLog.setDeptName(currentUser.getDept().getDeptName()); + } } if (e != null) { operLog.setStatus(BusinessStatus.FAIL.ordinal()); - operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); + operLog.setErrorMsg(StringUtils.substring(Convert.toStr(e.getMessage(), ExceptionUtil.getExceptionMessage(e)), 0, 2000)); } // 设置方法名称 String className = joinPoint.getTarget().getClass().getName(); @@ -96,6 +120,8 @@ public class LogAspect operLog.setRequestMethod(ServletUtils.getRequest().getMethod()); // 处理设置注解上的参数 getControllerMethodDescription(joinPoint, controllerLog, operLog, jsonResult); + // 设置消耗时间 + operLog.setCostTime(System.currentTimeMillis() - TIME_THREADLOCAL.get()); // 保存数据库 AsyncManager.me().execute(AsyncFactory.recordOper(operLog)); } @@ -105,11 +131,15 @@ public class LogAspect log.error("异常信息:{}", exp.getMessage()); exp.printStackTrace(); } + finally + { + TIME_THREADLOCAL.remove(); + } } /** * 获取注解中对方法的描述信息 用于Controller层注解 - * + * * @param log 日志 * @param operLog 操作日志 * @throws Exception @@ -126,7 +156,7 @@ public class LogAspect if (log.isSaveRequestData()) { // 获取参数的信息,传入到数据库中。 - setRequestValue(joinPoint, operLog); + setRequestValue(joinPoint, operLog, log.excludeParamNames()); } // 是否需要保存response,参数和值 if (log.isSaveResponseData() && StringUtils.isNotNull(jsonResult)) @@ -137,29 +167,29 @@ public class LogAspect /** * 获取请求的参数,放到log中 - * + * * @param operLog 操作日志 * @throws Exception 异常 */ - private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog) throws Exception + private void setRequestValue(JoinPoint joinPoint, SysOperLog operLog, String[] excludeParamNames) throws Exception { + Map paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest()); String requestMethod = operLog.getRequestMethod(); - if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) + if (StringUtils.isEmpty(paramsMap) && StringUtils.equalsAny(requestMethod, HttpMethod.PUT.name(), HttpMethod.POST.name(), HttpMethod.DELETE.name())) { - String params = argsArrayToString(joinPoint.getArgs()); + String params = argsArrayToString(joinPoint.getArgs(), excludeParamNames); operLog.setOperParam(StringUtils.substring(params, 0, 2000)); } else { - Map paramsMap = ServletUtils.getParamMap(ServletUtils.getRequest()); - operLog.setOperParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter()), 0, 2000)); + operLog.setOperParam(StringUtils.substring(JSON.toJSONString(paramsMap, excludePropertyPreFilter(excludeParamNames)), 0, 2000)); } } /** * 参数拼装 */ - private String argsArrayToString(Object[] paramsArray) + private String argsArrayToString(Object[] paramsArray, String[] excludeParamNames) { String params = ""; if (paramsArray != null && paramsArray.length > 0) @@ -170,7 +200,7 @@ public class LogAspect { try { - String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter()); + String jsonObj = JSON.toJSONString(o, excludePropertyPreFilter(excludeParamNames)); params += jsonObj.toString() + " "; } catch (Exception e) @@ -185,14 +215,14 @@ public class LogAspect /** * 忽略敏感属性 */ - public PropertyPreExcludeFilter excludePropertyPreFilter() + public PropertyPreExcludeFilter excludePropertyPreFilter(String[] excludeParamNames) { - return new PropertyPreExcludeFilter().addExcludes(EXCLUDE_PROPERTIES); + return new PropertyPreExcludeFilter().addExcludes(ArrayUtils.addAll(EXCLUDE_PROPERTIES, excludeParamNames)); } /** * 判断是否需要过滤的对象。 - * + * * @param o 对象信息。 * @return 如果是需要过滤的对象,则返回true;否则返回false。 */ diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/DruidConfig.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/DruidConfig.java index 6614ed63..d5ffc7d0 100644 --- a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/DruidConfig.java +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/DruidConfig.java @@ -1,20 +1,5 @@ package com.fastbee.framework.config; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.sql.DataSource; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Primary; import com.alibaba.druid.pool.DruidDataSource; import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder; import com.alibaba.druid.spring.boot.autoconfigure.properties.DruidStatProperties; @@ -23,10 +8,22 @@ import com.fastbee.common.enums.DataSourceType; import com.fastbee.common.utils.spring.SpringUtils; import com.fastbee.framework.config.properties.DruidProperties; import com.fastbee.framework.datasource.DynamicDataSource; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; + +import javax.servlet.*; +import javax.sql.DataSource; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; /** * druid 配置多数据源 - * + * * @author ruoyi */ @Configuration @@ -58,10 +55,10 @@ public class DruidConfig setDataSource(targetDataSources, DataSourceType.SLAVE.name(), "slaveDataSource"); return new DynamicDataSource(masterDataSource, targetDataSources); } - + /** * 设置数据源 - * + * * @param targetDataSources 备选数据源集合 * @param sourceName 数据源名称 * @param beanName bean名称 diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/FastJson2JsonRedisSerializer.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/FastJson2JsonRedisSerializer.java index 43f1889d..401fccdc 100644 --- a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/FastJson2JsonRedisSerializer.java +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/FastJson2JsonRedisSerializer.java @@ -1,21 +1,26 @@ package com.fastbee.framework.config; -import java.nio.charset.Charset; -import org.springframework.data.redis.serializer.RedisSerializer; -import org.springframework.data.redis.serializer.SerializationException; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONWriter; +import com.alibaba.fastjson2.filter.Filter; +import com.fastbee.common.constant.Constants; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.SerializationException; + +import java.nio.charset.Charset; /** * Redis使用FastJson序列化 - * + * * @author ruoyi */ public class FastJson2JsonRedisSerializer implements RedisSerializer { public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8"); + static final Filter AUTO_TYPE_FILTER = JSONReader.autoTypeFilter(Constants.JSON_WHITELIST_STR); + private Class clazz; public FastJson2JsonRedisSerializer(Class clazz) @@ -43,6 +48,6 @@ public class FastJson2JsonRedisSerializer implements RedisSerializer } String str = new String(bytes, DEFAULT_CHARSET); - return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType); + return JSON.parseObject(str, clazz, AUTO_TYPE_FILTER); } } diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/FilterConfig.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/FilterConfig.java index 8e0e76ef..37c890a4 100644 --- a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/FilterConfig.java +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/FilterConfig.java @@ -1,16 +1,17 @@ package com.fastbee.framework.config; -import java.util.HashMap; -import java.util.Map; -import javax.servlet.DispatcherType; +import com.fastbee.common.filter.RepeatableFilter; +import com.fastbee.common.filter.XssFilter; +import com.fastbee.common.utils.StringUtils; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.fastbee.common.filter.RepeatableFilter; -import com.fastbee.common.filter.XssFilter; -import com.fastbee.common.utils.StringUtils; + +import javax.servlet.DispatcherType; +import java.util.HashMap; +import java.util.Map; /** * Filter配置 diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/SecurityConfig.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/SecurityConfig.java index 8281994c..74f4a9a0 100644 --- a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/SecurityConfig.java +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/SecurityConfig.java @@ -1,32 +1,35 @@ package com.fastbee.framework.config; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.http.HttpMethod; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; -import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; -import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; -import org.springframework.security.config.http.SessionCreationPolicy; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; -import org.springframework.security.web.authentication.logout.LogoutFilter; -import org.springframework.web.filter.CorsFilter; import com.fastbee.framework.config.properties.PermitAllUrlProperties; import com.fastbee.framework.security.filter.JwtAuthenticationTokenFilter; import com.fastbee.framework.security.handle.AuthenticationEntryPointImpl; import com.fastbee.framework.security.handle.LogoutSuccessHandlerImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Primary; +import org.springframework.http.HttpMethod; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.ProviderManager; +import org.springframework.security.authentication.dao.DaoAuthenticationProvider; +import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; +import org.springframework.security.config.annotation.web.builders.HttpSecurity; +import org.springframework.security.config.http.SessionCreationPolicy; +import org.springframework.security.core.userdetails.UserDetailsService; +import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; +import org.springframework.security.web.SecurityFilterChain; +import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; +import org.springframework.security.web.authentication.logout.LogoutFilter; +import org.springframework.web.filter.CorsFilter; /** * spring security配置 * * @author ruoyi */ -@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) -public class SecurityConfig extends WebSecurityConfigurerAdapter +@EnableMethodSecurity(prePostEnabled = true, securedEnabled = true) +@Configuration +public class SecurityConfig { /** * 自定义用户认证逻辑 @@ -65,16 +68,15 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter private PermitAllUrlProperties permitAllUrl; /** - * 解决 无法直接注入 AuthenticationManager - * - * @return - * @throws Exception + * 身份验证实现 */ @Bean - @Override - public AuthenticationManager authenticationManagerBean() throws Exception + public AuthenticationManager authenticationManager() { - return super.authenticationManagerBean(); + DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider(); + daoAuthenticationProvider.setUserDetailsService(userDetailsService); + daoAuthenticationProvider.setPasswordEncoder(bCryptPasswordEncoder()); + return new ProviderManager(daoAuthenticationProvider); } /** @@ -92,44 +94,45 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter * rememberMe | 允许通过remember-me登录的用户访问 * authenticated | 用户登录后可访问 */ - @Override - protected void configure(HttpSecurity httpSecurity) throws Exception + @Bean + @Primary + protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { - // 注解标记允许匿名访问的url - ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry registry = httpSecurity.authorizeRequests(); - permitAllUrl.getUrls().forEach(url -> registry.antMatchers(url).permitAll()); - - httpSecurity - // CSRF禁用,因为不使用session - .csrf().disable() - // 禁用HTTP响应标头 - .headers().cacheControl().disable().and() - // 认证失败处理类 - .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() - // 基于token,所以不需要session - .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() - // 过滤请求 - .authorizeRequests() + return httpSecurity + // CSRF禁用,因为不使用session + .csrf(csrf -> csrf.disable()) + // 禁用HTTP响应标头 + .headers((headersCustomizer) -> { + headersCustomizer.cacheControl(cache -> cache.disable()).frameOptions(options -> options.sameOrigin()); + }) + // 认证失败处理类 + .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler)) + // 基于token,所以不需要session + .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) + // 注解标记允许匿名访问的url + .authorizeHttpRequests((requests) -> { + permitAllUrl.getUrls().forEach(url -> requests.antMatchers(url).permitAll()); // 对于登录login 注册register 验证码captchaImage 允许匿名访问 - .antMatchers("/login", "/register", "/captchaImage","/iot/tool/register","/iot/tool/ntp","/iot/tool/download", - "/iot/tool/mqtt/auth","/iot/tool/mqtt/authv5","/iot/tool/mqtt/webhook","/iot/tool/mqtt/webhookv5","/auth/**/**", - "/wechat/mobileLogin", "/wechat/miniLogin", "/wechat/wxBind/callback").permitAll() - .antMatchers("/zlmhook/**").permitAll() - .antMatchers("/goview/sys/login","/goview/project/getData").permitAll() // 静态资源,可匿名访问 - .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll() - .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll() - // 除上面外的所有请求全部需要鉴权认证 - .anyRequest().authenticated() - .and() - .headers().frameOptions().disable(); - // 添加Logout filter - httpSecurity.logout().logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler); - // 添加JWT filter - httpSecurity.addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); - // 添加CORS filter - httpSecurity.addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class); - httpSecurity.addFilterBefore(corsFilter, LogoutFilter.class); + requests.antMatchers("/login", "/register", "/captchaImage","/iot/tool/register","/iot/tool/ntp","/iot/tool/download", + "/iot/tool/mqtt/auth","/iot/tool/mqtt/authv5","/iot/tool/mqtt/webhook","/iot/tool/mqtt/webhookv5","/auth/**/**", + "/wechat/mobileLogin", "/wechat/miniLogin", "/wechat/wxBind/callback").permitAll() + .antMatchers("/zlmhook/**").permitAll() + .antMatchers("/goview/sys/login","/goview/project/getData").permitAll() + // 静态资源,可匿名访问 + .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll() + .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/*/api-docs", "/druid/**").permitAll() + // 除上面外的所有请求全部需要鉴权认证 + .anyRequest().authenticated(); + }) + // 添加Logout filter + .logout(logout -> logout.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler)) + // 添加JWT filter + .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class) + // 添加CORS filter + .addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class) + .addFilterBefore(corsFilter, LogoutFilter.class) + .build(); } /** @@ -140,13 +143,4 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter { return new BCryptPasswordEncoder(); } - - /** - * 身份认证接口 - */ - @Override - protected void configure(AuthenticationManagerBuilder auth) throws Exception - { - auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); - } } diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/ServerConfig.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/ServerConfig.java index a07d6e0a..993af48a 100644 --- a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/ServerConfig.java +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/ServerConfig.java @@ -1,12 +1,13 @@ package com.fastbee.framework.config; -import javax.servlet.http.HttpServletRequest; -import org.springframework.stereotype.Component; import com.fastbee.common.utils.ServletUtils; +import org.springframework.stereotype.Component; + +import javax.servlet.http.HttpServletRequest; /** * 服务相关配置 - * + * * @author ruoyi */ @Component @@ -14,7 +15,7 @@ public class ServerConfig { /** * 获取完整的请求路径,包括:域名,端口,上下文访问路径 - * + * * @return 服务地址 */ public String getUrl() diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysRegisterService.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysRegisterService.java index dcf3255b..61b9cf12 100644 --- a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysRegisterService.java +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/web/service/SysRegisterService.java @@ -1,7 +1,5 @@ package com.fastbee.framework.web.service; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; import com.fastbee.common.constant.CacheConstants; import com.fastbee.common.constant.Constants; import com.fastbee.common.constant.UserConstants; @@ -17,10 +15,12 @@ import com.fastbee.framework.manager.AsyncManager; import com.fastbee.framework.manager.factory.AsyncFactory; import com.fastbee.system.service.ISysConfigService; import com.fastbee.system.service.ISysUserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; /** * 注册校验方法 - * + * * @author ruoyi */ @Component @@ -69,7 +69,7 @@ public class SysRegisterService { msg = "密码长度必须在5到20个字符之间"; } - else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser))) + else if (!userService.checkUserNameUnique(sysUser)) { msg = "保存用户'" + username + "'失败,注册账号已存在"; } @@ -92,7 +92,7 @@ public class SysRegisterService /** * 校验验证码 - * + * * @param username 用户名 * @param code 验证码 * @param uuid 唯一标识 diff --git a/springboot/fastbee-service/fastbee-iot-service/pom.xml b/springboot/fastbee-service/fastbee-iot-service/pom.xml index 1e29cb9a..1f534278 100644 --- a/springboot/fastbee-service/fastbee-iot-service/pom.xml +++ b/springboot/fastbee-service/fastbee-iot-service/pom.xml @@ -46,12 +46,7 @@ org.apache.commons commons-text - - - org.springframework.security.oauth - spring-security-oauth2 - 2.5.1.RELEASE - + org.springframework.boot spring-boot-starter-thymeleaf diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/AuthorizationServerConfig.java b/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/AuthorizationServerConfig.java deleted file mode 100644 index e001f335..00000000 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/AuthorizationServerConfig.java +++ /dev/null @@ -1,119 +0,0 @@ -package com.fastbee.iot.oauth; - - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.core.userdetails.UserDetailsService; -import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; -import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer; -import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.OAuth2RequestFactory; -import org.springframework.security.oauth2.provider.approval.ApprovalStore; -import org.springframework.security.oauth2.provider.approval.JdbcApprovalStore; -import org.springframework.security.oauth2.provider.approval.UserApprovalHandler; -import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; -import org.springframework.security.oauth2.provider.code.JdbcAuthorizationCodeServices; -import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint; -import org.springframework.security.oauth2.provider.request.DefaultOAuth2RequestFactory; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; - -import javax.sql.DataSource; - -/** - * 授权服务器配置,配置客户端id,密钥和令牌的过期时间 - */ -@Configuration -@EnableAuthorizationServer -public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { - @Autowired - private DataSource dataSource; - - @Autowired - private AuthenticationManager authenticationManager; - - @Autowired - private UserDetailsService userDetailsService; - - /** - * 用来配置令牌端点(Token Endpoint)的安全约束 - * @param security - * @throws Exception - */ - @Override - public void configure(AuthorizationServerSecurityConfigurer security) throws Exception { - security.allowFormAuthenticationForClients() - .authenticationEntryPoint(new OAuth2AuthenticationEntryPoint()); - } - - /** - * 用来配置客户端详情服务 - * @param clients - * @throws Exception - */ - @Override - public void configure(ClientDetailsServiceConfigurer clients) throws Exception { - - clients.withClientDetails(getClientDetailsService()); - } - - /** - * 用来配置授权(authorization)以及令牌(token)的访问端点和令牌服务(token services)。 - * @param endpoints - * @throws Exception - */ - @Override - public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { - // 查询用户、授权、分组,可以被重写 - endpoints.userDetailsService(userDetailsService) - // 审批客户端的授权 - .userApprovalHandler(userApprovalHandler()) - // 授权审批 - .approvalStore(approvalStore()) - // 获取授权码 - .authorizationCodeServices(new JdbcAuthorizationCodeServices(dataSource)) - // 验证token - .authenticationManager(authenticationManager) - // 查询、保存、刷新token - .tokenStore(this.getJdbcTokenStore()); - } - - @Bean - public ApprovalStore approvalStore() { - return new JdbcApprovalStore(dataSource); - } - - @Bean - public UserApprovalHandler userApprovalHandler() { - return new SpeakerApprovalHandler(getClientDetailsService(), approvalStore(), oAuth2RequestFactory()); - } - - @Bean - public JdbcClientDetailsService getClientDetailsService() { - JdbcClientDetailsService jdbcClientDetailsService = new JdbcClientDetailsService(dataSource); - jdbcClientDetailsService.setPasswordEncoder(passwordEncoder()); - return jdbcClientDetailsService; - } - - @Bean - public OAuth2RequestFactory oAuth2RequestFactory() { - return new DefaultOAuth2RequestFactory(getClientDetailsService()); - } - @Bean - public TokenStore getJdbcTokenStore(){ - TokenStore tokenStore = new JdbcTokenStore(dataSource); - return tokenStore; - } - - - - public BCryptPasswordEncoder passwordEncoder(){ - return new BCryptPasswordEncoder(); - } - -} diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/ResourceServerConfig.java b/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/ResourceServerConfig.java deleted file mode 100644 index bb4429d5..00000000 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/ResourceServerConfig.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.fastbee.iot.oauth; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.annotation.Order; -import org.springframework.security.config.annotation.web.builders.HttpSecurity; -import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; -import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter; -import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer; -import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationManager; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore; - -import javax.sql.DataSource; - -@Configuration -@EnableResourceServer -public class ResourceServerConfig extends ResourceServerConfigurerAdapter { - - @Autowired - private DataSource dataSource; - - @Override - public void configure(ResourceServerSecurityConfigurer resources) throws Exception { - TokenStore tokenStore = jdbcTokenStore(); - OAuth2AuthenticationManager auth2AuthenticationManager= new OAuth2AuthenticationManager(); - resources.authenticationManager(auth2AuthenticationManager); - resources.resourceId("speaker-service").tokenStore(tokenStore).stateless(true); - } - - @Override - public void configure(HttpSecurity http) throws Exception { - // 限制资源服务器只接管匹配的资源 - http.requestMatchers().antMatchers("/oauth/speaker/**") - .and() - //授权的请求 - .authorizeRequests() - .anyRequest().authenticated() - //关闭跨站请求防护 - .and() - .csrf().disable(); - } - - public TokenStore jdbcTokenStore(){ - TokenStore tokenStore = new JdbcTokenStore(dataSource); - return tokenStore; - } - -} \ No newline at end of file diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/SpeakerApprovalHandler.java b/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/SpeakerApprovalHandler.java deleted file mode 100644 index 61fafb57..00000000 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/SpeakerApprovalHandler.java +++ /dev/null @@ -1,83 +0,0 @@ -package com.fastbee.iot.oauth; - - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.core.Authentication; -import org.springframework.security.oauth2.common.util.OAuth2Utils; -import org.springframework.security.oauth2.provider.AuthorizationRequest; -import org.springframework.security.oauth2.provider.OAuth2RequestFactory; -import org.springframework.security.oauth2.provider.approval.Approval; -import org.springframework.security.oauth2.provider.approval.ApprovalStore; -import org.springframework.security.oauth2.provider.approval.ApprovalStoreUserApprovalHandler; -import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; - -import java.util.*; - -/** - * kerwincui - */ -public class SpeakerApprovalHandler extends ApprovalStoreUserApprovalHandler { - - private int approvalExpirySeconds = -1; - - @Autowired - private ApprovalStore approvalStore; - - public SpeakerApprovalHandler(JdbcClientDetailsService clientDetailsService, ApprovalStore approvalStore, OAuth2RequestFactory oAuth2RequestFactory) { - this.setApprovalStore(approvalStore); - this.setClientDetailsService(clientDetailsService); - this.setRequestFactory(oAuth2RequestFactory); - } - - @Override - public AuthorizationRequest updateAfterApproval(AuthorizationRequest authorizationRequest, Authentication userAuthentication) { - // 获取授权过的范围 - Set requestedScopes = authorizationRequest.getScope(); - Set approvedScopes = new HashSet(); - Set approvals = new HashSet(); - Date expiry = computeExpiry(); - - // 存储授权或拒绝的范围 - Map approvalParameters = authorizationRequest.getApprovalParameters(); - for (String requestedScope : requestedScopes) { - String approvalParameter = OAuth2Utils.SCOPE_PREFIX + requestedScope; - String value = approvalParameters.get(approvalParameter); - value = value == null ? "" : value.toLowerCase(); - if ("true".equals(value) || value.startsWith("approve")||value.equals("on")) { - approvedScopes.add(requestedScope); - approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), - requestedScope, expiry, Approval.ApprovalStatus.APPROVED)); - } - else { - approvals.add(new Approval(userAuthentication.getName(), authorizationRequest.getClientId(), - requestedScope, expiry, Approval.ApprovalStatus.DENIED)); - } - } - approvalStore.addApprovals(approvals); - - boolean approved; - authorizationRequest.setScope(approvedScopes); - if (approvedScopes.isEmpty() && !requestedScopes.isEmpty()) { - approved = false; - } - else { - approved = true; - } - authorizationRequest.setApproved(approved); - return authorizationRequest; - } - - private Date computeExpiry() { - Calendar expiresAt = Calendar.getInstance(); - // 默认一个月 - if (approvalExpirySeconds == -1) { - expiresAt.add(Calendar.MONTH, 1); - } - else { - expiresAt.add(Calendar.SECOND, approvalExpirySeconds); - } - return expiresAt.getTime(); - } - -} - diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/ConfirmAccessController.java b/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/ConfirmAccessController.java deleted file mode 100644 index ea3d94fd..00000000 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/ConfirmAccessController.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.fastbee.iot.oauth.api; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.oauth2.common.util.OAuth2Utils; -import org.springframework.security.oauth2.provider.AuthorizationRequest; -import org.springframework.security.oauth2.provider.ClientDetails; -import org.springframework.security.oauth2.provider.approval.Approval; -import org.springframework.security.oauth2.provider.approval.ApprovalStore; -import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.SessionAttributes; - -import java.security.Principal; -import java.util.LinkedHashMap; -import java.util.Map; - -/** - * kerwincui - */ -@Controller -@SessionAttributes("authorizationRequest") -public class ConfirmAccessController { - @Autowired - private JdbcClientDetailsService clientDetailsService; - @Autowired - private ApprovalStore approvalStore; - - @RequestMapping("/oauth/confirm_access") - public String getAccessConfirmation(Map model, Principal principal ) { - AuthorizationRequest clientAuth = (AuthorizationRequest) model.remove("authorizationRequest"); - ClientDetails client = clientDetailsService.loadClientByClientId(clientAuth.getClientId()); - - Map scopes = new LinkedHashMap(); - for (String scope : clientAuth.getScope()) { - scopes.put(OAuth2Utils.SCOPE_PREFIX + scope, "false"); - } - for (Approval approval : approvalStore.getApprovals(principal.getName(), client.getClientId())) { - if (clientAuth.getScope().contains(approval.getScope())) { - scopes.put(OAuth2Utils.SCOPE_PREFIX + approval.getScope(), - approval.getStatus() == Approval.ApprovalStatus.APPROVED ? "true" : "false"); - } - } - model.put("auth_request", clientAuth); - model.put("client", client); - model.put("scopes", scopes); - return "oauth/access_confirmation"; - } -} diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/LoginController.java b/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/LoginController.java deleted file mode 100644 index d8dfe0b7..00000000 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/LoginController.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.fastbee.iot.oauth.api; - -import com.fastbee.common.core.domain.AjaxResult; -import com.fastbee.common.core.domain.model.LoginBody; -import com.fastbee.common.utils.SecurityUtils; -import com.fastbee.framework.web.service.SysLoginService; -import com.fastbee.framework.web.service.TokenService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.oauth2.common.OAuth2AccessToken; -import org.springframework.security.oauth2.provider.token.TokenStore; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.*; - -import javax.servlet.http.HttpServletRequest; -import java.util.HashMap; -import java.util.Map; - -@Controller -public class LoginController { - - - @Autowired - private TokenStore tokenStore; - - @Autowired - private SysLoginService loginService; - - @Autowired - private TokenService tokenService; - - @RequestMapping("/oauth/login") - public String login() { - return "oauth/login"; - } - - @RequestMapping("/oauth/index") - public String index() { - return "oauth/index"; - } - - @GetMapping("/oauth/logout") - @ResponseBody - public String logout(@RequestHeader String Authorization) { - if (!Authorization.isEmpty()){ - String token=Authorization.split(" ")[1]; - OAuth2AccessToken auth2AccessToken = tokenStore.readAccessToken(token); - tokenStore.removeAccessToken(auth2AccessToken); - return "SUCCESS"; - }else{ - return "FAIL"; - } - - } - -} \ No newline at end of file diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/SpeakerController.java b/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/SpeakerController.java deleted file mode 100644 index f1f1dc70..00000000 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/oauth/api/SpeakerController.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.fastbee.iot.oauth.api; - -import com.alibaba.fastjson2.JSONObject; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * kerwincui - */ -@RestController -public class SpeakerController { - @GetMapping("/oauth/speaker/get") - public JSONObject getSpeaker() { -// Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - JSONObject Json = new JSONObject(); - Json.put("1", "1"); - Json.put("2", "2"); - Json.put("3", "3"); - System.out.println("调用了接口get"); - return Json; - } - @PostMapping("/oauth/speaker/post") - public JSONObject postSpeaker() { -// Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - JSONObject bookJson = new JSONObject(); - bookJson.put("1", "1"); - System.out.println("调用了接口post"); - return bookJson; - } -} diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/service/impl/ToolServiceImpl.java b/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/service/impl/ToolServiceImpl.java index a505573b..c384e3b5 100644 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/service/impl/ToolServiceImpl.java +++ b/springboot/fastbee-service/fastbee-iot-service/src/main/java/com/fastbee/iot/service/impl/ToolServiceImpl.java @@ -144,10 +144,10 @@ public class ToolServiceImpl implements IToolService { msg = "密码长度必须在5到20个字符之间"; } - else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser))) + else if (userService.checkUserNameUnique(sysUser)) { msg = "保存用户'" + username + "'失败,注册账号已存在"; - }else if (UserConstants.NOT_UNIQUE.equals(checkPhoneUnique(phonenumber))) + }else if (checkPhoneUnique(phonenumber)) { msg = "保存用户'" + username + "'失败,注册手机号码已存在"; } @@ -203,10 +203,10 @@ public class ToolServiceImpl implements IToolService { msg = "密码长度必须在5到20个字符之间"; } - else if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(sysUser))) + else if (userService.checkUserNameUnique(sysUser)) { msg = "保存用户'" + username + "'失败,注册账号已存在"; - }else if (UserConstants.NOT_UNIQUE.equals(checkPhoneUnique(phonenumber))) + }else if (checkPhoneUnique(phonenumber)) { msg = "保存用户'" + username + "'失败,注册手机号码已存在"; } @@ -252,7 +252,7 @@ public class ToolServiceImpl implements IToolService * @param phonenumber 手机号码 * @return */ - public String checkPhoneUnique(String phonenumber) + public boolean checkPhoneUnique(String phonenumber) { SysUser info = userMapper.checkPhoneUnique(phonenumber); if (StringUtils.isNotNull(info)) diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/domain/SysOperLog.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/domain/SysOperLog.java index f1abc898..bf20342e 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/domain/SysOperLog.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/domain/SysOperLog.java @@ -1,19 +1,18 @@ package com.fastbee.system.domain; -import java.util.Date; import com.fasterxml.jackson.annotation.JsonFormat; import com.fastbee.common.annotation.Excel; import com.fastbee.common.annotation.Excel.ColumnType; import com.fastbee.common.core.domain.BaseEntity; -import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Date; + /** * 操作日志记录表 oper_log - * + * * @author ruoyi */ -@ApiModel(value = "SysOperLog", description = "操作日志记录表 oper_log") public class SysOperLog extends BaseEntity { private static final long serialVersionUID = 1L; @@ -103,6 +102,10 @@ public class SysOperLog extends BaseEntity @Excel(name = "操作时间", width = 30, dateFormat = "yyyy-MM-dd HH:mm:ss") private Date operTime; + /** 消耗时间 */ + @Excel(name = "消耗时间", suffix = "毫秒") + private Long costTime; + public Long getOperId() { return operId; @@ -272,4 +275,14 @@ public class SysOperLog extends BaseEntity { this.operTime = operTime; } + + public Long getCostTime() + { + return costTime; + } + + public void setCostTime(Long costTime) + { + this.costTime = costTime; + } } diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/mapper/SysOperLogMapper.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/mapper/SysOperLogMapper.java index 8d3f219f..c788e1ab 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/mapper/SysOperLogMapper.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/mapper/SysOperLogMapper.java @@ -5,21 +5,21 @@ import com.fastbee.system.domain.SysOperLog; /** * 操作日志 数据层 - * + * * @author ruoyi */ public interface SysOperLogMapper { /** * 新增操作日志 - * + * * @param operLog 操作日志对象 */ public void insertOperlog(SysOperLog operLog); /** * 查询系统操作日志集合 - * + * * @param operLog 操作日志对象 * @return 操作日志集合 */ @@ -27,7 +27,7 @@ public interface SysOperLogMapper /** * 批量删除系统操作日志 - * + * * @param operIds 需要删除的操作日志ID * @return 结果 */ @@ -35,7 +35,7 @@ public interface SysOperLogMapper /** * 查询操作日志详细 - * + * * @param operId 操作ID * @return 操作日志对象 */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/mapper/SysRoleMapper.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/mapper/SysRoleMapper.java index 58dc920e..79c2c397 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/mapper/SysRoleMapper.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/mapper/SysRoleMapper.java @@ -1,18 +1,19 @@ package com.fastbee.system.mapper; -import java.util.List; import com.fastbee.common.core.domain.entity.SysRole; +import java.util.List; + /** * 角色表 数据层 - * + * * @author ruoyi */ public interface SysRoleMapper { /** * 根据条件分页查询角色数据 - * + * * @param role 角色信息 * @return 角色数据集合信息 */ @@ -20,7 +21,7 @@ public interface SysRoleMapper /** * 根据用户ID查询角色 - * + * * @param userId 用户ID * @return 角色列表 */ @@ -28,14 +29,14 @@ public interface SysRoleMapper /** * 查询所有角色 - * + * * @return 角色列表 */ public List selectRoleAll(); /** * 根据用户ID获取角色选择框列表 - * + * * @param userId 用户ID * @return 选中角色ID列表 */ @@ -43,7 +44,7 @@ public interface SysRoleMapper /** * 通过角色ID查询角色 - * + * * @param roleId 角色ID * @return 角色对象信息 */ @@ -51,7 +52,7 @@ public interface SysRoleMapper /** * 根据用户ID查询角色 - * + * * @param userName 用户名 * @return 角色列表 */ @@ -59,7 +60,7 @@ public interface SysRoleMapper /** * 校验角色名称是否唯一 - * + * * @param roleName 角色名称 * @return 角色信息 */ @@ -67,7 +68,7 @@ public interface SysRoleMapper /** * 校验角色权限是否唯一 - * + * * @param roleKey 角色权限 * @return 角色信息 */ @@ -75,7 +76,7 @@ public interface SysRoleMapper /** * 修改角色信息 - * + * * @param role 角色信息 * @return 结果 */ @@ -83,7 +84,7 @@ public interface SysRoleMapper /** * 新增角色信息 - * + * * @param role 角色信息 * @return 结果 */ @@ -91,7 +92,7 @@ public interface SysRoleMapper /** * 通过角色ID删除角色 - * + * * @param roleId 角色ID * @return 结果 */ @@ -99,7 +100,7 @@ public interface SysRoleMapper /** * 批量删除角色信息 - * + * * @param roleIds 需要删除的角色ID * @return 结果 */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysConfigService.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysConfigService.java index 09831377..6c3b106b 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysConfigService.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysConfigService.java @@ -1,18 +1,19 @@ package com.fastbee.system.service; -import java.util.List; import com.fastbee.system.domain.SysConfig; +import java.util.List; + /** * 参数配置 服务层 - * + * * @author ruoyi */ public interface ISysConfigService { /** * 查询参数配置信息 - * + * * @param configId 参数配置ID * @return 参数配置信息 */ @@ -20,7 +21,7 @@ public interface ISysConfigService /** * 根据键名查询参数配置信息 - * + * * @param configKey 参数键名 * @return 参数键值 */ @@ -28,14 +29,14 @@ public interface ISysConfigService /** * 获取验证码开关 - * + * * @return true开启,false关闭 */ public boolean selectCaptchaEnabled(); /** * 查询参数配置列表 - * + * * @param config 参数配置信息 * @return 参数配置集合 */ @@ -43,7 +44,7 @@ public interface ISysConfigService /** * 新增参数配置 - * + * * @param config 参数配置信息 * @return 结果 */ @@ -51,7 +52,7 @@ public interface ISysConfigService /** * 修改参数配置 - * + * * @param config 参数配置信息 * @return 结果 */ @@ -59,7 +60,7 @@ public interface ISysConfigService /** * 批量删除参数信息 - * + * * @param configIds 需要删除的参数ID */ public void deleteConfigByIds(Long[] configIds); @@ -81,9 +82,9 @@ public interface ISysConfigService /** * 校验参数键名是否唯一 - * + * * @param config 参数信息 * @return 结果 */ - public String checkConfigKeyUnique(SysConfig config); + public boolean checkConfigKeyUnique(SysConfig config); } diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysDeptService.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysDeptService.java index bf5ca2c0..c43f144e 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysDeptService.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysDeptService.java @@ -1,19 +1,20 @@ package com.fastbee.system.service; -import java.util.List; import com.fastbee.common.core.domain.TreeSelect; import com.fastbee.common.core.domain.entity.SysDept; +import java.util.List; + /** * 部门管理 服务层 - * + * * @author ruoyi */ public interface ISysDeptService { /** * 查询部门管理数据 - * + * * @param dept 部门信息 * @return 部门信息集合 */ @@ -21,7 +22,7 @@ public interface ISysDeptService /** * 查询部门树结构信息 - * + * * @param dept 部门信息 * @return 部门树信息集合 */ @@ -29,7 +30,7 @@ public interface ISysDeptService /** * 构建前端所需要树结构 - * + * * @param depts 部门列表 * @return 树结构列表 */ @@ -37,7 +38,7 @@ public interface ISysDeptService /** * 构建前端所需要下拉树结构 - * + * * @param depts 部门列表 * @return 下拉树结构列表 */ @@ -45,7 +46,7 @@ public interface ISysDeptService /** * 根据角色ID查询部门树信息 - * + * * @param roleId 角色ID * @return 选中部门列表 */ @@ -53,7 +54,7 @@ public interface ISysDeptService /** * 根据部门ID查询信息 - * + * * @param deptId 部门ID * @return 部门信息 */ @@ -61,7 +62,7 @@ public interface ISysDeptService /** * 根据ID查询所有子部门(正常状态) - * + * * @param deptId 部门ID * @return 子部门数 */ @@ -69,7 +70,7 @@ public interface ISysDeptService /** * 是否存在部门子节点 - * + * * @param deptId 部门ID * @return 结果 */ @@ -77,7 +78,7 @@ public interface ISysDeptService /** * 查询部门是否存在用户 - * + * * @param deptId 部门ID * @return 结果 true 存在 false 不存在 */ @@ -85,22 +86,22 @@ public interface ISysDeptService /** * 校验部门名称是否唯一 - * + * * @param dept 部门信息 * @return 结果 */ - public String checkDeptNameUnique(SysDept dept); + public boolean checkDeptNameUnique(SysDept dept); /** * 校验部门是否有数据权限 - * + * * @param deptId 部门id */ public void checkDeptDataScope(Long deptId); /** * 新增保存部门信息 - * + * * @param dept 部门信息 * @return 结果 */ @@ -108,7 +109,7 @@ public interface ISysDeptService /** * 修改保存部门信息 - * + * * @param dept 部门信息 * @return 结果 */ @@ -116,7 +117,7 @@ public interface ISysDeptService /** * 删除部门管理信息 - * + * * @param deptId 部门ID * @return 结果 */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysDictTypeService.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysDictTypeService.java index 22d0f3f2..a472277c 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysDictTypeService.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysDictTypeService.java @@ -1,19 +1,20 @@ package com.fastbee.system.service; -import java.util.List; import com.fastbee.common.core.domain.entity.SysDictData; import com.fastbee.common.core.domain.entity.SysDictType; +import java.util.List; + /** * 字典 业务层 - * + * * @author ruoyi */ public interface ISysDictTypeService { /** * 根据条件分页查询字典类型 - * + * * @param dictType 字典类型信息 * @return 字典类型集合信息 */ @@ -21,14 +22,14 @@ public interface ISysDictTypeService /** * 根据所有字典类型 - * + * * @return 字典类型集合信息 */ public List selectDictTypeAll(); /** * 根据字典类型查询字典数据 - * + * * @param dictType 字典类型 * @return 字典数据集合信息 */ @@ -36,7 +37,7 @@ public interface ISysDictTypeService /** * 根据字典类型ID查询信息 - * + * * @param dictId 字典类型ID * @return 字典类型 */ @@ -44,7 +45,7 @@ public interface ISysDictTypeService /** * 根据字典类型查询信息 - * + * * @param dictType 字典类型 * @return 字典类型 */ @@ -52,7 +53,7 @@ public interface ISysDictTypeService /** * 批量删除字典信息 - * + * * @param dictIds 需要删除的字典ID */ public void deleteDictTypeByIds(Long[] dictIds); @@ -74,7 +75,7 @@ public interface ISysDictTypeService /** * 新增保存字典类型信息 - * + * * @param dictType 字典类型信息 * @return 结果 */ @@ -82,7 +83,7 @@ public interface ISysDictTypeService /** * 修改保存字典类型信息 - * + * * @param dictType 字典类型信息 * @return 结果 */ @@ -90,9 +91,9 @@ public interface ISysDictTypeService /** * 校验字典类型称是否唯一 - * + * * @param dictType 字典类型 * @return 结果 */ - public String checkDictTypeUnique(SysDictType dictType); + public boolean checkDictTypeUnique(SysDictType dictType); } diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysMenuService.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysMenuService.java index 6c13cea0..1c19b334 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysMenuService.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysMenuService.java @@ -8,14 +8,14 @@ import com.fastbee.system.domain.vo.RouterVo; /** * 菜单 业务层 - * + * * @author ruoyi */ public interface ISysMenuService { /** * 根据用户查询系统菜单列表 - * + * * @param userId 用户ID * @return 菜单列表 */ @@ -23,7 +23,7 @@ public interface ISysMenuService /** * 根据用户查询系统菜单列表 - * + * * @param menu 菜单信息 * @param userId 用户ID * @return 菜单列表 @@ -32,7 +32,7 @@ public interface ISysMenuService /** * 根据用户ID查询权限 - * + * * @param userId 用户ID * @return 权限列表 */ @@ -40,7 +40,7 @@ public interface ISysMenuService /** * 根据角色ID查询权限 - * + * * @param roleId 角色ID * @return 权限列表 */ @@ -48,7 +48,7 @@ public interface ISysMenuService /** * 根据用户ID查询菜单树信息 - * + * * @param userId 用户ID * @return 菜单列表 */ @@ -56,7 +56,7 @@ public interface ISysMenuService /** * 根据角色ID查询菜单树信息 - * + * * @param roleId 角色ID * @return 选中菜单列表 */ @@ -64,7 +64,7 @@ public interface ISysMenuService /** * 构建前端路由所需要的菜单 - * + * * @param menus 菜单列表 * @return 路由列表 */ @@ -72,7 +72,7 @@ public interface ISysMenuService /** * 构建前端所需要树结构 - * + * * @param menus 菜单列表 * @return 树结构列表 */ @@ -80,7 +80,7 @@ public interface ISysMenuService /** * 构建前端所需要下拉树结构 - * + * * @param menus 菜单列表 * @return 下拉树结构列表 */ @@ -88,7 +88,7 @@ public interface ISysMenuService /** * 根据菜单ID查询信息 - * + * * @param menuId 菜单ID * @return 菜单信息 */ @@ -96,7 +96,7 @@ public interface ISysMenuService /** * 是否存在菜单子节点 - * + * * @param menuId 菜单ID * @return 结果 true 存在 false 不存在 */ @@ -104,7 +104,7 @@ public interface ISysMenuService /** * 查询菜单是否存在角色 - * + * * @param menuId 菜单ID * @return 结果 true 存在 false 不存在 */ @@ -112,7 +112,7 @@ public interface ISysMenuService /** * 新增保存菜单信息 - * + * * @param menu 菜单信息 * @return 结果 */ @@ -120,7 +120,7 @@ public interface ISysMenuService /** * 修改保存菜单信息 - * + * * @param menu 菜单信息 * @return 结果 */ @@ -128,7 +128,7 @@ public interface ISysMenuService /** * 删除菜单管理信息 - * + * * @param menuId 菜单ID * @return 结果 */ @@ -136,9 +136,9 @@ public interface ISysMenuService /** * 校验菜单名称是否唯一 - * + * * @param menu 菜单信息 * @return 结果 */ - public String checkMenuNameUnique(SysMenu menu); + public boolean checkMenuNameUnique(SysMenu menu); } diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysOperLogService.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysOperLogService.java index 990f7ec2..aab05df9 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysOperLogService.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysOperLogService.java @@ -1,25 +1,26 @@ package com.fastbee.system.service; -import java.util.List; import com.fastbee.system.domain.SysOperLog; +import java.util.List; + /** * 操作日志 服务层 - * + * * @author ruoyi */ public interface ISysOperLogService { /** * 新增操作日志 - * + * * @param operLog 操作日志对象 */ public void insertOperlog(SysOperLog operLog); /** * 查询系统操作日志集合 - * + * * @param operLog 操作日志对象 * @return 操作日志集合 */ @@ -27,7 +28,7 @@ public interface ISysOperLogService /** * 批量删除系统操作日志 - * + * * @param operIds 需要删除的操作日志ID * @return 结果 */ @@ -35,7 +36,7 @@ public interface ISysOperLogService /** * 查询操作日志详细 - * + * * @param operId 操作ID * @return 操作日志对象 */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysPostService.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysPostService.java index 9c3105c2..08799140 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysPostService.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysPostService.java @@ -1,18 +1,19 @@ package com.fastbee.system.service; -import java.util.List; import com.fastbee.system.domain.SysPost; +import java.util.List; + /** * 岗位信息 服务层 - * + * * @author ruoyi */ public interface ISysPostService { /** * 查询岗位信息集合 - * + * * @param post 岗位信息 * @return 岗位列表 */ @@ -20,14 +21,14 @@ public interface ISysPostService /** * 查询所有岗位 - * + * * @return 岗位列表 */ public List selectPostAll(); /** * 通过岗位ID查询岗位信息 - * + * * @param postId 岗位ID * @return 角色对象信息 */ @@ -35,7 +36,7 @@ public interface ISysPostService /** * 根据用户ID获取岗位选择框列表 - * + * * @param userId 用户ID * @return 选中岗位ID列表 */ @@ -43,23 +44,23 @@ public interface ISysPostService /** * 校验岗位名称 - * + * * @param post 岗位信息 * @return 结果 */ - public String checkPostNameUnique(SysPost post); + public boolean checkPostNameUnique(SysPost post); /** * 校验岗位编码 - * + * * @param post 岗位信息 * @return 结果 */ - public String checkPostCodeUnique(SysPost post); + public boolean checkPostCodeUnique(SysPost post); /** * 通过岗位ID查询岗位使用数量 - * + * * @param postId 岗位ID * @return 结果 */ @@ -67,7 +68,7 @@ public interface ISysPostService /** * 删除岗位信息 - * + * * @param postId 岗位ID * @return 结果 */ @@ -75,7 +76,7 @@ public interface ISysPostService /** * 批量删除岗位信息 - * + * * @param postIds 需要删除的岗位ID * @return 结果 */ @@ -83,7 +84,7 @@ public interface ISysPostService /** * 新增保存岗位信息 - * + * * @param post 岗位信息 * @return 结果 */ @@ -91,7 +92,7 @@ public interface ISysPostService /** * 修改保存岗位信息 - * + * * @param post 岗位信息 * @return 结果 */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysRoleService.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysRoleService.java index 7b30f76f..6bfb7da2 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysRoleService.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysRoleService.java @@ -1,20 +1,21 @@ package com.fastbee.system.service; -import java.util.List; -import java.util.Set; import com.fastbee.common.core.domain.entity.SysRole; import com.fastbee.system.domain.SysUserRole; +import java.util.List; +import java.util.Set; + /** * 角色业务层 - * + * * @author ruoyi */ public interface ISysRoleService { /** * 根据条件分页查询角色数据 - * + * * @param role 角色信息 * @return 角色数据集合信息 */ @@ -22,7 +23,7 @@ public interface ISysRoleService /** * 根据用户ID查询角色列表 - * + * * @param userId 用户ID * @return 角色列表 */ @@ -30,7 +31,7 @@ public interface ISysRoleService /** * 根据用户ID查询角色权限 - * + * * @param userId 用户ID * @return 权限列表 */ @@ -38,14 +39,14 @@ public interface ISysRoleService /** * 查询所有角色 - * + * * @return 角色列表 */ public List selectRoleAll(); /** * 根据用户ID获取角色选择框列表 - * + * * @param userId 用户ID * @return 选中角色ID列表 */ @@ -53,7 +54,7 @@ public interface ISysRoleService /** * 通过角色ID查询角色 - * + * * @param roleId 角色ID * @return 角色对象信息 */ @@ -61,37 +62,37 @@ public interface ISysRoleService /** * 校验角色名称是否唯一 - * + * * @param role 角色信息 * @return 结果 */ - public String checkRoleNameUnique(SysRole role); + public boolean checkRoleNameUnique(SysRole role); /** * 校验角色权限是否唯一 - * + * * @param role 角色信息 * @return 结果 */ - public String checkRoleKeyUnique(SysRole role); + public boolean checkRoleKeyUnique(SysRole role); /** * 校验角色是否允许操作 - * + * * @param role 角色信息 */ public void checkRoleAllowed(SysRole role); /** * 校验角色是否有数据权限 - * - * @param roleId 角色id + * + * @param roleIds 角色id */ - public void checkRoleDataScope(Long roleId); + public void checkRoleDataScope(Long... roleIds); /** * 通过角色ID查询角色使用数量 - * + * * @param roleId 角色ID * @return 结果 */ @@ -99,7 +100,7 @@ public interface ISysRoleService /** * 新增保存角色信息 - * + * * @param role 角色信息 * @return 结果 */ @@ -107,7 +108,7 @@ public interface ISysRoleService /** * 修改保存角色信息 - * + * * @param role 角色信息 * @return 结果 */ @@ -115,7 +116,7 @@ public interface ISysRoleService /** * 修改角色状态 - * + * * @param role 角色信息 * @return 结果 */ @@ -123,7 +124,7 @@ public interface ISysRoleService /** * 修改数据权限信息 - * + * * @param role 角色信息 * @return 结果 */ @@ -131,7 +132,7 @@ public interface ISysRoleService /** * 通过角色ID删除角色 - * + * * @param roleId 角色ID * @return 结果 */ @@ -139,7 +140,7 @@ public interface ISysRoleService /** * 批量删除角色信息 - * + * * @param roleIds 需要删除的角色ID * @return 结果 */ @@ -147,7 +148,7 @@ public interface ISysRoleService /** * 取消授权用户角色 - * + * * @param userRole 用户和角色关联信息 * @return 结果 */ @@ -155,7 +156,7 @@ public interface ISysRoleService /** * 批量取消授权用户角色 - * + * * @param roleId 角色ID * @param userIds 需要取消授权的用户数据ID * @return 结果 @@ -164,7 +165,7 @@ public interface ISysRoleService /** * 批量选择授权用户角色 - * + * * @param roleId 角色ID * @param userIds 需要删除的用户数据ID * @return 结果 diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysUserService.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysUserService.java index 021cdd3a..3f4122c1 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysUserService.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/ISysUserService.java @@ -73,7 +73,7 @@ public interface ISysUserService * @param user 用户信息 * @return 结果 */ - public String checkUserNameUnique(SysUser user); + public boolean checkUserNameUnique(SysUser user); /** * 校验手机号码是否唯一 @@ -81,7 +81,7 @@ public interface ISysUserService * @param user 用户信息 * @return 结果 */ - public String checkPhoneUnique(SysUser user); + public boolean checkPhoneUnique(SysUser user); /** * 校验email是否唯一 @@ -89,7 +89,7 @@ public interface ISysUserService * @param user 用户信息 * @return 结果 */ - public String checkEmailUnique(SysUser user); + public boolean checkEmailUnique(SysUser user); /** * 校验用户是否允许操作 diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysConfigServiceImpl.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysConfigServiceImpl.java index 13226fe7..d994ab09 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysConfigServiceImpl.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysConfigServiceImpl.java @@ -1,10 +1,5 @@ package com.fastbee.system.service.impl; -import java.util.Collection; -import java.util.List; -import javax.annotation.PostConstruct; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import com.fastbee.common.annotation.DataSource; import com.fastbee.common.constant.CacheConstants; import com.fastbee.common.constant.UserConstants; @@ -16,10 +11,16 @@ import com.fastbee.common.utils.StringUtils; import com.fastbee.system.domain.SysConfig; import com.fastbee.system.mapper.SysConfigMapper; import com.fastbee.system.service.ISysConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import javax.annotation.PostConstruct; +import java.util.Collection; +import java.util.List; /** * 参数配置 服务层实现 - * + * * @author ruoyi */ @Service @@ -42,7 +43,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 查询参数配置信息 - * + * * @param configId 参数配置ID * @return 参数配置信息 */ @@ -57,7 +58,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 根据键名查询参数配置信息 - * + * * @param configKey 参数key * @return 参数键值 */ @@ -82,7 +83,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 获取验证码开关 - * + * * @return true开启,false关闭 */ @Override @@ -98,7 +99,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 查询参数配置列表 - * + * * @param config 参数配置信息 * @return 参数配置集合 */ @@ -110,7 +111,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 新增参数配置 - * + * * @param config 参数配置信息 * @return 结果 */ @@ -127,7 +128,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 修改参数配置 - * + * * @param config 参数配置信息 * @return 结果 */ @@ -150,7 +151,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 批量删除参数信息 - * + * * @param configIds 需要删除的参数ID */ @Override @@ -203,12 +204,12 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 校验参数键名是否唯一 - * + * * @param config 参数配置信息 * @return 结果 */ @Override - public String checkConfigKeyUnique(SysConfig config) + public boolean checkConfigKeyUnique(SysConfig config) { Long configId = StringUtils.isNull(config.getConfigId()) ? -1L : config.getConfigId(); SysConfig info = configMapper.checkConfigKeyUnique(config.getConfigKey()); @@ -221,7 +222,7 @@ public class SysConfigServiceImpl implements ISysConfigService /** * 设置cache key - * + * * @param configKey 参数键 * @return 缓存键key */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDeptServiceImpl.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDeptServiceImpl.java index 0abe4efc..926b7139 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDeptServiceImpl.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDeptServiceImpl.java @@ -1,11 +1,5 @@ package com.fastbee.system.service.impl; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.stream.Collectors; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import com.fastbee.common.annotation.DataScope; import com.fastbee.common.constant.UserConstants; import com.fastbee.common.core.domain.TreeSelect; @@ -20,10 +14,17 @@ import com.fastbee.common.utils.spring.SpringUtils; import com.fastbee.system.mapper.SysDeptMapper; import com.fastbee.system.mapper.SysRoleMapper; import com.fastbee.system.service.ISysDeptService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.stream.Collectors; /** * 部门管理 服务实现 - * + * * @author ruoyi */ @Service @@ -37,7 +38,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 查询部门管理数据 - * + * * @param dept 部门信息 * @return 部门信息集合 */ @@ -50,7 +51,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 查询部门树结构信息 - * + * * @param dept 部门信息 * @return 部门树信息集合 */ @@ -63,7 +64,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 构建前端所需要树结构 - * + * * @param depts 部门列表 * @return 树结构列表 */ @@ -90,7 +91,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 构建前端所需要下拉树结构 - * + * * @param depts 部门列表 * @return 下拉树结构列表 */ @@ -103,7 +104,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 根据角色ID查询部门树信息 - * + * * @param roleId 角色ID * @return 选中部门列表 */ @@ -116,7 +117,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 根据部门ID查询信息 - * + * * @param deptId 部门ID * @return 部门信息 */ @@ -128,7 +129,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 根据ID查询所有子部门(正常状态) - * + * * @param deptId 部门ID * @return 子部门数 */ @@ -140,7 +141,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 是否存在子节点 - * + * * @param deptId 部门ID * @return 结果 */ @@ -153,7 +154,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 查询部门是否存在用户 - * + * * @param deptId 部门ID * @return 结果 true 存在 false 不存在 */ @@ -166,12 +167,12 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 校验部门名称是否唯一 - * + * * @param dept 部门信息 * @return 结果 */ @Override - public String checkDeptNameUnique(SysDept dept) + public boolean checkDeptNameUnique(SysDept dept) { Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId(); SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId()); @@ -184,13 +185,13 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 校验部门是否有数据权限 - * + * * @param deptId 部门id */ @Override public void checkDeptDataScope(Long deptId) { - if (!SysUser.isAdmin(SecurityUtils.getUserId())) + if (!SysUser.isAdmin(SecurityUtils.getUserId()) && StringUtils.isNotNull(deptId)) { SysDept dept = new SysDept(); dept.setDeptId(deptId); @@ -204,7 +205,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 新增保存部门信息 - * + * * @param dept 部门信息 * @return 结果 */ @@ -223,7 +224,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 修改保存部门信息 - * + * * @param dept 部门信息 * @return 结果 */ @@ -251,7 +252,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 修改该部门的父级部门状态 - * + * * @param dept 当前部门 */ private void updateParentDeptStatusNormal(SysDept dept) @@ -263,7 +264,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 修改子元素关系 - * + * * @param deptId 被修改的部门ID * @param newAncestors 新的父ID集合 * @param oldAncestors 旧的父ID集合 @@ -283,7 +284,7 @@ public class SysDeptServiceImpl implements ISysDeptService /** * 删除部门管理信息 - * + * * @param deptId 部门ID * @return 结果 */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDictTypeServiceImpl.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDictTypeServiceImpl.java index db06a350..20340852 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDictTypeServiceImpl.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysDictTypeServiceImpl.java @@ -1,13 +1,5 @@ package com.fastbee.system.service.impl; -import java.util.Comparator; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import javax.annotation.PostConstruct; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import com.fastbee.common.constant.UserConstants; import com.fastbee.common.core.domain.entity.SysDictData; import com.fastbee.common.core.domain.entity.SysDictType; @@ -17,10 +9,19 @@ import com.fastbee.common.utils.StringUtils; import com.fastbee.system.mapper.SysDictDataMapper; import com.fastbee.system.mapper.SysDictTypeMapper; import com.fastbee.system.service.ISysDictTypeService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.PostConstruct; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; /** * 字典 业务层处理 - * + * * @author ruoyi */ @Service @@ -43,7 +44,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 根据条件分页查询字典类型 - * + * * @param dictType 字典类型信息 * @return 字典类型集合信息 */ @@ -55,7 +56,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 根据所有字典类型 - * + * * @return 字典类型集合信息 */ @Override @@ -66,7 +67,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 根据字典类型查询字典数据 - * + * * @param dictType 字典类型 * @return 字典数据集合信息 */ @@ -89,7 +90,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 根据字典类型ID查询信息 - * + * * @param dictId 字典类型ID * @return 字典类型 */ @@ -101,7 +102,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 根据字典类型查询信息 - * + * * @param dictType 字典类型 * @return 字典类型 */ @@ -113,7 +114,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 批量删除字典类型信息 - * + * * @param dictIds 需要删除的字典ID */ @Override @@ -167,7 +168,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 新增保存字典类型信息 - * + * * @param dict 字典类型信息 * @return 结果 */ @@ -184,7 +185,7 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 修改保存字典类型信息 - * + * * @param dict 字典类型信息 * @return 结果 */ @@ -205,12 +206,12 @@ public class SysDictTypeServiceImpl implements ISysDictTypeService /** * 校验字典类型称是否唯一 - * + * * @param dict 字典类型 * @return 结果 */ @Override - public String checkDictTypeUnique(SysDictType dict) + public boolean checkDictTypeUnique(SysDictType dict) { Long dictId = StringUtils.isNull(dict.getDictId()) ? -1L : dict.getDictId(); SysDictType dictType = dictTypeMapper.checkDictTypeUnique(dict.getDictType()); diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysMenuServiceImpl.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysMenuServiceImpl.java index d8c713af..1227943c 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysMenuServiceImpl.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysMenuServiceImpl.java @@ -27,7 +27,7 @@ import com.fastbee.system.service.ISysMenuService; /** * 菜单 业务层处理 - * + * * @author ruoyi */ @Service @@ -46,7 +46,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 根据用户查询系统菜单列表 - * + * * @param userId 用户ID * @return 菜单列表 */ @@ -58,7 +58,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 查询系统菜单列表 - * + * * @param menu 菜单信息 * @return 菜单列表 */ @@ -81,7 +81,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 根据用户ID查询权限 - * + * * @param userId 用户ID * @return 权限列表 */ @@ -102,7 +102,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 根据角色ID查询权限 - * + * * @param roleId 角色ID * @return 权限列表 */ @@ -123,7 +123,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 根据用户ID查询菜单 - * + * * @param userId 用户名称 * @return 菜单列表 */ @@ -144,7 +144,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 根据角色ID查询菜单树信息 - * + * * @param roleId 角色ID * @return 选中菜单列表 */ @@ -157,7 +157,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 构建前端路由所需要的菜单 - * + * * @param menus 菜单列表 * @return 路由列表 */ @@ -215,7 +215,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 构建前端所需要树结构 - * + * * @param menus 菜单列表 * @return 树结构列表 */ @@ -243,7 +243,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 构建前端所需要下拉树结构 - * + * * @param menus 菜单列表 * @return 下拉树结构列表 */ @@ -256,7 +256,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 根据菜单ID查询信息 - * + * * @param menuId 菜单ID * @return 菜单信息 */ @@ -268,7 +268,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 是否存在菜单子节点 - * + * * @param menuId 菜单ID * @return 结果 */ @@ -281,7 +281,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 查询菜单使用数量 - * + * * @param menuId 菜单ID * @return 结果 */ @@ -294,7 +294,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 新增保存菜单信息 - * + * * @param menu 菜单信息 * @return 结果 */ @@ -306,7 +306,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 修改保存菜单信息 - * + * * @param menu 菜单信息 * @return 结果 */ @@ -318,7 +318,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 删除菜单管理信息 - * + * * @param menuId 菜单ID * @return 结果 */ @@ -330,12 +330,12 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 校验菜单名称是否唯一 - * + * * @param menu 菜单信息 * @return 结果 */ @Override - public String checkMenuNameUnique(SysMenu menu) + public boolean checkMenuNameUnique(SysMenu menu) { Long menuId = StringUtils.isNull(menu.getMenuId()) ? -1L : menu.getMenuId(); SysMenu info = menuMapper.checkMenuNameUnique(menu.getMenuName(), menu.getParentId()); @@ -348,7 +348,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 获取路由名称 - * + * * @param menu 菜单信息 * @return 路由名称 */ @@ -365,7 +365,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 获取路由地址 - * + * * @param menu 菜单信息 * @return 路由地址 */ @@ -393,7 +393,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 获取组件信息 - * + * * @param menu 菜单信息 * @return 组件信息 */ @@ -417,7 +417,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 是否为菜单内部跳转 - * + * * @param menu 菜单信息 * @return 结果 */ @@ -429,7 +429,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 是否为内链组件 - * + * * @param menu 菜单信息 * @return 结果 */ @@ -440,7 +440,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 是否为parent_view组件 - * + * * @param menu 菜单信息 * @return 结果 */ @@ -451,7 +451,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 根据父节点的ID获取所有子节点 - * + * * @param list 分类表 * @param parentId 传入的父节点ID * @return String @@ -474,7 +474,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 递归列表 - * + * * @param list 分类表 * @param t 子节点 */ @@ -520,7 +520,7 @@ public class SysMenuServiceImpl implements ISysMenuService /** * 内链域名特殊字符替换 - * + * * @return 替换后的内链域名 */ public String innerLinkReplaceEach(String path) diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysOperLogServiceImpl.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysOperLogServiceImpl.java index 7df1116d..36e250e5 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysOperLogServiceImpl.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysOperLogServiceImpl.java @@ -1,15 +1,16 @@ package com.fastbee.system.service.impl; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import com.fastbee.system.domain.SysOperLog; import com.fastbee.system.mapper.SysOperLogMapper; import com.fastbee.system.service.ISysOperLogService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; /** * 操作日志 服务层处理 - * + * * @author ruoyi */ @Service @@ -20,7 +21,7 @@ public class SysOperLogServiceImpl implements ISysOperLogService /** * 新增操作日志 - * + * * @param operLog 操作日志对象 */ @Override @@ -31,7 +32,7 @@ public class SysOperLogServiceImpl implements ISysOperLogService /** * 查询系统操作日志集合 - * + * * @param operLog 操作日志对象 * @return 操作日志集合 */ @@ -43,7 +44,7 @@ public class SysOperLogServiceImpl implements ISysOperLogService /** * 批量删除系统操作日志 - * + * * @param operIds 需要删除的操作日志ID * @return 结果 */ @@ -55,7 +56,7 @@ public class SysOperLogServiceImpl implements ISysOperLogService /** * 查询操作日志详细 - * + * * @param operId 操作ID * @return 操作日志对象 */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysPostServiceImpl.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysPostServiceImpl.java index e4261907..189cbeb5 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysPostServiceImpl.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysPostServiceImpl.java @@ -1,8 +1,5 @@ package com.fastbee.system.service.impl; -import java.util.List; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; import com.fastbee.common.constant.UserConstants; import com.fastbee.common.exception.ServiceException; import com.fastbee.common.utils.StringUtils; @@ -10,10 +7,14 @@ import com.fastbee.system.domain.SysPost; import com.fastbee.system.mapper.SysPostMapper; import com.fastbee.system.mapper.SysUserPostMapper; import com.fastbee.system.service.ISysPostService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; + +import java.util.List; /** * 岗位信息 服务层处理 - * + * * @author ruoyi */ @Service @@ -27,7 +28,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 查询岗位信息集合 - * + * * @param post 岗位信息 * @return 岗位信息集合 */ @@ -39,7 +40,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 查询所有岗位 - * + * * @return 岗位列表 */ @Override @@ -50,7 +51,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 通过岗位ID查询岗位信息 - * + * * @param postId 岗位ID * @return 角色对象信息 */ @@ -62,7 +63,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 根据用户ID获取岗位选择框列表 - * + * * @param userId 用户ID * @return 选中岗位ID列表 */ @@ -74,12 +75,12 @@ public class SysPostServiceImpl implements ISysPostService /** * 校验岗位名称是否唯一 - * + * * @param post 岗位信息 * @return 结果 */ @Override - public String checkPostNameUnique(SysPost post) + public boolean checkPostNameUnique(SysPost post) { Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); SysPost info = postMapper.checkPostNameUnique(post.getPostName()); @@ -92,12 +93,12 @@ public class SysPostServiceImpl implements ISysPostService /** * 校验岗位编码是否唯一 - * + * * @param post 岗位信息 * @return 结果 */ @Override - public String checkPostCodeUnique(SysPost post) + public boolean checkPostCodeUnique(SysPost post) { Long postId = StringUtils.isNull(post.getPostId()) ? -1L : post.getPostId(); SysPost info = postMapper.checkPostCodeUnique(post.getPostCode()); @@ -110,7 +111,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 通过岗位ID查询岗位使用数量 - * + * * @param postId 岗位ID * @return 结果 */ @@ -122,7 +123,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 删除岗位信息 - * + * * @param postId 岗位ID * @return 结果 */ @@ -134,7 +135,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 批量删除岗位信息 - * + * * @param postIds 需要删除的岗位ID * @return 结果 */ @@ -154,7 +155,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 新增保存岗位信息 - * + * * @param post 岗位信息 * @return 结果 */ @@ -166,7 +167,7 @@ public class SysPostServiceImpl implements ISysPostService /** * 修改保存岗位信息 - * + * * @param post 岗位信息 * @return 结果 */ diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysRoleServiceImpl.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysRoleServiceImpl.java index 665a4d47..92d36999 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysRoleServiceImpl.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysRoleServiceImpl.java @@ -1,13 +1,5 @@ package com.fastbee.system.service.impl; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import com.fastbee.common.annotation.DataScope; import com.fastbee.common.constant.UserConstants; import com.fastbee.common.core.domain.entity.SysRole; @@ -24,10 +16,15 @@ import com.fastbee.system.mapper.SysRoleMapper; import com.fastbee.system.mapper.SysRoleMenuMapper; import com.fastbee.system.mapper.SysUserRoleMapper; import com.fastbee.system.service.ISysRoleService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.*; /** * 角色 业务层处理 - * + * * @author ruoyi */ @Service @@ -47,7 +44,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 根据条件分页查询角色数据 - * + * * @param role 角色信息 * @return 角色数据集合信息 */ @@ -60,7 +57,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 根据用户ID查询角色 - * + * * @param userId 用户ID * @return 角色列表 */ @@ -85,7 +82,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 根据用户ID查询权限 - * + * * @param userId 用户ID * @return 权限列表 */ @@ -106,7 +103,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 查询所有角色 - * + * * @return 角色列表 */ @Override @@ -117,7 +114,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 根据用户ID获取角色选择框列表 - * + * * @param userId 用户ID * @return 选中角色ID列表 */ @@ -129,7 +126,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 通过角色ID查询角色 - * + * * @param roleId 角色ID * @return 角色对象信息 */ @@ -141,12 +138,12 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 校验角色名称是否唯一 - * + * * @param role 角色信息 * @return 结果 */ @Override - public String checkRoleNameUnique(SysRole role) + public boolean checkRoleNameUnique(SysRole role) { Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); SysRole info = roleMapper.checkRoleNameUnique(role.getRoleName()); @@ -159,12 +156,12 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 校验角色权限是否唯一 - * + * * @param role 角色信息 * @return 结果 */ @Override - public String checkRoleKeyUnique(SysRole role) + public boolean checkRoleKeyUnique(SysRole role) { Long roleId = StringUtils.isNull(role.getRoleId()) ? -1L : role.getRoleId(); SysRole info = roleMapper.checkRoleKeyUnique(role.getRoleKey()); @@ -177,7 +174,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 校验角色是否允许操作 - * + * * @param role 角色信息 */ @Override @@ -191,27 +188,30 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 校验角色是否有数据权限 - * - * @param roleId 角色id + * + * @param roleIds 角色id */ @Override - public void checkRoleDataScope(Long roleId) + public void checkRoleDataScope(Long... roleIds) { if (!SysUser.isAdmin(SecurityUtils.getUserId())) { - SysRole role = new SysRole(); - role.setRoleId(roleId); - List roles = SpringUtils.getAopProxy(this).selectRoleList(role); - if (StringUtils.isEmpty(roles)) + for (Long roleId : roleIds) { - throw new ServiceException("没有权限访问角色数据!"); + SysRole role = new SysRole(); + role.setRoleId(roleId); + List roles = SpringUtils.getAopProxy(this).selectRoleList(role); + if (StringUtils.isEmpty(roles)) + { + throw new ServiceException("没有权限访问角色数据!"); + } } } } /** * 通过角色ID查询角色使用数量 - * + * * @param roleId 角色ID * @return 结果 */ @@ -223,7 +223,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 新增保存角色信息 - * + * * @param role 角色信息 * @return 结果 */ @@ -238,7 +238,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 修改保存角色信息 - * + * * @param role 角色信息 * @return 结果 */ @@ -255,7 +255,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 修改角色状态 - * + * * @param role 角色信息 * @return 结果 */ @@ -267,7 +267,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 修改数据权限信息 - * + * * @param role 角色信息 * @return 结果 */ @@ -285,7 +285,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 新增角色菜单信息 - * + * * @param role 角色对象 */ public int insertRoleMenu(SysRole role) @@ -333,7 +333,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 通过角色ID删除角色 - * + * * @param roleId 角色ID * @return 结果 */ @@ -350,7 +350,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 批量删除角色信息 - * + * * @param roleIds 需要删除的角色ID * @return 结果 */ @@ -377,7 +377,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 取消授权用户角色 - * + * * @param userRole 用户和角色关联信息 * @return 结果 */ @@ -389,7 +389,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 批量取消授权用户角色 - * + * * @param roleId 角色ID * @param userIds 需要取消授权的用户数据ID * @return 结果 @@ -402,7 +402,7 @@ public class SysRoleServiceImpl implements ISysRoleService /** * 批量选择授权用户角色 - * + * * @param roleId 角色ID * @param userIds 需要授权的用户数据ID * @return 结果 diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysUserServiceImpl.java b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysUserServiceImpl.java index 90569b7e..42d7a353 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysUserServiceImpl.java +++ b/springboot/fastbee-service/fastbee-system-service/src/main/java/com/fastbee/system/service/impl/SysUserServiceImpl.java @@ -13,12 +13,9 @@ import com.fastbee.common.utils.spring.SpringUtils; import com.fastbee.system.domain.SysPost; import com.fastbee.system.domain.SysUserPost; import com.fastbee.system.domain.SysUserRole; -import com.fastbee.system.mapper.SysPostMapper; -import com.fastbee.system.mapper.SysRoleMapper; -import com.fastbee.system.mapper.SysUserMapper; -import com.fastbee.system.mapper.SysUserPostMapper; -import com.fastbee.system.mapper.SysUserRoleMapper; +import com.fastbee.system.mapper.*; import com.fastbee.system.service.ISysConfigService; +import com.fastbee.system.service.ISysDeptService; import com.fastbee.system.service.ISysUserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -60,6 +57,9 @@ public class SysUserServiceImpl implements ISysUserService @Autowired private ISysConfigService configService; + @Autowired + private ISysDeptService deptService; + @Autowired protected Validator validator; @@ -167,7 +167,7 @@ public class SysUserServiceImpl implements ISysUserService * @return 结果 */ @Override - public String checkUserNameUnique(SysUser user) + public boolean checkUserNameUnique(SysUser user) { Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); SysUser info = userMapper.checkUserNameUnique(user.getUserName()); @@ -185,7 +185,7 @@ public class SysUserServiceImpl implements ISysUserService * @return */ @Override - public String checkPhoneUnique(SysUser user) + public boolean checkPhoneUnique(SysUser user) { Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); SysUser info = userMapper.checkPhoneUnique(user.getPhonenumber()); @@ -203,7 +203,7 @@ public class SysUserServiceImpl implements ISysUserService * @return */ @Override - public String checkEmailUnique(SysUser user) + public boolean checkEmailUnique(SysUser user) { Long userId = StringUtils.isNull(user.getUserId()) ? -1L : user.getUserId(); SysUser info = userMapper.checkEmailUnique(user.getEmail()); @@ -495,7 +495,6 @@ public class SysUserServiceImpl implements ISysUserService int failureNum = 0; StringBuilder successMsg = new StringBuilder(); StringBuilder failureMsg = new StringBuilder(); - String password = configService.selectConfigByKey("sys.user.initPassword"); for (SysUser user : userList) { try @@ -505,19 +504,23 @@ public class SysUserServiceImpl implements ISysUserService if (StringUtils.isNull(u)) { BeanValidators.validateWithException(validator, user); + deptService.checkDeptDataScope(user.getDeptId()); + String password = configService.selectConfigByKey("sys.user.initPassword"); user.setPassword(SecurityUtils.encryptPassword(password)); user.setCreateBy(operName); - this.insertUser(user); + userMapper.insertUser(user); successNum++; successMsg.append("
" + successNum + "、账号 " + user.getUserName() + " 导入成功"); } else if (isUpdateSupport) { BeanValidators.validateWithException(validator, user); - checkUserAllowed(user); - checkUserDataScope(user.getUserId()); + checkUserAllowed(u); + checkUserDataScope(u.getUserId()); + deptService.checkDeptDataScope(user.getDeptId()); + user.setUserId(u.getUserId()); user.setUpdateBy(operName); - this.updateUser(user); + userMapper.updateUser(user); successNum++; successMsg.append("
" + successNum + "、账号 " + user.getUserName() + " 更新成功"); } diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysOperLogMapper.xml b/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysOperLogMapper.xml index 38456ed0..46a01557 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysOperLogMapper.xml +++ b/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysOperLogMapper.xml @@ -21,21 +21,25 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" + - select oper_id, title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time + select oper_id, title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time, cost_time from sys_oper_log - + - insert into sys_oper_log(title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, oper_time) - values (#{title}, #{businessType}, #{method}, #{requestMethod}, #{operatorType}, #{operName}, #{deptName}, #{operUrl}, #{operIp}, #{operLocation}, #{operParam}, #{jsonResult}, #{status}, #{errorMsg}, sysdate()) + insert into sys_oper_log(title, business_type, method, request_method, operator_type, oper_name, dept_name, oper_url, oper_ip, oper_location, oper_param, json_result, status, error_msg, cost_time, oper_time) + values (#{title}, #{businessType}, #{method}, #{requestMethod}, #{operatorType}, #{operName}, #{deptName}, #{operUrl}, #{operIp}, #{operLocation}, #{operParam}, #{jsonResult}, #{status}, #{errorMsg}, #{costTime}, sysdate()) - + - + delete from sys_oper_log where oper_id in #{operId} - + - + - + truncate table sys_oper_log - \ No newline at end of file + diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysRoleMapper.xml b/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysRoleMapper.xml index 9382b93a..84bfa099 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysRoleMapper.xml +++ b/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysRoleMapper.xml @@ -20,16 +20,16 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - + select distinct r.role_id, r.role_name, r.role_key, r.role_sort, r.data_scope, r.menu_check_strictly, r.dept_check_strictly, - r.status, r.del_flag, r.create_time, r.remark + r.status, r.del_flag, r.create_time, r.remark from sys_role r left join sys_user_role ur on ur.role_id = r.role_id left join sys_user u on u.user_id = ur.user_id left join sys_dept d on u.dept_id = d.dept_id - + - + - + - + - + - + - + - + - + insert into sys_role( role_id, @@ -120,7 +120,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" sysdate() ) - + update sys_role @@ -137,16 +137,16 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" where role_id = #{roleId} - + update sys_role set del_flag = '2' where role_id = #{roleId} - + update sys_role set del_flag = '2' where role_id in #{roleId} - + - - \ No newline at end of file + + diff --git a/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysUserMapper.xml b/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysUserMapper.xml index 8a25c029..8d171092 100644 --- a/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysUserMapper.xml +++ b/springboot/fastbee-service/fastbee-system-service/src/main/resources/mapper/system/SysUserMapper.xml @@ -23,8 +23,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - - + + @@ -42,7 +42,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - + @@ -73,10 +73,10 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" AND u.phonenumber like concat('%', #{phonenumber}, '%') - AND date_format(u.create_time,'%y%m%d') >= date_format(#{params.beginTime},'%y%m%d') + AND date_format(u.create_time,'%Y%m%d') >= date_format(#{params.beginTime},'%Y%m%d') - AND date_format(u.create_time,'%y%m%d') <= date_format(#{params.endTime},'%y%m%d') + AND date_format(u.create_time,'%Y%m%d') <= date_format(#{params.endTime},'%Y%m%d') AND (u.dept_id = #{deptId} OR u.dept_id IN ( SELECT t.dept_id FROM sys_dept t WHERE find_in_set(#{deptId}, ancestors) )) @@ -142,12 +142,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" select user_id, email from sys_user where email = #{email} and del_flag = '0' limit 1 - - - + insert into sys_user( user_id, dept_id, @@ -183,7 +178,6 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" update sys_user dept_id = #{deptId}, - user_name = #{userName}, nick_name = #{nickName}, email = #{email}, phonenumber = #{phonenumber}, @@ -223,29 +217,4 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - - update iot_social_user - set del_flag = 1, - update_time = now() - where sys_user_id = #{sysUserId} - and source_client in - - #{sourceClient} - - - - - update iot_social_user - set del_flag = 1, - update_time = now() - where sys_user_id in - - #{sysUserId} - - and source_client in - - #{sourceClient} - - - diff --git a/springboot/pom.xml b/springboot/pom.xml index 06054532..f545ec7b 100644 --- a/springboot/pom.xml +++ b/springboot/pom.xml @@ -13,7 +13,7 @@ FastBee物联网平台 - 3.8.5 + 3.8.9 2.1.0 UTF-8 UTF-8 @@ -66,15 +66,65 @@ + + + org.springframework + spring-framework-bom + ${spring-framework.version} + pom + import + + + + + org.springframework.security + spring-security-bom + ${spring-security.version} + pom + import + + org.springframework.boot spring-boot-dependencies - 2.5.14 + ${spring-boot.version} pom import + + + ch.qos.logback + logback-core + ${logback.version} + + + + ch.qos.logback + logback-classic + ${logback.version} + + + + + org.apache.tomcat.embed + tomcat-embed-core + ${tomcat.version} + + + + org.apache.tomcat.embed + tomcat-embed-el + ${tomcat.version} + + + + org.apache.tomcat.embed + tomcat-embed-websocket + ${tomcat.version} + + com.alibaba From 54f248733022438d1587871f89da547e3c335e8a Mon Sep 17 00:00:00 2001 From: gx_ma <1773945958@qq.com> Date: Tue, 22 Apr 2025 10:03:31 +0800 Subject: [PATCH 02/18] =?UTF-8?q?feat(=E5=A4=9A=E6=95=B0=E6=8D=AE=E6=BA=90?= =?UTF-8?q?=E8=84=9A=E6=9C=AC):=20=E8=BE=BE=E6=A2=A6=E3=80=81SQL=20server?= =?UTF-8?q?=E3=80=81postgres?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/fastbee/FastBeeApplication.java | 2 +- .../common/mabatis/enums/DataBaseType.java | 64 + springboot/fastbee-framework/pom.xml | 7 + .../framework/config/DataSourceConfig.java | 69 + .../mybatis/helper/DataBaseHelper.java | 164 + .../fastbee/data/service/impl/DeviceJob.java | 4 +- .../fastbee/sip/mapper/SipDeviceMapper.java | 2 +- .../main/resources/mapper/SipDeviceMapper.xml | 2 +- .../fastbee-iot-service/pom.xml | 7 + .../fastbee-system-service/pom.xml | 6 + springboot/sql/dameng/fastbee-v2.1.sql | 3226 ++++++ springboot/sql/postgres/fastbee-v2.1.sql | 4434 ++++++++ springboot/sql/sqlserver/fastbee-v2.1.sql | 9327 +++++++++++++++++ 13 files changed, 17310 insertions(+), 4 deletions(-) create mode 100644 springboot/fastbee-common/src/main/java/com/fastbee/common/mabatis/enums/DataBaseType.java create mode 100644 springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/DataSourceConfig.java create mode 100644 springboot/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/helper/DataBaseHelper.java create mode 100644 springboot/sql/dameng/fastbee-v2.1.sql create mode 100644 springboot/sql/postgres/fastbee-v2.1.sql create mode 100644 springboot/sql/sqlserver/fastbee-v2.1.sql diff --git a/springboot/fastbee-admin/src/main/java/com/fastbee/FastBeeApplication.java b/springboot/fastbee-admin/src/main/java/com/fastbee/FastBeeApplication.java index 945d7de5..b9833640 100644 --- a/springboot/fastbee-admin/src/main/java/com/fastbee/FastBeeApplication.java +++ b/springboot/fastbee-admin/src/main/java/com/fastbee/FastBeeApplication.java @@ -9,7 +9,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; * * @author ruoyi */ -@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) +@SpringBootApplication public class FastBeeApplication { public static void main(String[] args) diff --git a/springboot/fastbee-common/src/main/java/com/fastbee/common/mabatis/enums/DataBaseType.java b/springboot/fastbee-common/src/main/java/com/fastbee/common/mabatis/enums/DataBaseType.java new file mode 100644 index 00000000..2fef9e70 --- /dev/null +++ b/springboot/fastbee-common/src/main/java/com/fastbee/common/mabatis/enums/DataBaseType.java @@ -0,0 +1,64 @@ +package com.fastbee.common.mabatis.enums; + +import com.fastbee.common.utils.StringUtils; +import lombok.AllArgsConstructor; +import lombok.Getter; + + +/** + * 数据库类型 + * + * @author Lion Li + */ +@Getter +@AllArgsConstructor +public enum DataBaseType { + + /** + * MySQL + */ + MY_SQL("MySQL"), + + /** + * Oracle + */ + ORACLE("Oracle"), + + /** + * PostgreSQL + */ + POSTGRE_SQL("PostgreSQL"), + + /** + * SQL Server + */ + SQL_SERVER("Microsoft SQL Server"), + + /** + * 达梦 + */ + DM("DM DBMS"); + + /** + * 数据库类型 + */ + private final String type; + + /** + * 根据数据库产品名称查找对应的数据库类型 + * + * @param databaseProductName 数据库产品名称 + * @return 对应的数据库类型枚举值,如果未找到则返回 null + */ + public static DataBaseType find(String databaseProductName) { + if (StringUtils.isBlank(databaseProductName)) { + return null; + } + for (DataBaseType type : values()) { + if (type.getType().equals(databaseProductName)) { + return type; + } + } + return null; + } +} diff --git a/springboot/fastbee-framework/pom.xml b/springboot/fastbee-framework/pom.xml index b628b4e8..91196f4a 100644 --- a/springboot/fastbee-framework/pom.xml +++ b/springboot/fastbee-framework/pom.xml @@ -59,6 +59,13 @@ oshi-core + + + com.baomidou + dynamic-datasource-spring-boot-starter + ${dynamic-datasource.version} + + diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/DataSourceConfig.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/DataSourceConfig.java new file mode 100644 index 00000000..92fd89af --- /dev/null +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/config/DataSourceConfig.java @@ -0,0 +1,69 @@ +package com.fastbee.framework.config; + +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator; +import com.baomidou.dynamic.datasource.provider.AbstractDataSourceProvider; +import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider; +import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Lazy; +import org.springframework.context.annotation.Primary; +import org.springframework.jdbc.datasource.DataSourceTransactionManager; + +import javax.sql.DataSource; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +@Configuration +public class DataSourceConfig { + private final DynamicDataSourceProperties properties; + private final DefaultDataSourceCreator dataSourceCreator; + private final DataSource shardingSphereDataSource; + + public DataSourceConfig(DynamicDataSourceProperties properties, + DefaultDataSourceCreator dataSourceCreator, + @Lazy + @Qualifier("shardingSphereDataSource") DataSource shardingSphereDataSource) { + this.properties = properties; + this.dataSourceCreator = dataSourceCreator; + this.shardingSphereDataSource = shardingSphereDataSource; + } + + + @Bean + public DynamicDataSourceProvider dynamicDataSourceProvider() { + return new AbstractDataSourceProvider(dataSourceCreator) { + @Override + public Map loadDataSources() { + Map dataSourceMap = new HashMap<>(); + // 把 shardingSphereDataSource 加入多数据源,到时候使用的时候就可以 `@DS("shardingSphere")` + if(null != shardingSphereDataSource) { + dataSourceMap.put("shardingSphere", shardingSphereDataSource); + } + return dataSourceMap; + } + }; + } + + @Primary + @Bean + public DataSource dataSource(List providers) { + DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource(providers); + dataSource.setPrimary(properties.getPrimary()); + dataSource.setStrict(properties.getStrict()); + dataSource.setStrategy(properties.getStrategy()); + dataSource.setP6spy(properties.getP6spy()); + dataSource.setSeata(properties.getSeata()); + return dataSource; + } + + + @Bean + public DataSourceTransactionManager transactionManager(DataSource dataSource) { + return new DataSourceTransactionManager(dataSource); + } +} diff --git a/springboot/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/helper/DataBaseHelper.java b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/helper/DataBaseHelper.java new file mode 100644 index 00000000..2299365c --- /dev/null +++ b/springboot/fastbee-framework/src/main/java/com/fastbee/framework/mybatis/helper/DataBaseHelper.java @@ -0,0 +1,164 @@ +package com.fastbee.framework.mybatis.helper; + +import cn.hutool.core.convert.Convert; +import com.baomidou.dynamic.datasource.DynamicRoutingDataSource; +import com.fastbee.common.exception.ServiceException; +import com.fastbee.common.mabatis.enums.DataBaseType; +import com.fastbee.common.utils.spring.SpringUtils; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; + +/** + * 数据库助手 + * + * @author Lion Li + */ +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public class DataBaseHelper { + + private static final DynamicRoutingDataSource DS = SpringUtils.getBean(DynamicRoutingDataSource.class); + public static final String DEFAULT_DATASOURCE_NAME = "master"; + + /** + * 获取当前数据库类型 + */ + public static DataBaseType getDataBaseType(String dataName) { + DataSource dataSource = DS.getDataSources().get(dataName); + try (Connection conn = dataSource.getConnection()) { + DatabaseMetaData metaData = conn.getMetaData(); + String databaseProductName = metaData.getDatabaseProductName(); + return DataBaseType.find(databaseProductName); + } catch (SQLException e) { + throw new ServiceException(e.getMessage()); + } + } + + public static boolean isMySql() { + return DataBaseType.MY_SQL == getDataBaseType(DEFAULT_DATASOURCE_NAME); + } + + public static boolean isOracle() { + return DataBaseType.ORACLE == getDataBaseType(DEFAULT_DATASOURCE_NAME); + } + + public static boolean isPostgerSql() { + return DataBaseType.POSTGRE_SQL == getDataBaseType(DEFAULT_DATASOURCE_NAME); + } + + public static boolean isSqlServer() { + return DataBaseType.SQL_SERVER == getDataBaseType(DEFAULT_DATASOURCE_NAME); + } + + public static boolean isDm() { + return DataBaseType.DM == getDataBaseType(DEFAULT_DATASOURCE_NAME); + } + + public static boolean isMySql(String dataName) { + return DataBaseType.MY_SQL == getDataBaseType(dataName); + } + + public static boolean isOracle(String dataName) { + return DataBaseType.ORACLE == getDataBaseType(dataName); + } + + public static boolean isPostgerSql(String dataName) { + return DataBaseType.POSTGRE_SQL == getDataBaseType(dataName); + } + + public static boolean isSqlServer(String dataName) { + return DataBaseType.SQL_SERVER == getDataBaseType(dataName); + } + + public static boolean isDm(String dataName) { + return DataBaseType.DM == getDataBaseType(dataName); + } + + public static String findInSet(Object var1, String var2) { + DataBaseType dataBasyType = getDataBaseType(DEFAULT_DATASOURCE_NAME); + String var = Convert.toStr(var1); + if (dataBasyType == DataBaseType.SQL_SERVER) { + // charindex(',100,' , ',0,100,101,') <> 0 + return String.format("charindex(',%s,' , ','+%s+',') <> 0", var, var2); + } else if (dataBasyType == DataBaseType.POSTGRE_SQL) { + // (select strpos(',0,100,101,' , ',100,')) <> 0 + return String.format("(select strpos(','||%s||',' , ',%s,')) <> 0", var2, var); + } else if (dataBasyType == DataBaseType.ORACLE || dataBasyType == DataBaseType.DM) { + // instr(',0,100,101,' , ',100,') <> 0 + return String.format("instr(','||%s||',' , ',%s,') <> 0", var2, var); + } + // find_in_set(100 , '0,100,101') + return String.format("find_in_set(%s , %s) <> 0", var, var2); + } + + public static String findInSetColumn(String var1, String var2) { + DataBaseType dataBasyType = getDataBaseType(DEFAULT_DATASOURCE_NAME); + String var = Convert.toStr(var1); + if (dataBasyType == DataBaseType.SQL_SERVER) { + // charindex(','+de.dept_id+',' , ',0,100,101,') <> 0 + return String.format("charindex(',' + %s + ',' , ',' + %s + ',') <> 0", var, var2); + } else if (dataBasyType == DataBaseType.POSTGRE_SQL) { + // (select strpos(',0,100,101,' , ',' || de.dept_id || ',')) <> 0 + return String.format("(select strpos(','||%s||',' , ','|| %s ||',')) <> 0", var2, var); + } else if (dataBasyType == DataBaseType.ORACLE|| dataBasyType == DataBaseType.DM) { + // instr(',0,100,101,' , ','||de.dept_id||',') <> 0 + return String.format("instr(','||%s||',' , ','||%s||',') <> 0", var2, var); + } + // find_in_set(de.dept_id , '0,100,101') + return String.format("find_in_set(%s , '%s') <> 0", var, var2); + } + + /** + * 获取当前加载的数据库名 + */ + public static List getDataSourceNameList() { + return new ArrayList<>(DS.getDataSources().keySet()); + } + + public static String getDeptCondition(Long deptId) { + if (deptId == null || deptId == 0) { + // 无效条件,确保查询不会返回结果 + return "1=1"; + } + if (isPostgerSql()) { + return "SELECT u.user_id FROM sys_user u WHERE u.dept_id IN (SELECT dept_id FROM sys_dept WHERE " + deptId + "::text = ANY(string_to_array(ancestors, ',')) OR dept_id = " + deptId + ")"; + } else if (isSqlServer()) { + return "SELECT u.user_id FROM sys_user u WHERE u.dept_id IN (SELECT dept_id FROM sys_dept WHERE CHARINDEX(',' + CAST(" + deptId + " AS VARCHAR) + ',', ',' + ancestors + ',') > 0 OR dept_id = " + deptId + ")"; + } else if (isOracle()) { + return "SELECT u.user_id FROM sys_user u WHERE u.dept_id IN (SELECT dept_id FROM sys_dept WHERE INSTR(',' || ancestors || ',', ',' || " + deptId + " || ',') > 0 OR dept_id = " + deptId + ")"; + } else if (isDm()) { + return "SELECT u.user_id FROM sys_user u WHERE u.dept_id IN (SELECT dept_id FROM sys_dept WHERE INSTR(',' || ancestors || ',', ',' || " + deptId + " || ',') > 0 OR dept_id = " + deptId + ")"; + } else if (isMySql()) { + return "SELECT u.user_id FROM sys_user u WHERE u.dept_id IN (SELECT dept_id FROM sys_dept WHERE FIND_IN_SET(" + deptId + ", ancestors) > 0 OR dept_id = " + deptId + ")"; + } else { + throw new UnsupportedOperationException("Unsupported database type"); + } + } + + public static String checkTime(Integer timeout) { + if (timeout == null || timeout == 0) { + // 无效条件,确保查询不会返回结果 + return ""; + } + if (isPostgerSql()) { + return "CURRENT_TIMESTAMP > last_connect_time + interval '1 seconds' * " + timeout; + } else if (isSqlServer()) { + return "CURRENT_TIMESTAMP > DATEADD(SECOND, " + timeout + " last_connect_time)"; + } else if (isOracle()) { + return "CURRENT_TIMESTAMP > last_connect_time + (" + timeout + " / 86400)"; + } else if (isDm()) { + return "CURRENT_TIMESTAMP > DATEADD(SECOND, " + timeout + ", last_connect_time)"; + } else if (isMySql()) { + return "CURRENT_TIMESTAMP > DATE_ADD(last_connect_time, INTERVAL " + timeout + " SECOND)"; + } else { + throw new UnsupportedOperationException("Unsupported database type"); + } + } + +} diff --git a/springboot/fastbee-open-api/src/main/java/com/fastbee/data/service/impl/DeviceJob.java b/springboot/fastbee-open-api/src/main/java/com/fastbee/data/service/impl/DeviceJob.java index 8ae40e5f..7497f5ef 100644 --- a/springboot/fastbee-open-api/src/main/java/com/fastbee/data/service/impl/DeviceJob.java +++ b/springboot/fastbee-open-api/src/main/java/com/fastbee/data/service/impl/DeviceJob.java @@ -2,6 +2,7 @@ package com.fastbee.data.service.impl; import com.fastbee.base.session.Session; import com.fastbee.common.enums.DeviceStatus; +import com.fastbee.framework.mybatis.helper.DataBaseHelper; import com.fastbee.iot.domain.Device; import com.fastbee.iot.model.DeviceStatusVO; import com.fastbee.iot.service.IDeviceService; @@ -42,7 +43,8 @@ public class DeviceJob { private Boolean enabled; public void updateSipDeviceOnlineStatus(Integer timeout) { - List devs = sipDeviceMapper.selectOfflineSipDevice(timeout); + String checkTimeCondition = DataBaseHelper.checkTime(timeout); + List devs = sipDeviceMapper.selectOfflineSipDevice(checkTimeCondition); devs.forEach(item -> { if (!Objects.equals(item.getDeviceSipId(), "")) { //更新iot设备状态 diff --git a/springboot/fastbee-server/sip-server/src/main/java/com/fastbee/sip/mapper/SipDeviceMapper.java b/springboot/fastbee-server/sip-server/src/main/java/com/fastbee/sip/mapper/SipDeviceMapper.java index d84875f3..8a79b384 100644 --- a/springboot/fastbee-server/sip-server/src/main/java/com/fastbee/sip/mapper/SipDeviceMapper.java +++ b/springboot/fastbee-server/sip-server/src/main/java/com/fastbee/sip/mapper/SipDeviceMapper.java @@ -31,7 +31,7 @@ public interface SipDeviceMapper * @return 监控设备集合 */ public List selectSipDeviceList(SipDevice sipDevice); - public List selectOfflineSipDevice(Integer timeout); + public List selectOfflineSipDevice(String checkTimeCondition); /** * 新增监控设备 diff --git a/springboot/fastbee-server/sip-server/src/main/resources/mapper/SipDeviceMapper.xml b/springboot/fastbee-server/sip-server/src/main/resources/mapper/SipDeviceMapper.xml index 73237e0c..208f1d13 100644 --- a/springboot/fastbee-server/sip-server/src/main/resources/mapper/SipDeviceMapper.xml +++ b/springboot/fastbee-server/sip-server/src/main/resources/mapper/SipDeviceMapper.xml @@ -196,7 +196,7 @@ @@ -98,14 +98,14 @@ model, firmware, transport, - streamMode, + stream_mode, online, - registerTime, - lastConnectTime, + register_time, + last_connect_time, active_time, ip, port, - hostAddress, + host_address, del_flag, create_by, create_time, @@ -122,14 +122,14 @@ #{model}, #{firmware}, #{transport}, - #{streammode}, + #{streamMode}, #{online}, - #{registertime}, - #{lastconnecttime}, + #{registerTime}, + #{lastConnectTime}, #{activeTime}, #{ip}, #{port}, - #{hostaddress}, + #{hostAddress}, #{delFlag}, #{createBy}, #{createTime}, @@ -150,14 +150,14 @@ model = #{model}, firmware = #{firmware}, transport = #{transport}, - streamMode = #{streammode}, + stream_mode = #{streamMode}, online = #{online}, - registerTime = #{registertime}, - lastConnectTime = #{lastconnecttime}, + register_time = #{registerTime}, + last_connect_time = #{lastConnectTime}, active_time = #{activeTime}, ip = #{ip}, port = #{port}, - hostAddress = #{hostaddress}, + host_address = #{hostAddress}, del_flag = #{delFlag}, create_by = #{createBy}, create_time = #{createTime}, @@ -185,18 +185,20 @@ update sip_device online = #{online}, - lastConnectTime = #{lastconnecttime}, + last_connect_time = #{lastConnectTime}, active_time = #{activeTime}, ip = #{ip}, port = #{port}, - hostaddress = #{hostaddress}, + hostaddress = #{hostAddress}, where device_sip_id = #{deviceSipId} + + + and client_key = #{clientKey} + and client_secret = #{clientSecret} + and token = #{token} + and grant_type = #{grantType} + and device_type = #{deviceType} + and timeout = #{timeout} + and enable = #{enable} + and del_flag = '0' + + + + + + + insert into sys_client + + client_key, + client_secret, + token, + grant_type, + device_type, + timeout, + enable, + del_flag, + create_by, + create_time, + update_by, + update_time, + remark, + + + #{clientKey}, + #{clientSecret}, + #{token}, + #{grantType}, + #{deviceType}, + #{timeout}, + #{enable}, + #{delFlag}, + #{createBy}, + #{createTime}, + #{updateBy}, + #{updateTime}, + #{remark}, + + + + + update sys_client + + client_key = #{clientKey}, + client_secret = #{clientSecret}, + token = #{token}, + grant_type = #{grantType}, + device_type = #{deviceType}, + timeout = #{timeout}, + enable = #{enable}, + del_flag = #{delFlag}, + create_by = #{createBy}, + create_time = #{createTime}, + update_by = #{updateBy}, + update_time = #{updateTime}, + remark = #{remark}, + + where id = #{id} + + + From f5598f1663d24734287ea5ac42e5b23451fa6e12 Mon Sep 17 00:00:00 2001 From: gx_ma <1773945958@qq.com> Date: Wed, 23 Apr 2025 17:04:02 +0800 Subject: [PATCH 06/18] =?UTF-8?q?fix(=E5=A4=9A=E6=95=B0=E6=8D=AE=E6=BA=90)?= =?UTF-8?q?:=20=E6=8A=A5=E9=94=99=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../fastbee-iot-service/pom.xml | 16 + .../resources/mapper/iot/DeviceMapper.xml | 6 +- .../mapper/system/SysNoticeMapper.xml | 6 +- springboot/sql/dameng/fastbee-v2.1.sql | 493 ------------------ vue/.env.development | 2 +- 5 files changed, 23 insertions(+), 500 deletions(-) diff --git a/springboot/fastbee-service/fastbee-iot-service/pom.xml b/springboot/fastbee-service/fastbee-iot-service/pom.xml index 5e92c536..fa358edf 100644 --- a/springboot/fastbee-service/fastbee-iot-service/pom.xml +++ b/springboot/fastbee-service/fastbee-iot-service/pom.xml @@ -127,6 +127,22 @@ 8.1.1.49
+ + com.microsoft.sqlserver + mssql-jdbc + 8.4.1.jre8 + + + org.postgresql + postgresql + 42.5.0 + + + com.oracle.database.jdbc + ojdbc8 + 19.3.0.0 + + diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/resources/mapper/iot/DeviceMapper.xml b/springboot/fastbee-service/fastbee-iot-service/src/main/resources/mapper/iot/DeviceMapper.xml index 07830978..b8ec6ce6 100644 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/resources/mapper/iot/DeviceMapper.xml +++ b/springboot/fastbee-service/fastbee-iot-service/src/main/resources/mapper/iot/DeviceMapper.xml @@ -297,7 +297,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" select log_value, create_time from iot_device_log and is_monitor=1 - and identity = #{identity} + and identify = #{identity} and device_id = #{deviceId} and serial_number = #{serialNumber} and create_time between #{beginTime} and #{endTime} @@ -96,7 +96,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - insert into iot_device_log (log_type,log_value,device_id,device_name,serial_number,identity,create_by, + insert into iot_device_log (log_type,log_value,device_id,device_name,serial_number,identify,create_by, is_monitor,mode,create_time,remark,user_id,user_name,tenant_id,tenant_name,model_name) values @@ -114,7 +114,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" device_id = #{deviceId}, device_name = #{deviceName}, serial_number = #{serialNumber}, - identity = #{identity}, + identify = #{identity}, create_by = #{createBy}, is_monitor = #{isMonitor}, mode = #{mode}, diff --git a/springboot/fastbee-service/fastbee-iot-service/src/main/resources/mapper/iot/EventLogMapper.xml b/springboot/fastbee-service/fastbee-iot-service/src/main/resources/mapper/iot/EventLogMapper.xml index 6696c7ce..896a7c32 100644 --- a/springboot/fastbee-service/fastbee-iot-service/src/main/resources/mapper/iot/EventLogMapper.xml +++ b/springboot/fastbee-service/fastbee-iot-service/src/main/resources/mapper/iot/EventLogMapper.xml @@ -6,7 +6,7 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - + @@ -25,13 +25,13 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" - select log_id, identity, model_name, log_type, log_value, device_id, device_name, serial_number, is_monitor, mode, user_id, user_name, tenant_id, tenant_name, create_by, create_time, remark from iot_event_log + select log_id, identify, model_name, log_type, log_value, device_id, device_name, serial_number, is_monitor, mode, user_id, user_name, tenant_id, tenant_name, create_by, create_time, remark from iot_event_log diff --git a/springboot/sql/dameng/fastbee-v2.1.sql b/springboot/sql/dameng/fastbee-v2.1.sql index 34b6a384..58dbb7e7 100644 --- a/springboot/sql/dameng/fastbee-v2.1.sql +++ b/springboot/sql/dameng/fastbee-v2.1.sql @@ -908,7 +908,7 @@ CREATE TABLE "IOT_DEVICE_JOB" CREATE TABLE "IOT_DEVICE_LOG" ( "LOG_ID" BIGINT IDENTITY(1,1) NOT NULL, - "IDENTITY" VARCHAR(64) NOT NULL, + "IDENTIFY" VARCHAR(64) NOT NULL, "MODEL_NAME" VARCHAR(255) NULL, "LOG_TYPE" TINYINT NOT NULL, "LOG_VALUE" VARCHAR(64) NOT NULL, @@ -962,7 +962,7 @@ CREATE TABLE "IOT_DEVICE_USER" CREATE TABLE "IOT_EVENT_LOG" ( "LOG_ID" BIGINT IDENTITY(1,1) NOT NULL, - "IDENTITY" VARCHAR(64) NOT NULL, + "IDENTIFY" VARCHAR(64) NOT NULL, "MODEL_NAME" VARCHAR(255) NULL, "LOG_TYPE" TINYINT NOT NULL, "LOG_VALUE" VARCHAR(64) NOT NULL, diff --git a/springboot/sql/fastbee.sql b/springboot/sql/fastbee.sql index b827923d..6d798905 100644 --- a/springboot/sql/fastbee.sql +++ b/springboot/sql/fastbee.sql @@ -230,7 +230,7 @@ INSERT INTO `iot_device_job` VALUES (5, '告警定时触发', 'DEFAULT', '0 13 1 DROP TABLE IF EXISTS `iot_device_log`; CREATE TABLE `iot_device_log` ( `log_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '设备监测信息ID', - `identity` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '标识符', + `identify` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '标识符', `model_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '物模型名称', `log_type` tinyint(1) NOT NULL COMMENT '类型(1=属性上报,2=调用功能,3=事件上报,4=设备升级,5=设备上线,6=设备离线)', `log_value` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '日志值', @@ -327,7 +327,7 @@ INSERT INTO `iot_device_user` VALUES (140, 1, 1, 'admin', '¥视频监控', '15 DROP TABLE IF EXISTS `iot_event_log`; CREATE TABLE `iot_event_log` ( `log_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '设备事件日志ID', - `identity` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '标识符', + `identify` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '标识符', `model_name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '物模型名称', `log_type` tinyint(1) NOT NULL COMMENT '类型(3=事件上报,5=设备上线,6=设备离线)', `log_value` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '日志值', diff --git a/springboot/sql/postgres/fastbee-v2.1.sql b/springboot/sql/postgres/fastbee-v2.1.sql index e3bdf07f..c4767851 100644 --- a/springboot/sql/postgres/fastbee-v2.1.sql +++ b/springboot/sql/postgres/fastbee-v2.1.sql @@ -349,7 +349,7 @@ COMMIT; DROP TABLE IF EXISTS "public"."iot_device_log"; CREATE TABLE "public"."iot_device_log" ( "log_id" int8 NOT NULL, - "identity" varchar(64) NOT NULL, + "identify" varchar(64) NOT NULL, "model_name" varchar(255), "log_type" int2 NOT NULL, "log_value" varchar(64) NOT NULL, @@ -368,7 +368,7 @@ CREATE TABLE "public"."iot_device_log" ( ) ; COMMENT ON COLUMN "public"."iot_device_log"."log_id" IS '设备监测信息ID'; -COMMENT ON COLUMN "public"."iot_device_log"."identity" IS '标识符'; +COMMENT ON COLUMN "public"."iot_device_log"."identify" IS '标识符'; COMMENT ON COLUMN "public"."iot_device_log"."model_name" IS '物模型名称'; COMMENT ON COLUMN "public"."iot_device_log"."log_type" IS '类型(1=属性上报,2=调用功能,3=事件上报,4=设备升级,5=设备上线,6=设备离线)'; COMMENT ON COLUMN "public"."iot_device_log"."log_value" IS '日志值'; @@ -482,7 +482,7 @@ COMMIT; DROP TABLE IF EXISTS "public"."iot_event_log"; CREATE TABLE "public"."iot_event_log" ( "log_id" int8 NOT NULL, - "identity" varchar(64) NOT NULL, + "identify" varchar(64) NOT NULL, "model_name" varchar(255), "log_type" int2 NOT NULL, "log_value" varchar(64) NOT NULL, @@ -501,7 +501,7 @@ CREATE TABLE "public"."iot_event_log" ( ) ; COMMENT ON COLUMN "public"."iot_event_log"."log_id" IS '设备事件日志ID'; -COMMENT ON COLUMN "public"."iot_event_log"."identity" IS '标识符'; +COMMENT ON COLUMN "public"."iot_event_log"."identify" IS '标识符'; COMMENT ON COLUMN "public"."iot_event_log"."model_name" IS '物模型名称'; COMMENT ON COLUMN "public"."iot_event_log"."log_type" IS '类型(3=事件上报,5=设备上线,6=设备离线)'; COMMENT ON COLUMN "public"."iot_event_log"."log_value" IS '日志值'; diff --git a/springboot/sql/sqlserver/fastbee-v2.1.sql b/springboot/sql/sqlserver/fastbee-v2.1.sql index 6cdb34f6..99cfa972 100644 --- a/springboot/sql/sqlserver/fastbee-v2.1.sql +++ b/springboot/sql/sqlserver/fastbee-v2.1.sql @@ -1093,7 +1093,7 @@ GO CREATE TABLE [dbo].[iot_device_log] ( [log_id] bigint NOT NULL, - [identity] nvarchar(64) NOT NULL, + [identify] nvarchar(64) NOT NULL, [model_name] nvarchar(255) NULL, [log_type] tinyint NOT NULL, [log_value] nvarchar(64) NOT NULL, @@ -1123,7 +1123,7 @@ EXEC sp_addextendedproperty 'MS_Description', N'标识符', 'SCHEMA', N'dbo', 'TABLE', N'iot_device_log', -'COLUMN', N'identity' +'COLUMN', N'identify' GO EXEC sp_addextendedproperty @@ -1463,7 +1463,7 @@ GO CREATE TABLE [dbo].[iot_event_log] ( [log_id] bigint NOT NULL, - [identity] nvarchar(64) NOT NULL, + [identify] nvarchar(64) NOT NULL, [model_name] nvarchar(255) NULL, [log_type] tinyint NOT NULL, [log_value] nvarchar(64) NOT NULL, @@ -1493,7 +1493,7 @@ EXEC sp_addextendedproperty 'MS_Description', N'标识符', 'SCHEMA', N'dbo', 'TABLE', N'iot_event_log', -'COLUMN', N'identity' +'COLUMN', N'identify' GO EXEC sp_addextendedproperty From 00f5c882e24cce0b63fd8313c3b7f6e15ac69959 Mon Sep 17 00:00:00 2001 From: Zhu <2698076424@qq.com> Date: Thu, 24 Apr 2025 15:47:04 +0800 Subject: [PATCH 10/18] =?UTF-8?q?fix(=E7=94=9F=E6=88=90=E4=BB=A3=E7=A0=81)?= =?UTF-8?q?:=20=E6=96=B0=E5=A2=9E=E6=95=B0=E6=8D=AE=E6=BA=90=E7=9A=84?= =?UTF-8?q?=E6=98=BE=E7=A4=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- vue/src/api/tool/gen.js | 8 ++++++++ vue/src/views/tool/gen/importTable.vue | 19 +++++++++++++++++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/vue/src/api/tool/gen.js b/vue/src/api/tool/gen.js index 45069278..c44638e0 100644 --- a/vue/src/api/tool/gen.js +++ b/vue/src/api/tool/gen.js @@ -74,3 +74,11 @@ export function synchDb(tableName) { method: 'get' }) } + +// 查询数据源列表 +export function listDataSource() { + return request({ + url: '/tool/gen/getDataNames', + method: 'get', + }); +} \ No newline at end of file diff --git a/vue/src/views/tool/gen/importTable.vue b/vue/src/views/tool/gen/importTable.vue index 3ea9532b..27a0c586 100644 --- a/vue/src/views/tool/gen/importTable.vue +++ b/vue/src/views/tool/gen/importTable.vue @@ -2,6 +2,11 @@ + + + + + @@ -55,7 +71,21 @@ export default { // fix css style bug in open el-dialog .el-popup-parent--hidden { .fixed-header { - padding-right: 17px; + padding-right: 6px; } } + +::-webkit-scrollbar { + width: 6px; + height: 6px; +} + +::-webkit-scrollbar-track { + background-color: #f1f1f1; +} + +::-webkit-scrollbar-thumb { + background-color: #c0c0c0; + border-radius: 3px; +} diff --git a/vue/src/plugins/cache.js b/vue/src/plugins/cache.js index 6b5c00b9..b67d453f 100644 --- a/vue/src/plugins/cache.js +++ b/vue/src/plugins/cache.js @@ -26,6 +26,7 @@ const sessionCache = { if (value != null) { return JSON.parse(value) } + return null }, remove (key) { sessionStorage.removeItem(key); @@ -59,6 +60,7 @@ const localCache = { if (value != null) { return JSON.parse(value) } + return null }, remove (key) { localStorage.removeItem(key); diff --git a/vue/src/plugins/download.js b/vue/src/plugins/download.js index a3bb8c4f..42acd006 100644 --- a/vue/src/plugins/download.js +++ b/vue/src/plugins/download.js @@ -1,11 +1,12 @@ import axios from 'axios' -import { Message } from 'element-ui' +import {Loading, Message} from 'element-ui' import { saveAs } from 'file-saver' import { getToken } from '@/utils/auth' import errorCode from '@/utils/errorCode' import { blobValidate } from "@/utils/ruoyi"; const baseURL = process.env.VUE_APP_BASE_API +let downloadLoadingInstance; export default { name(name, isDelete = true) { @@ -15,9 +16,9 @@ export default { url: url, responseType: 'blob', headers: { 'Authorization': 'Bearer ' + getToken() } - }).then(async (res) => { - const isLogin = await blobValidate(res.data); - if (isLogin) { + }).then((res) => { + const isBlob = blobValidate(res.data); + if (isBlob) { const blob = new Blob([res.data]) this.saveAs(blob, decodeURIComponent(res.headers['download-filename'])) } else { @@ -32,9 +33,9 @@ export default { url: url, responseType: 'blob', headers: { 'Authorization': 'Bearer ' + getToken() } - }).then(async (res) => { - const isLogin = await blobValidate(res.data); - if (isLogin) { + }).then((res) => { + const isBlob = blobValidate(res.data); + if (isBlob) { const blob = new Blob([res.data]) this.saveAs(blob, decodeURIComponent(res.headers['download-filename'])) } else { @@ -44,19 +45,25 @@ export default { }, zip(url, name) { var url = baseURL + url + downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", }) axios({ method: 'get', url: url, responseType: 'blob', headers: { 'Authorization': 'Bearer ' + getToken() } - }).then(async (res) => { - const isLogin = await blobValidate(res.data); - if (isLogin) { + }).then((res) => { + const isBlob = blobValidate(res.data); + if (isBlob) { const blob = new Blob([res.data], { type: 'application/zip' }) this.saveAs(blob, name) } else { this.printErrMsg(res.data); } + downloadLoadingInstance.close(); + }).catch((r) => { + console.error(r) + Message.error('下载文件出现错误,请联系管理员!') + downloadLoadingInstance.close(); }) }, saveAs(text, name, opts) { diff --git a/vue/src/plugins/tab.js b/vue/src/plugins/tab.js index cade9f75..fcde4197 100644 --- a/vue/src/plugins/tab.js +++ b/vue/src/plugins/tab.js @@ -32,8 +32,12 @@ export default { // 关闭指定tab页签 closePage(obj) { if (obj === undefined) { - return store.dispatch('tagsView/delView', router.currentRoute).then(({ lastPath }) => { - return router.push(lastPath || '/'); + return store.dispatch('tagsView/delView', router.currentRoute).then(({ visitedViews }) => { + const latestView = visitedViews.slice(-1)[0] + if (latestView) { + return router.push(latestView.fullPath) + } + return router.push('/'); }); } return store.dispatch('tagsView/delView', obj); @@ -56,7 +60,7 @@ export default { }, // 添加tab页签 openPage(title, url, params) { - var obj = { path: url, meta: { title: title } } + const obj = { path: url, meta: { title: title } } store.dispatch('tagsView/addView', obj); return router.push({ path: url, query: params }); }, diff --git a/vue/src/store/modules/user.js b/vue/src/store/modules/user.js index fb516f3d..63e6ba2e 100644 --- a/vue/src/store/modules/user.js +++ b/vue/src/store/modules/user.js @@ -1,109 +1,106 @@ -import { login, logout, getInfo } from '@/api/login'; -import { getToken, setToken, removeToken, setUserId, removeUserId } from '@/utils/auth'; +import { login, logout, getInfo } from '@/api/login' +import { getToken, setToken, removeToken } from '@/utils/auth' +import { isHttp, isEmpty } from "@/utils/validate" +import defAva from '@/assets/images/profile.jpg' const user = { state: { token: getToken(), + id: '', name: '', avatar: '', roles: [], - permissions: [], + permissions: [] }, mutations: { SET_TOKEN: (state, token) => { - state.token = token; + state.token = token + }, + SET_ID: (state, id) => { + state.id = id }, SET_NAME: (state, name) => { - state.name = name; + state.name = name }, SET_AVATAR: (state, avatar) => { - state.avatar = avatar; + state.avatar = avatar }, SET_ROLES: (state, roles) => { - state.roles = roles; + state.roles = roles }, SET_PERMISSIONS: (state, permissions) => { - state.permissions = permissions; - }, - SET_MQTT: (state, mqtt) => { - state.mqtt = mqtt; - }, + state.permissions = permissions + } }, actions: { // 登录 Login({ commit }, userInfo) { - const username = userInfo.username.trim(); - const password = userInfo.password; - const code = userInfo.code; - const uuid = userInfo.uuid; + const username = userInfo.username.trim() + const password = userInfo.password + const code = userInfo.code + const uuid = userInfo.uuid return new Promise((resolve, reject) => { - login(username, password, code, uuid) - .then((res) => { - setToken(res.token); - commit('SET_TOKEN', res.token); - resolve(); - }) - .catch((error) => { - reject(error); - }); - }); + login(username, password, code, uuid).then(res => { + setToken(res.token) + commit('SET_TOKEN', res.token) + resolve() + }).catch(error => { + reject(error) + }) + }) }, // 获取用户信息 GetInfo({ commit, state }) { return new Promise((resolve, reject) => { - getInfo() - .then((res) => { - const user = res.user; - const avatar = user.avatar === '' || user.avatar == null ? require('@/assets/images/profile.jpg') : process.env.VUE_APP_BASE_API + user.avatar; - if (res.roles && res.roles.length > 0) { - // 验证返回的roles是否是一个非空数组 - commit('SET_ROLES', res.roles); - commit('SET_PERMISSIONS', res.permissions); - } else { - commit('SET_ROLES', ['ROLE_DEFAULT']); - } - commit('SET_NAME', user.userName); - commit('SET_AVATAR', avatar); - commit('SET_MQTT', res.mqtt); - setUserId(user.userId); - resolve(res); - }) - .catch((error) => { - reject(error); - }); - }); + getInfo().then(res => { + const user = res.user + let avatar = user.avatar || "" + if (!isHttp(avatar)) { + avatar = (isEmpty(avatar)) ? defAva : process.env.VUE_APP_BASE_API + avatar + } + if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组 + commit('SET_ROLES', res.roles) + commit('SET_PERMISSIONS', res.permissions) + } else { + commit('SET_ROLES', ['ROLE_DEFAULT']) + } + commit('SET_ID', user.userId) + commit('SET_NAME', user.userName) + commit('SET_AVATAR', avatar) + resolve(res) + }).catch(error => { + reject(error) + }) + }) }, // 退出系统 LogOut({ commit, state }) { return new Promise((resolve, reject) => { - logout(state.token) - .then(() => { - commit('SET_TOKEN', ''); - commit('SET_ROLES', []); - commit('SET_PERMISSIONS', []); - removeToken(); - removeUserId(); - resolve(); - }) - .catch((error) => { - reject(error); - }); - }); + logout(state.token).then(() => { + commit('SET_TOKEN', '') + commit('SET_ROLES', []) + commit('SET_PERMISSIONS', []) + removeToken() + resolve() + }).catch(error => { + reject(error) + }) + }) }, // 前端 登出 FedLogOut({ commit }) { - return new Promise((resolve) => { - commit('SET_TOKEN', ''); - removeToken(); - resolve(); - }); - }, - }, -}; + return new Promise(resolve => { + commit('SET_TOKEN', '') + removeToken() + resolve() + }) + } + } +} -export default user; +export default user diff --git a/vue/src/utils/permission.js b/vue/src/utils/permission.js index 1730e332..189a7162 100644 --- a/vue/src/utils/permission.js +++ b/vue/src/utils/permission.js @@ -15,10 +15,8 @@ export function checkPermi(value) { return all_permission === permission || permissionDatas.includes(permission) }) - if (!hasPermission) { - return false - } - return true + return hasPermission; + } else { console.error(`need roles! Like checkPermi="['system:user:add','system:user:edit']"`) return false @@ -40,10 +38,8 @@ export function checkRole(value) { return super_admin === role || permissionRoles.includes(role) }) - if (!hasRole) { - return false - } - return true + return hasRole; + } else { console.error(`need roles! Like checkRole="['admin','editor']"`) return false diff --git a/vue/src/utils/validate.js b/vue/src/utils/validate.js index 558e9a8e..6a4c0c5d 100644 --- a/vue/src/utils/validate.js +++ b/vue/src/utils/validate.js @@ -1,4 +1,38 @@ /** + * 路径匹配器 + * @param {string} pattern + * @param {string} path + * @returns {Boolean} + */ +export function isPathMatch(pattern, path) { + const regexPattern = pattern.replace(/\//g, '\\/').replace(/\*\*/g, '.*').replace(/\*/g, '[^\\/]*') + const regex = new RegExp(`^${regexPattern}$`) + return regex.test(path) +} + +/** + * 判断value字符串是否为空 + * @param {string} value + * @returns {Boolean} + */ +export function isEmpty(value) { + if (value == null || value == "" || value == undefined || value == "undefined") { + return true + } + return false +} + +/** + * 判断url是否是http或https + * @param {string} url + * @returns {Boolean} + */ +export function isHttp(url) { + return url.indexOf('http://') !== -1 || url.indexOf('https://') !== -1 +} + +/** + * 判断path是否为外链 * @param {string} path * @returns {Boolean} */ @@ -65,10 +99,7 @@ export function validEmail(email) { * @returns {Boolean} */ export function isString(str) { - if (typeof str === 'string' || str instanceof String) { - return true - } - return false + return typeof str === 'string' || str instanceof String } /** @@ -81,34 +112,3 @@ export function isArray(arg) { } return Array.isArray(arg) } -//ֵΧУ -export function checkNumber(rule, value, callback) { - if (!value) { - return callback(new Error('벻Ϊ')); - } - setTimeout(() => { - if (!Number(value)) { - } else { - if (value < 1 || value > 64) { - callback(new Error('ֵΧΪ1-64')); - } else { - callback(); - } - } - }, 100); -} -export function checkNumberAddr(rule, value, callback) { - if (!value) { - return callback(new Error('벻Ϊ')); - } - setTimeout(() => { - if (!Number(value)) { - } else { - if (value < 1 || value > 65536) { - callback(new Error('ֵΧΪ1-65536')); - } else { - callback(); - } - } - }, 100); -} diff --git a/vue/src/views/dashboard/LineChart.vue b/vue/src/views/dashboard/LineChart.vue index ddd1063d..702ff73f 100644 --- a/vue/src/views/dashboard/LineChart.vue +++ b/vue/src/views/dashboard/LineChart.vue @@ -3,7 +3,7 @@ \ No newline at end of file + diff --git a/vue/src/views/system/config/index.vue b/vue/src/views/system/config/index.vue index f580b983..6bde2ee0 100644 --- a/vue/src/views/system/config/index.vue +++ b/vue/src/views/system/config/index.vue @@ -107,7 +107,7 @@ - +