Quellcode durchsuchen

修改用户缓存

wangliang vor 4 Jahren
Ursprung
Commit
33f6bb4b25

+ 5 - 4
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/SysUserService.java

@@ -8,6 +8,7 @@ import com.qmth.distributed.print.business.bean.dto.UserDto;
 import com.qmth.distributed.print.business.bean.params.UserSaveParams;
 import com.qmth.distributed.print.business.entity.SysUser;
 
+import java.security.NoSuchAlgorithmException;
 import java.util.List;
 
 /**
@@ -24,11 +25,11 @@ public interface SysUserService extends IService<SysUser> {
 
     boolean saveUser(UserSaveParams userSaveParams);
 
-    boolean enable(SysUser user);
+    boolean enable(SysUser user) throws NoSuchAlgorithmException;
 
-    boolean resetPassword(Long id);
+    boolean resetPassword(Long id) throws NoSuchAlgorithmException;
 
-    boolean updatePassword(SysUser user);
+    boolean updatePassword(SysUser user) throws NoSuchAlgorithmException;
 
     boolean bindRoles(SysUser sysUser);
 
@@ -38,7 +39,7 @@ public interface SysUserService extends IService<SysUser> {
 
     List<SysUser> listByOrgId(Long id);
 
-    boolean saveCustomer(SysUser user);
+    boolean saveCustomer(UserSaveParams userSaveParams);
 
     IPage<UserDto> listCustomer(String realName, Boolean enable, Integer pageNumber, Integer pageSize);
 }

+ 100 - 214
distributed-print-business/src/main/java/com/qmth/distributed/print/business/service/impl/SysUserServiceImpl.java

@@ -17,7 +17,6 @@ import com.qmth.distributed.print.business.enums.RoleTypeEnum;
 import com.qmth.distributed.print.business.mapper.SysUserMapper;
 import com.qmth.distributed.print.business.service.*;
 import com.qmth.distributed.print.business.util.ServletUtil;
-import com.qmth.distributed.print.common.contant.SystemConstant;
 import com.qmth.distributed.print.common.enums.ExceptionResultEnum;
 import com.qmth.distributed.print.common.util.ResultUtil;
 import org.apache.commons.lang3.StringUtils;
@@ -28,6 +27,7 @@ import org.springframework.transaction.annotation.Transactional;
 import sun.misc.BASE64Encoder;
 
 import javax.annotation.Resource;
+import java.security.NoSuchAlgorithmException;
 import java.util.*;
 import java.util.stream.Collectors;
 
@@ -89,171 +89,44 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
         return userDtoIPage;
     }
 
-
     @Transactional
     @Override
     public boolean saveUser(UserSaveParams userSaveParams) {
-//        Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
-//        user.setSchoolId(schoolId);
-//        SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
-//
-//        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
-//        queryWrapper.lambda().eq(SysUser::getLoginName, user.getLoginName());
-//        SysUser sysUser = this.getOne(queryWrapper);
-//        boolean isSuccess;
-//        // 新增
-//        if (Objects.isNull(user.getId())) {
-//            if (sysUser != null) {
-//                throw ExceptionResultEnum.ERROR.exception("用户名已存在");
-//            }
-//            SysConfig sysConfig = sysConfigService.getByKey("sys.user.initPassword");
-//            BASE64Encoder encoder = new BASE64Encoder();
-//            user.setPassword(encoder.encode(StringUtils.isNoneBlank(sysConfig.getConfigValue()) ? sysConfig.getConfigValue().getBytes() : "123456".getBytes()));
-//            user.setId(SystemConstant.getDbUuid());
-//            user.setCreateId(sysUser1.getId());
-//            user.setCreateTime(System.currentTimeMillis());
-//            isSuccess = this.save(user);
-//        }
-//        // 修改
-//        else {
-//            if (sysUser != null && user.getId().longValue() != sysUser.getId().longValue()) {
-//                throw ExceptionResultEnum.ERROR.exception("用户名已存在");
-//            }
-//            sysUser.setRealName(user.getRealName());
-//            sysUser.setMobileNumber(user.getMobileNumber());
-//            sysUser.setOrgId(user.getOrgId());
-//            sysUser.setUpdateId(sysUser1.getId());
-//            sysUser.setUpdateTime(System.currentTimeMillis());
-//            isSuccess = this.updateById(sysUser);
-//
-//            //删除角色
-//            UpdateWrapper<SysUserRole> updateWrapper = new UpdateWrapper<>();
-//            updateWrapper.lambda().eq(SysUserRole::getUserId, sysUser.getId());
-//
-//            //删除课程
-//            basicUserCourseService.removeByUserId(sysUser.getId());
-//
-//            sysUserRoleService.remove(updateWrapper);
-//        }
-//
-//        //新增用户-角色
-//        for (Long roleId : user.getRoleIds()) {
-//            List<SysRolePrivilege> rolePrivileges = sysRolePrivilegeService.listByRoleId(roleId);
-//            for (SysRolePrivilege rolePrivilege : rolePrivileges) {
-//                SysUserRole userRole = new SysUserRole();
-//                userRole.setUserId(user.getId());
-//                userRole.setRoleId(roleId);
-//                userRole.setPrivilegeId(rolePrivilege.getPrivilegeId());
-//                sysUserRoleService.save(userRole);
-//            }
-////            cacheService.removeRolePrivilegeCache(roleId);
-//        }
-//
-//        // 角色里是否有考务老师角色
-//        List<SysRole> sysRoles = sysRoleService.list(user.getRoleIds(), RoleTypeEnum.QUESTION_TEACHER.name());
-//        if (sysRoles != null && sysRoles.size() > 0) {
-//            Long[] courseIds = user.getCourseIds();
-//            if (courseIds.length == 0) {
-//                throw ExceptionResultEnum.ERROR.exception("请选择课程");
-//            }
-//
-//            basicUserCourseService.saveBatch(user);
-//
-//        }
-//
-//        // 清除缓存
-////        cacheService.removeUserAuthCache(user.getId());
-        boolean isSuccess = true;
-        try {
-            Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
-            SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
-            Gson gson = new Gson();
-            userSaveParams.setSchoolId(schoolId);
-            SysUser sysUser = gson.fromJson(gson.toJson(userSaveParams), SysUser.class);
-            if (Objects.isNull(sysUser.getId())) {//新增用户
-                sysUser.setInsertInfo(requestUser.getId());
-                sysUserService.save(sysUser);
-                for (Long roleId : userSaveParams.getRoleIds()) {
-                    commonService.addUserRolePrivilege(sysUser, roleId);
-                }
-            } else {//修改用户
-                List<SysUserRole> sysUserRoleList = cacheService.userRolePrivilegeCache(sysUser.getId());
-                List<Long> userRolesList = Arrays.asList(userSaveParams.getRoleIds());
-                List<Long> dbUserRolesList = sysUserRoleList.stream().map(SysUserRole::getRoleId).distinct().collect(Collectors.toList());
-                int count = (int) dbUserRolesList.stream().filter(s -> userRolesList.contains(s)).count();
-                SysUser dbUser = sysUserService.getById(sysUser.getId());
-                sysUser.setUpdateInfo(requestUser.getId());
-                sysUserService.updateById(sysUser);
-                if (count == 0 || dbUserRolesList.size() != userRolesList.size()) {
-                    QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
-                    sysUserRoleQueryWrapper.lambda().eq(SysUserRole::getUserId, sysUser.getId());
-                    sysUserRoleService.remove(sysUserRoleQueryWrapper);
-
-                    cacheService.removeUserRolePrivilegeCache(sysUser.getId());
-                    for (Long roleId : userSaveParams.getRoleIds()) {
-                        commonService.addUserRolePrivilege(sysUser, roleId);
-                    }
-                }
-                //如果修改了角色,需要重新登录
-                if (count == 0 || dbUserRolesList.size() != userRolesList.size()) {
-                    commonService.removeUserInfo(sysUser.getId());
-                }
-                //如果修改了机构,需更新用户缓存
-                if (dbUser.getOrgId().longValue() != sysUser.getOrgId().longValue()) {
-                    cacheService.updateUserCache(sysUser.getId());
-                    cacheService.updateUserAuthCache(sysUser.getId());
-                }
-            }
-            //用户科目全量删除全量增加
-            QueryWrapper<BasicUserCourse> basicUserCourseQueryWrapper = new QueryWrapper<>();
-            basicUserCourseQueryWrapper.lambda().eq(BasicUserCourse::getUserId, sysUser.getId());
-            basicUserCourseService.remove(basicUserCourseQueryWrapper);
-
-            List<SysRole> sysRoles = sysRoleService.list(sysUser.getRoleIds(), RoleTypeEnum.QUESTION_TEACHER.name());
-            if (sysRoles != null && sysRoles.size() > 0) {
-                Long[] courseIds = sysUser.getCourseIds();
-                if (courseIds.length == 0) {
-                    throw ExceptionResultEnum.ERROR.exception("请选择课程");
-                }
-                basicUserCourseService.saveBatch(sysUser);
-            }
-        } catch (Exception e) {
-            log.error("请求出错", e);
-            isSuccess = false;
-            if (e instanceof DuplicateKeyException) {
-                String errorColumn = e.getCause().toString();
-                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
-                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
-            } else if (e instanceof ApiException) {
-                ResultUtil.error((ApiException) e, e.getMessage());
-            } else {
-                ResultUtil.error(e.getMessage());
-            }
-        }
-        return isSuccess;
+        return saveUserCommon(userSaveParams);
     }
 
     @Override
-    public boolean enable(SysUser user) {
+    public boolean enable(SysUser user) throws NoSuchAlgorithmException {
         UpdateWrapper<SysUser> updateWrapper = new UpdateWrapper<>();
         updateWrapper.lambda().set(SysUser::getEnable, user.getEnable()).eq(SysUser::getId, user.getId());
-        return this.update(updateWrapper);
+
+        boolean success = this.update(updateWrapper);
+        //如果状态为禁用,需要踢下线重新登录
+        if (!user.getEnable()) {
+            commonService.removeUserInfo(user.getId());
+        }
+        return success;
     }
 
     @Override
-    public boolean resetPassword(Long id) {
+    public boolean resetPassword(Long id) throws NoSuchAlgorithmException {
         SysConfig sysConfig = sysConfigService.getByKey("sys.user.initPassword");
         BASE64Encoder encoder = new BASE64Encoder();
         String md5Password = encoder.encode(StringUtils.isNoneBlank(sysConfig.getConfigValue()) ? sysConfig.getConfigValue().getBytes() : "123456".getBytes());
 
         SysUser user = this.getById(id);
+        String oldPassword = user.getPassword();
         user.setPassword(md5Password);
 
+        //如果原密码和旧密码不一致,需要重新登录
+        if (!Objects.equals(user.getOldPassword(), oldPassword)) {
+            commonService.removeUserInfo(user.getId());
+        }
         return this.updateById(user);
     }
 
     @Override
-    public boolean updatePassword(SysUser user) {
+    public boolean updatePassword(SysUser user) throws NoSuchAlgorithmException {
         SysUser sysUser = this.getById(user.getId());
         if (sysUser == null) {
             throw ExceptionResultEnum.ERROR.exception("用户不存在");
@@ -262,7 +135,12 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
             throw ExceptionResultEnum.ERROR.exception("原密码不正确");
         }
         sysUser.setPassword(user.getPassword());
-        return this.updateById(sysUser);
+        boolean success = this.updateById(sysUser);
+        //如果原密码和旧密码不一致,需要重新登录
+        if (!Objects.equals(user.getOldPassword(), sysUser.getPassword())) {
+            commonService.removeUserInfo(sysUser.getId());
+        }
+        return success;
     }
 
     @Transactional
@@ -340,64 +218,8 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
 
     @Transactional
     @Override
-    public boolean saveCustomer(SysUser user) {
-        SysUser sysUser1 = (SysUser) ServletUtil.getRequestUser();
-
-        QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
-        queryWrapper.lambda().eq(SysUser::getLoginName, user.getLoginName());
-        SysUser sysUser = this.getOne(queryWrapper);
-        boolean isSuccess;
-        // 新增
-        if (Objects.isNull(user.getId())) {
-            if (sysUser != null) {
-                throw ExceptionResultEnum.ERROR.exception("用户名已存在");
-            }
-            SysConfig sysConfig = sysConfigService.getByKey("sys.user.initPassword");
-            BASE64Encoder encoder = new BASE64Encoder();
-            user.setPassword(encoder.encode(StringUtils.isNoneBlank(sysConfig.getConfigValue()) ? sysConfig.getConfigValue().getBytes() : "123456".getBytes()));
-            user.setId(SystemConstant.getDbUuid());
-            user.setCreateId(sysUser1.getId());
-            user.setCreateTime(System.currentTimeMillis());
-            isSuccess = this.save(user);
-        }
-        // 修改
-        else {
-            if (sysUser != null && user.getId().longValue() != sysUser.getId().longValue()) {
-                throw ExceptionResultEnum.ERROR.exception("用户名已存在");
-            }
-            sysUser.setRealName(user.getRealName());
-            sysUser.setMobileNumber(user.getMobileNumber());
-            sysUser.setUpdateId(sysUser1.getId());
-            sysUser.setUpdateTime(System.currentTimeMillis());
-            isSuccess = this.updateById(sysUser);
-
-            //删除角色
-            UpdateWrapper<SysUserRole> updateWrapper = new UpdateWrapper<>();
-            updateWrapper.lambda().eq(SysUserRole::getUserId, sysUser.getId());
-            sysUserRoleService.remove(updateWrapper);
-        }
-
-        //新增用户-角色
-        for (Long roleId : user.getRoleIds()) {
-            SysRole sysRole = sysRoleService.getById(roleId);
-            if (!RoleTypeEnum.CUSTOMER.name().equals(sysRole.getType().name())) {
-                throw ExceptionResultEnum.ERROR.exception("只能添加客服角色的用户");
-            }
-            List<SysRolePrivilege> rolePrivileges = sysRolePrivilegeService.listByRoleId(roleId);
-            for (SysRolePrivilege rolePrivilege : rolePrivileges) {
-                SysUserRole userRole = new SysUserRole();
-                userRole.setUserId(user.getId());
-                userRole.setRoleId(roleId);
-                userRole.setPrivilegeId(rolePrivilege.getPrivilegeId());
-                sysUserRoleService.save(userRole);
-            }
-            cacheService.removeRolePrivilegeCache(roleId);
-        }
-
-        // 清除缓存
-        cacheService.removeUserAuthCache(user.getId());
-
-        return isSuccess;
+    public boolean saveCustomer(UserSaveParams userSaveParams) {
+        return saveUserCommon(userSaveParams);
     }
 
     @Override
@@ -418,16 +240,80 @@ public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> impl
         return userDtoIPage;
     }
 
-    public static void main(String[] args) {
-        Long[] longs = new Long[]{1L, 2L};
-        List<Long> longList = new ArrayList<>();
-        longList.add(4L);
-        longList.add(3L);
-        longList.add(5L);
-        longList.add(1L);
-        List<Long> longList1 = Arrays.asList(longs);
-        int count = (int) longList.stream().filter(s -> longList1.contains(s)).count();
-        System.out.println(count);
-//        Arrays.asList(longs);
+    /**
+     * 保存用户公用
+     *
+     * @param userSaveParams
+     * @return
+     */
+    public boolean saveUserCommon(UserSaveParams userSaveParams) {
+        boolean isSuccess = true;
+        try {
+            Long schoolId = Long.valueOf(ServletUtil.getRequestHeaderSchoolId().toString());
+            SysUser requestUser = (SysUser) ServletUtil.getRequestUser();
+            Gson gson = new Gson();
+            userSaveParams.setSchoolId(schoolId);
+            SysUser sysUser = gson.fromJson(gson.toJson(userSaveParams), SysUser.class);
+            if (Objects.isNull(sysUser.getId())) {//新增用户
+                sysUser.setInsertInfo(requestUser.getId());
+                sysUserService.save(sysUser);
+                for (Long roleId : userSaveParams.getRoleIds()) {
+                    commonService.addUserRolePrivilege(sysUser, roleId);
+                }
+            } else {//修改用户
+                List<SysUserRole> sysUserRoleList = cacheService.userRolePrivilegeCache(sysUser.getId());
+                List<Long> userRolesList = Arrays.asList(userSaveParams.getRoleIds());
+                List<Long> dbUserRolesList = sysUserRoleList.stream().map(SysUserRole::getRoleId).distinct().collect(Collectors.toList());
+                int count = (int) dbUserRolesList.stream().filter(s -> userRolesList.contains(s)).count();
+                SysUser dbUser = sysUserService.getById(sysUser.getId());
+                sysUser.setUpdateInfo(requestUser.getId());
+                sysUserService.updateById(sysUser);
+                if (count == 0 || dbUserRolesList.size() != userRolesList.size()) {
+                    QueryWrapper<SysUserRole> sysUserRoleQueryWrapper = new QueryWrapper<>();
+                    sysUserRoleQueryWrapper.lambda().eq(SysUserRole::getUserId, sysUser.getId());
+                    sysUserRoleService.remove(sysUserRoleQueryWrapper);
+
+                    cacheService.removeUserRolePrivilegeCache(sysUser.getId());
+                    for (Long roleId : userSaveParams.getRoleIds()) {
+                        commonService.addUserRolePrivilege(sysUser, roleId);
+                    }
+                }
+                //如果修改了角色,需要重新登录
+                if (count == 0 || dbUserRolesList.size() != userRolesList.size()) {
+                    commonService.removeUserInfo(sysUser.getId());
+                }
+                //如果修改了机构,需更新用户缓存
+                if (dbUser.getOrgId().longValue() != sysUser.getOrgId().longValue()) {
+                    cacheService.updateUserCache(sysUser.getId());
+                    cacheService.updateUserAuthCache(sysUser.getId());
+                }
+            }
+            //用户科目全量删除全量增加
+            QueryWrapper<BasicUserCourse> basicUserCourseQueryWrapper = new QueryWrapper<>();
+            basicUserCourseQueryWrapper.lambda().eq(BasicUserCourse::getUserId, sysUser.getId());
+            basicUserCourseService.remove(basicUserCourseQueryWrapper);
+
+            List<SysRole> sysRoles = sysRoleService.list(sysUser.getRoleIds(), RoleTypeEnum.QUESTION_TEACHER.name());
+            if (sysRoles != null && sysRoles.size() > 0) {
+                Long[] courseIds = sysUser.getCourseIds();
+                if (courseIds.length == 0) {
+                    throw ExceptionResultEnum.ERROR.exception("请选择课程");
+                }
+                basicUserCourseService.saveBatch(sysUser);
+            }
+        } catch (Exception e) {
+            log.error("请求出错", e);
+            isSuccess = false;
+            if (e instanceof DuplicateKeyException) {
+                String errorColumn = e.getCause().toString();
+                String columnStr = errorColumn.substring(errorColumn.lastIndexOf("key") + 3, errorColumn.length()).replaceAll("'", "");
+                throw ExceptionResultEnum.SQL_ERROR.exception("[" + FieldUniqueEnum.convertToTitle(columnStr) + "]数据不允许重复插入");
+            } else if (e instanceof ApiException) {
+                ResultUtil.error((ApiException) e, e.getMessage());
+            } else {
+                ResultUtil.error(e.getMessage());
+            }
+        }
+        return isSuccess;
     }
 }

+ 14 - 15
distributed-print/src/main/java/com/qmth/distributed/print/api/SysUserController.java

@@ -21,6 +21,7 @@ import org.springframework.validation.BindingResult;
 import org.springframework.web.bind.annotation.*;
 
 import javax.validation.Valid;
+import java.security.NoSuchAlgorithmException;
 import java.util.List;
 
 /**
@@ -110,21 +111,22 @@ public class SysUserController {
         if (bindingResult.hasErrors()) {
             return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
         }
-        boolean isSuccess = sysUserService.saveUser(userSaveParams);
-        return ResultUtil.ok(isSuccess);
+        return ResultUtil.ok(sysUserService.saveUser(userSaveParams));
     }
 
     /**
      * 新增客服
      *
-     * @param user
+     * @param userSaveParams
      * @return
      */
     @ApiOperation(value = "新增客服")
     @RequestMapping(value = "/save_customer", method = RequestMethod.POST)
-    public Result saveCustomer(@RequestBody SysUser user) {
-        boolean isSuccess = sysUserService.saveCustomer(user);
-        return ResultUtil.ok(isSuccess);
+    public Result saveCustomer(@ApiParam(value = "用户信息", required = true) @Valid @RequestBody UserSaveParams userSaveParams, BindingResult bindingResult) {
+        if (bindingResult.hasErrors()) {
+            return ResultUtil.error(bindingResult.getAllErrors().get(0).getDefaultMessage());
+        }
+        return ResultUtil.ok(sysUserService.saveCustomer(userSaveParams));
     }
 
     /**
@@ -135,9 +137,8 @@ public class SysUserController {
      */
     @ApiOperation(value = "启用/禁用")
     @RequestMapping(value = "/enable", method = RequestMethod.POST)
-    public Result enable(@RequestBody SysUser user) {
-        boolean isSuccess = sysUserService.enable(user);
-        return ResultUtil.ok(isSuccess);
+    public Result enable(@RequestBody SysUser user) throws NoSuchAlgorithmException {
+        return ResultUtil.ok(sysUserService.enable(user));
     }
 
     /**
@@ -148,9 +149,8 @@ public class SysUserController {
      */
     @ApiOperation(value = "重置密码")
     @RequestMapping(value = "/reset_password", method = RequestMethod.POST)
-    public Result resetPassword(@RequestBody SysUser user) {
-        boolean isSuccess = sysUserService.resetPassword(user.getId());
-        return ResultUtil.ok(isSuccess);
+    public Result resetPassword(@RequestBody SysUser user) throws NoSuchAlgorithmException {
+        return ResultUtil.ok(sysUserService.resetPassword(user.getId()));
     }
 
     /**
@@ -160,9 +160,8 @@ public class SysUserController {
      */
     @ApiOperation(value = "修改密码")
     @RequestMapping(value = "/update_password", method = RequestMethod.POST)
-    public Result updatePassword(@RequestBody SysUser user) {
-        boolean isSuccess = sysUserService.updatePassword(user);
-        return ResultUtil.ok(isSuccess);
+    public Result updatePassword(@RequestBody SysUser user) throws NoSuchAlgorithmException {
+        return ResultUtil.ok(sysUserService.updatePassword(user));
     }
 
     /**