[代码完善](v2.5): v2.5 beta 缓存优化、加入RsaUtils工具类解决Rsa解密过慢,多选删除优化,修复菜单缓存问题,修复代码生成表查询分页问题

去除大量基于注解的缓存,去除列表查询的缓存,去除不合理的@CacheEvict(allEntries = true),缓存细腻化。

部分接口多选删除优化。

修复由于升级 hutool 工具版本导致代码生成分页错误的Bug

有问题请提 Issues

2.5 Beta 详情:https://www.ydyno.com/archives/1225.html
pull/372/head
ZhengJie 2020-05-18 23:12:21 +08:00
parent 2d969b43a5
commit 1af4eb89d2
34 changed files with 589 additions and 220 deletions

View File

@ -0,0 +1,38 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.zhengjie.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author Zheng Jie
* @website https://docs.auauz.net
* @description
* @date 2020-05-18
**/
@Data
@Component
public class RsaProperties {
public static String privateKey;
@Value("${rsa.private_key}")
public void setPrivateKey(String privateKey) {
RsaProperties.privateKey = privateKey;
}
}

View File

@ -0,0 +1,180 @@
package me.zhengjie.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
/**
* @author https://www.cnblogs.com/nihaorz/p/10690643.html
* @description
* @date 2020-05-18
**/
public class RsaUtils {
private static final String SRC = "123456";
public static void main(String[] args) throws Exception {
System.out.println("\n");
RSAKeyPair keyPair = generateKeyPair();
System.out.println("公钥:" + keyPair.getPublicKey());
System.out.println("私钥:" + keyPair.getPrivateKey());
System.out.println("\n");
test1(keyPair);
System.out.println("\n");
test2(keyPair);
System.out.println("\n");
}
/**
*
*/
private static void test1(RSAKeyPair keyPair) throws Exception {
System.out.println("***************** 公钥加密私钥解密开始 *****************");
String text1 = encryptByPublicKey(keyPair.getPublicKey(), RsaUtils.SRC);
String text2 = decryptByPrivateKey(keyPair.getPrivateKey(), text1);
System.out.println("加密前:" + RsaUtils.SRC);
System.out.println("加密后:" + text1);
System.out.println("解密后:" + text2);
if (RsaUtils.SRC.equals(text2)) {
System.out.println("解密字符串和原始字符串一致,解密成功");
} else {
System.out.println("解密字符串和原始字符串不一致,解密失败");
}
System.out.println("***************** 公钥加密私钥解密结束 *****************");
}
/**
*
* @throws Exception /
*/
private static void test2(RSAKeyPair keyPair) throws Exception {
System.out.println("***************** 私钥加密公钥解密开始 *****************");
String text1 = encryptByPrivateKey(keyPair.getPrivateKey(), RsaUtils.SRC);
String text2 = decryptByPublicKey(keyPair.getPublicKey(), text1);
System.out.println("加密前:" + RsaUtils.SRC);
System.out.println("加密后:" + text1);
System.out.println("解密后:" + text2);
if (RsaUtils.SRC.equals(text2)) {
System.out.println("解密字符串和原始字符串一致,解密成功");
} else {
System.out.println("解密字符串和原始字符串不一致,解密失败");
}
System.out.println("***************** 私钥加密公钥解密结束 *****************");
}
/**
*
*
* @param publicKeyText
* @param text
* @return /
* @throws Exception /
*/
public static String decryptByPublicKey(String publicKeyText, String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
*
*
* @param privateKeyText
* @param text
* @return /
* @throws Exception /
*/
public static String encryptByPrivateKey(String privateKeyText, String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.encodeBase64String(result);
}
/**
*
*
* @param privateKeyText
* @param text
* @return /
* @throws Exception /
*/
public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}
/**
*
*
* @param publicKeyText
* @param text
* @return /
*/
public static String encryptByPublicKey(String publicKeyText, String text) throws Exception {
X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] result = cipher.doFinal(text.getBytes());
return Base64.encodeBase64String(result);
}
/**
* RSA
*
* @return /
* @throws NoSuchAlgorithmException /
*/
public static RSAKeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(1024);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
String publicKeyString = Base64.encodeBase64String(rsaPublicKey.getEncoded());
String privateKeyString = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
return new RSAKeyPair(publicKeyString, privateKeyString);
}
/**
* RSA
*/
public static class RSAKeyPair {
private final String publicKey;
private final String privateKey;
public RSAKeyPair(String publicKey, String privateKey) {
this.publicKey = publicKey;
this.privateKey = privateKey;
}
public String getPublicKey() {
return publicKey;
}
public String getPrivateKey() {
return privateKey;
}
}
}

View File

@ -58,7 +58,7 @@ public class GeneratorController {
public ResponseEntity<Object> queryTables(@RequestParam(defaultValue = "") String name,
@RequestParam(defaultValue = "0")Integer page,
@RequestParam(defaultValue = "10")Integer size){
int[] startEnd = PageUtil.transToStartEnd(page+1, size);
int[] startEnd = PageUtil.transToStartEnd(page, size);
return new ResponseEntity<>(generatorService.getTables(name,startEnd), HttpStatus.OK);
}

View File

@ -34,6 +34,7 @@ import java.util.*;
* @date 2019-01-02
*/
@Slf4j
@SuppressWarnings({"unchecked","all"})
public class GenUtil {
private static final String TIMESTAMP = "Timestamp";

View File

@ -36,10 +36,7 @@ import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.*;
/**
* @author Zheng Jie
@ -88,13 +85,10 @@ public class LogServiceImpl implements LogService {
StringBuilder params = new StringBuilder("{");
//参数值
Object[] argValues = joinPoint.getArgs();
List<Object> argValues = new ArrayList<>(Arrays.asList(joinPoint.getArgs()));
//参数名称
String[] argNames = ((MethodSignature)joinPoint.getSignature()).getParameterNames();
if(argValues != null){
for (int i = 0; i < argValues.length; i++) {
params.append(" ").append(argNames[i]).append(": ").append(argValues[i]);
}
for (Object argValue : argValues) {
params.append(argValue).append(" ");
}
// 描述
if (log != null) {
@ -106,8 +100,7 @@ public class LogServiceImpl implements LogService {
String loginPath = "login";
if(loginPath.equals(signature.getName())){
try {
assert argValues != null;
username = new JSONObject(argValues[0]).get("username").toString();
username = new JSONObject(argValues.get(0)).get("username").toString();
}catch (Exception e){
e.printStackTrace();
}

View File

@ -20,8 +20,8 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author: ZhangHouYing
* @date: 2019-08-24 15:44
* @author ZhangHouYing
* @date 2019-08-24 15:44
*/
@Configuration
public class WebSocketConfig {
@ -30,5 +30,4 @@ public class WebSocketConfig {
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}

View File

@ -16,8 +16,6 @@
package me.zhengjie.modules.security.rest;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.wf.captcha.ArithmeticCaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
@ -25,12 +23,14 @@ import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.annotation.AnonymousAccess;
import me.zhengjie.annotation.Log;
import me.zhengjie.config.RsaProperties;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.security.config.SecurityProperties;
import me.zhengjie.modules.security.security.TokenProvider;
import me.zhengjie.modules.security.service.dto.AuthUserDto;
import me.zhengjie.modules.security.service.dto.JwtUserDto;
import me.zhengjie.modules.security.service.OnlineUserService;
import me.zhengjie.utils.RsaUtils;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.SecurityUtils;
import me.zhengjie.utils.StringUtils;
@ -62,8 +62,6 @@ public class AuthorizationController {
@Value("${loginCode.expiration}")
private Long expiration;
@Value("${rsa.private_key}")
private String privateKey;
@Value("${single.login:false}")
private Boolean singleLogin;
private final SecurityProperties properties;
@ -76,10 +74,9 @@ public class AuthorizationController {
@ApiOperation("登录授权")
@AnonymousAccess
@PostMapping(value = "/login")
public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request){
public ResponseEntity<Object> login(@Validated @RequestBody AuthUserDto authUser, HttpServletRequest request) throws Exception {
// 密码解密
RSA rsa = new RSA(privateKey, null);
String password = new String(rsa.decrypt(authUser.getPassword(), KeyType.PrivateKey));
String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, authUser.getPassword());
// 查询验证码
String code = (String) redisUtils.get(authUser.getUuid());
// 清除验证码

View File

@ -42,20 +42,14 @@ public interface DeptRepository extends JpaRepository<Dept, Long>, JpaSpecificat
*/
List<Dept> findByPidIsNull();
/**
* ID
* @param id ID
* @return /
*/
@Query(value = "select name from sys_dept where dept_id = ?1",nativeQuery = true)
String findNameById(Long id);
/**
* ID
* @param id ID
* @param roleId ID
* @return /
*/
Set<Dept> findByRoles_Id(Long id);
@Query(value = "select d.* from sys_dept d, sys_roles_depts r where " +
"d.dept_id = r.dept_id and r.role_id = ?1", nativeQuery = true)
Set<Dept> findByRoleId(Long roleId);
/**
*

View File

@ -19,9 +19,18 @@ import me.zhengjie.modules.system.domain.DictDetail;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
/**
* @author Zheng Jie
* @date 2019-04-10
*/
public interface DictDetailRepository extends JpaRepository<DictDetail, Long>, JpaSpecificationExecutor<DictDetail> {
/**
*
* @param name /
* @return /
*/
List<DictDetail> findByDictName(String name);
}

View File

@ -18,6 +18,8 @@ package me.zhengjie.modules.system.repository;
import me.zhengjie.modules.system.domain.Dict;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
import java.util.Set;
/**
@ -31,4 +33,11 @@ public interface DictRepository extends JpaRepository<Dict, Long>, JpaSpecificat
* @param ids /
*/
void deleteByIdIn(Set<Long> ids);
/**
*
* @param ids /
* @return /
*/
List<Dict> findByIdIn(Set<Long> ids);
}

View File

@ -19,6 +19,8 @@ import me.zhengjie.modules.system.domain.Job;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.Set;
/**
* @author Zheng Jie
* @date 2019-03-29
@ -31,4 +33,10 @@ public interface JobRepository extends JpaRepository<Job, Long>, JpaSpecificatio
* @return /
*/
Job findByName(String name);
/**
* Id
* @param ids /
*/
void deleteAllByIdIn(Set<Long> ids);
}

View File

@ -63,7 +63,9 @@ public interface MenuRepository extends JpaRepository<Menu, Long>, JpaSpecificat
* @param type
* @return /
*/
LinkedHashSet<Menu> findByRoles_IdInAndTypeNotOrderByMenuSortAsc(Set<Long> roleIds, int type);
@Query(value = "SELECT m.* FROM sys_menu m, sys_roles_menus r WHERE " +
"m.menu_id = r.menu_id AND r.role_id IN ?1 AND type != ?2 order by m.menu_sort asc",nativeQuery = true)
LinkedHashSet<Menu> findByRoleIdsAndTypeNot(Set<Long> roleIds, int type);
/**
*

View File

@ -35,12 +35,20 @@ public interface RoleRepository extends JpaRepository<Role, Long>, JpaSpecificat
*/
Role findByName(String name);
/**
*
* @param ids /
*/
void deleteAllByIdIn(Set<Long> ids);
/**
* ID
* @param id ID
* @return /
*/
Set<Role> findByUsers_Id(Long id);
@Query(value = "SELECT r.* FROM sys_role r, sys_users_roles u WHERE " +
"r.role_id = u.role_id AND u.user_id = ?1",nativeQuery = true)
Set<Role> findByUserId(Long id);
/**
*

View File

@ -21,6 +21,8 @@ import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import java.util.Date;
import java.util.List;
import java.util.Set;
/**
* @author Zheng Jie
@ -60,4 +62,37 @@ public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificat
@Modifying
@Query(value = "update sys_user set email = ?2 where username = ?1",nativeQuery = true)
void updateEmail(String username, String email);
/**
*
* @param roleId /
* @return /
*/
@Query(value = "SELECT u.* FROM sys_user u, sys_users_roles r WHERE" +
" u.user_id = r.user_id AND r.role_id = ?1", nativeQuery = true)
List<User> findByRoleId(Long roleId);
/**
*
* @param id /
* @return /
*/
@Query(value = "SELECT u.* FROM sys_user u, sys_users_roles r, sys_roles_depts d WHERE " +
"u.user_id = r.user_id AND r.role_id = d.role_id AND r.role_id = ?1", nativeQuery = true)
List<User> findByDeptRoleId(Long id);
/**
*
* @param id ID
* @return /
*/
@Query(value = "SELECT u.* FROM sys_user u, sys_users_roles ur, sys_roles_menus rm WHERE\n" +
"u.user_id = ur.user_id AND ur.role_id = rm.role_id AND rm.menu_id = ?1", nativeQuery = true)
List<User> findByMenuId(Long id);
/**
* Id
* @param ids /
*/
void deleteAllByIdIn(Set<Long> ids);
}

View File

@ -22,6 +22,7 @@ import me.zhengjie.annotation.Log;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.dto.DictDetailDto;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -32,6 +33,8 @@ import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
@ -58,15 +61,13 @@ public class DictDetailController {
@Log("查询多个字典详情")
@ApiOperation("查询多个字典详情")
@GetMapping(value = "/map")
public ResponseEntity<Object> getDictDetailMaps(DictDetailQueryCriteria criteria,
@PageableDefault(sort = {"dictSort"}, direction = Sort.Direction.ASC) Pageable pageable){
String[] names = criteria.getDictName().split(",");
Map<String,Object> map = new HashMap<>(names.length);
public ResponseEntity<Object> getDictDetailMaps(@RequestParam String dictName){
String[] names = dictName.split("[,]");
Map<String, List<DictDetailDto>> dictMap = new HashMap<>(16);
for (String name : names) {
criteria.setDictName(name);
map.put(name,dictDetailService.queryAll(criteria,pageable).get("content"));
dictMap.put(name, dictDetailService.getDictByName(name));
}
return new ResponseEntity<>(map,HttpStatus.OK);
return new ResponseEntity<>(dictMap, HttpStatus.OK);
}
@Log("新增字典详情")

View File

@ -22,9 +22,9 @@ import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.service.MenuService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.MenuDto;
import me.zhengjie.modules.system.service.dto.MenuQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.MenuMapper;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.SecurityUtils;
import org.springframework.http.HttpStatus;
@ -47,7 +47,7 @@ import java.util.*;
public class MenuController {
private final MenuService menuService;
private final RoleService roleService;
private final MenuMapper menuMapper;
private static final String ENTITY_NAME = "menu";
@Log("导出菜单数据")
@ -58,10 +58,10 @@ public class MenuController {
menuService.download(menuService.queryAll(criteria, false), response);
}
@ApiOperation("获取前端所需菜单")
@GetMapping(value = "/build")
@ApiOperation("获取前端所需菜单")
public ResponseEntity<Object> buildMenus(){
List<MenuDto> menuDtoList = menuService.findByRoles(roleService.findByUsersId(SecurityUtils.getCurrentUserId()));
List<MenuDto> menuDtoList = menuService.findByUser(SecurityUtils.getCurrentUserId());
List<MenuDto> menuDtos = menuService.buildTree(menuDtoList);
return new ResponseEntity<>(menuService.buildMenus(menuDtos),HttpStatus.OK);
}
@ -123,9 +123,9 @@ public class MenuController {
public ResponseEntity<Object> delete(@RequestBody Set<Long> ids){
Set<Menu> menuSet = new HashSet<>();
for (Long id : ids) {
List<Menu> menuList = menuService.findByPid(id);
List<MenuDto> menuList = menuService.getMenus(id);
menuSet.add(menuService.findOne(id));
menuSet = menuService.getDeleteMenus(menuList, menuSet);
menuSet = menuService.getDeleteMenus(menuMapper.toEntity(menuList), menuSet);
}
menuService.delete(menuSet);
return new ResponseEntity<>(HttpStatus.OK);

View File

@ -16,12 +16,11 @@
package me.zhengjie.modules.system.rest;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.config.RsaProperties;
import me.zhengjie.modules.system.service.DataService;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.exception.BadRequestException;
@ -35,7 +34,6 @@ import me.zhengjie.modules.system.service.VerifyService;
import me.zhengjie.utils.*;
import me.zhengjie.modules.system.service.UserService;
import me.zhengjie.utils.enums.CodeEnum;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
@ -61,8 +59,6 @@ import java.util.stream.Collectors;
@RequiredArgsConstructor
public class UserController {
@Value("${rsa.private_key}")
private String privateKey;
private final PasswordEncoder passwordEncoder;
private final UserService userService;
private final DataService dataService;
@ -85,7 +81,8 @@ public class UserController {
public ResponseEntity<Object> query(UserQueryCriteria criteria, Pageable pageable){
if (!ObjectUtils.isEmpty(criteria.getDeptId())) {
criteria.getDeptIds().add(criteria.getDeptId());
criteria.getDeptIds().addAll(dataService.getDeptChildren(deptService.findByPid(criteria.getDeptId())));
criteria.getDeptIds().addAll(deptService.getDeptChildren(criteria.getDeptId(),
deptService.findByPid(criteria.getDeptId())));
}
// 数据权限
List<Long> dataScopes = dataService.getDeptIds(userService.findByName(SecurityUtils.getCurrentUsername()));
@ -155,11 +152,9 @@ public class UserController {
@ApiOperation("修改密码")
@PostMapping(value = "/updatePass")
public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo){
// 密码解密
RSA rsa = new RSA(privateKey, null);
String oldPass = new String(rsa.decrypt(passVo.getOldPass(), KeyType.PrivateKey));
String newPass = new String(rsa.decrypt(passVo.getNewPass(), KeyType.PrivateKey));
public ResponseEntity<Object> updatePass(@RequestBody UserPassVo passVo) throws Exception {
String oldPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getOldPass());
String newPass = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,passVo.getNewPass());
UserDto user = userService.findByName(SecurityUtils.getCurrentUsername());
if(!passwordEncoder.matches(oldPass, user.getPassword())){
throw new BadRequestException("修改失败,旧密码错误");
@ -181,10 +176,8 @@ public class UserController {
@Log("修改邮箱")
@ApiOperation("修改邮箱")
@PostMapping(value = "/updateEmail/{code}")
public ResponseEntity<Object> updateEmail(@PathVariable String code,@RequestBody User user){
// 密码解密
RSA rsa = new RSA(privateKey, null);
String password = new String(rsa.decrypt(user.getPassword(), KeyType.PrivateKey));
public ResponseEntity<Object> updateEmail(@PathVariable String code,@RequestBody User user) throws Exception {
String password = RsaUtils.decryptByPrivateKey(RsaProperties.privateKey,user.getPassword());
UserDto userDto = userService.findByName(SecurityUtils.getCurrentUsername());
if(!passwordEncoder.matches(password, userDto.getPassword())){
throw new BadRequestException("密码错误");

View File

@ -15,9 +15,7 @@
*/
package me.zhengjie.modules.system.service;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.service.dto.UserDto;
import java.util.List;
/**
@ -33,11 +31,4 @@ public interface DataService {
* @return /
*/
List<Long> getDeptIds(UserDto user);
/**
*
* @param deptList /
* @return /
*/
List<Long> getDeptChildren(List<Dept> deptList);
}

View File

@ -76,7 +76,7 @@ public interface DeptService {
* @param id /
* @return /
*/
Set<Dept> findByRoleIds(Long id);
Set<Dept> findByRoleId(Long id);
/**
*
@ -108,4 +108,12 @@ public interface DeptService {
* @return /
*/
Object buildTree(List<DeptDto> deptDtos);
/**
*
* @param deptId
* @param deptList
* @return
*/
List<Long> getDeptChildren(Long deptId, List<Dept> deptList);
}

View File

@ -19,6 +19,7 @@ import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.service.dto.DictDetailDto;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import org.springframework.data.domain.Pageable;
import java.util.List;
import java.util.Map;
/**
@ -27,13 +28,6 @@ import java.util.Map;
*/
public interface DictDetailService {
/**
* ID
* @param id /
* @return /
*/
DictDetailDto findById(Long id);
/**
*
* @param resources /
@ -59,4 +53,11 @@ public interface DictDetailService {
* @return /
*/
Map<String,Object> queryAll(DictDetailQueryCriteria criteria, Pageable pageable);
/**
*
* @param name
* @return /
*/
List<DictDetailDto> getDictByName(String name);
}

View File

@ -19,7 +19,6 @@ import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.service.dto.DictDto;
import me.zhengjie.modules.system.service.dto.DictQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@ -47,13 +46,6 @@ public interface DictService {
*/
List<DictDto> queryAll(DictQueryCriteria dict);
/**
* ID
* @param id /
* @return /
*/
DictDto findById(Long id);
/**
*
* @param resources /

View File

@ -19,7 +19,6 @@ import me.zhengjie.modules.system.domain.Job;
import me.zhengjie.modules.system.service.dto.JobDto;
import me.zhengjie.modules.system.service.dto.JobQueryCriteria;
import org.springframework.data.domain.Pageable;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

View File

@ -66,13 +66,6 @@ public interface MenuService {
*/
Set<Menu> getDeleteMenus(List<Menu> menuList, Set<Menu> menuSet);
/**
* pid
* @param pid /
* @return /
*/
List<Menu> findByPid(long pid);
/**
*
* @param menuDtos
@ -80,13 +73,6 @@ public interface MenuService {
*/
List<MenuDto> buildTree(List<MenuDto> menuDtos);
/**
*
* @param roles /
* @return /
*/
List<MenuDto> findByRoles(List<RoleSmallDto> roles);
/**
*
* @param menuDtos /
@ -120,7 +106,7 @@ public interface MenuService {
* @param pid /
* @return /
*/
Object getMenus(Long pid);
List<MenuDto> getMenus(Long pid);
/**
* ID
@ -129,4 +115,11 @@ public interface MenuService {
* @return /
*/
List<MenuDto> getSuperior(MenuDto menuDto, List<Menu> objects);
/**
*
* @param currentUserId /
* @return /
*/
List<MenuDto> findByUser(Long currentUserId);
}

View File

@ -23,6 +23,8 @@ import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.utils.enums.DataScopeEnum;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import java.util.*;
@ -34,12 +36,19 @@ import java.util.*;
**/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "data")
public class DataServiceImpl implements DataService {
private final RoleService roleService;
private final DeptService deptService;
/**
*
* @param user /
* @return /
*/
@Override
@Cacheable(key = "'user:' + #p0.id")
public List<Long> getDeptIds(UserDto user) {
// 用于存储部门id
Set<Long> deptIds = new HashSet<>();
@ -69,35 +78,14 @@ public class DataServiceImpl implements DataService {
* @return ID
*/
public Set<Long> getCustomize(Set<Long> deptIds, RoleSmallDto role){
Set<Dept> depts = deptService.findByRoleIds(role.getId());
Set<Dept> depts = deptService.findByRoleId(role.getId());
for (Dept dept : depts) {
deptIds.add(dept.getId());
List<Dept> deptChildren = deptService.findByPid(dept.getId());
if (deptChildren != null && deptChildren.size() != 0) {
deptIds.addAll(getDeptChildren(deptChildren));
deptIds.addAll(deptService.getDeptChildren(dept.getId(), deptChildren));
}
}
return deptIds;
}
/**
*
* @param deptList
* @return
*/
@Override
public List<Long> getDeptChildren(List<Dept> deptList) {
List<Long> list = new ArrayList<>();
deptList.forEach(dept -> {
if (dept!=null && dept.getEnabled()){
List<Dept> depts = deptService.findByPid(dept.getId());
if(deptList.size() != 0){
list.addAll(getDeptChildren(depts));
}
list.add(dept.getId());
}
}
);
return list;
}
}

View File

@ -20,14 +20,19 @@ import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.dto.DeptDto;
import me.zhengjie.modules.system.service.dto.DeptQueryCriteria;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.service.DeptService;
import me.zhengjie.modules.system.service.mapstruct.DeptMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
@ -44,11 +49,14 @@ import java.util.stream.Collectors;
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dept")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DeptServiceImpl implements DeptService {
private final DeptRepository deptRepository;
private final DeptMapper deptMapper;
private final UserRepository userRepository;
private final RedisUtils redisUtils;
@Override
public List<DeptDto> queryAll(DeptQueryCriteria criteria, Boolean isQuery) throws Exception {
@ -74,6 +82,7 @@ public class DeptServiceImpl implements DeptService {
}
@Override
@Cacheable(key = "'id:' + #p0")
public DeptDto findById(Long id) {
Dept dept = deptRepository.findById(id).orElseGet(Dept::new);
ValidationUtil.isNull(dept.getId(),"Dept","id",id);
@ -81,13 +90,14 @@ public class DeptServiceImpl implements DeptService {
}
@Override
@Cacheable(key = "'pid:' + #p0")
public List<Dept> findByPid(long pid) {
return deptRepository.findByPid(pid);
}
@Override
public Set<Dept> findByRoleIds(Long id) {
return deptRepository.findByRoles_Id(id);
public Set<Dept> findByRoleId(Long id) {
return deptRepository.findByRoleId(id);
}
@Override
@ -97,6 +107,8 @@ public class DeptServiceImpl implements DeptService {
// 计算子节点数目
resources.setSubCount(0);
if(resources.getPid() != null){
// 清理缓存
redisUtils.del("dept::pid:" + resources.getPid());
updateSubCnt(resources.getPid());
}
}
@ -104,8 +116,8 @@ public class DeptServiceImpl implements DeptService {
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Dept resources) {
// 旧的菜单
DeptDto old = findById(resources.getId());
// 旧的部门
Long pid = findById(resources.getId()).getPid();
if(resources.getPid() != null && resources.getId().equals(resources.getPid())) {
throw new BadRequestException("上级不能为自己");
}
@ -114,16 +126,21 @@ public class DeptServiceImpl implements DeptService {
resources.setId(dept.getId());
deptRepository.save(resources);
if(resources.getPid() == null){
updateSubCnt(old.getPid());
updateSubCnt(pid);
} else {
pid = resources.getPid();
updateSubCnt(resources.getPid());
}
// 清理缓存
delCaches(resources.getId(), pid);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<DeptDto> deptDtos) {
for (DeptDto deptDto : deptDtos) {
// 清理缓存
delCaches(deptDto.getId(), deptDto.getPid());
deptRepository.deleteById(deptDto.getId());
if(deptDto.getPid() != null){
updateSubCnt(deptDto.getPid());
@ -156,6 +173,22 @@ public class DeptServiceImpl implements DeptService {
return deptDtos;
}
@Override
public List<Long> getDeptChildren(Long deptId, List<Dept> deptList) {
List<Long> list = new ArrayList<>();
deptList.forEach(dept -> {
if (dept!=null && dept.getEnabled()){
List<Dept> depts = deptRepository.findByPid(dept.getId());
if(deptList.size() != 0){
list.addAll(getDeptChildren(dept.getId(), depts));
}
list.add(dept.getId());
}
}
);
return list;
}
@Override
public List<DeptDto> getSuperior(DeptDto deptDto, List<Dept> depts) {
if(deptDto.getPid() == null){
@ -178,7 +211,7 @@ public class DeptServiceImpl implements DeptService {
trees.add(deptDTO);
}
for (DeptDto it : deptDtos) {
if (deptDTO.getId().equals(it.getPid())) {
if (it.getPid() != null && deptDTO.getId().equals(it.getPid())) {
isChild = true;
if (deptDTO.getChildren() == null) {
deptDTO.setChildren(new ArrayList<>());
@ -188,7 +221,7 @@ public class DeptServiceImpl implements DeptService {
}
if(isChild) {
depts.add(deptDTO);
} else if(!deptNames.contains(deptRepository.findNameById(deptDTO.getPid()))) {
} else if(deptDTO.getPid() != null && !deptNames.contains(findById(deptDTO.getPid()).getName())) {
depts.add(deptDTO);
}
}
@ -196,11 +229,8 @@ public class DeptServiceImpl implements DeptService {
if (CollectionUtil.isEmpty(trees)) {
trees = depts;
}
Integer totalElements = deptDtos.size();
Map<String,Object> map = new HashMap<>(2);
map.put("totalElements",totalElements);
map.put("totalElements",deptDtos.size());
map.put("content",CollectionUtil.isEmpty(trees)? deptDtos :trees);
return map;
}
@ -209,4 +239,18 @@ public class DeptServiceImpl implements DeptService {
int count = deptRepository.countByPid(deptId);
deptRepository.updateSubCntById(count, deptId);
}
/**
*
* @param id /
*/
public void delCaches(Long id, Long pid){
List<User> users = userRepository.findByDeptRoleId(id);
// 删除数据权限
redisUtils.delByKeys("data::user:",users.stream().map(User::getId).collect(Collectors.toSet()));
redisUtils.del("dept::id:" + id);
if (pid != null) {
redisUtils.del("dept::pid:" + pid);
}
}
}

View File

@ -16,20 +16,26 @@
package me.zhengjie.modules.system.service.impl;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.Dict;
import me.zhengjie.modules.system.domain.DictDetail;
import me.zhengjie.modules.system.repository.DictRepository;
import me.zhengjie.modules.system.service.dto.DictDetailQueryCriteria;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.RedisUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.system.repository.DictDetailRepository;
import me.zhengjie.modules.system.service.DictDetailService;
import me.zhengjie.modules.system.service.dto.DictDetailDto;
import me.zhengjie.modules.system.service.mapstruct.DictDetailMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
@ -38,11 +44,14 @@ import java.util.Map;
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictDetailServiceImpl implements DictDetailService {
private final DictRepository dictRepository;
private final DictDetailRepository dictDetailRepository;
private final DictDetailMapper dictDetailMapper;
private final RedisUtils redisUtils;
@Override
public Map<String,Object> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
@ -50,17 +59,12 @@ public class DictDetailServiceImpl implements DictDetailService {
return PageUtil.toPage(page.map(dictDetailMapper::toDto));
}
@Override
public DictDetailDto findById(Long id) {
DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new);
ValidationUtil.isNull(dictDetail.getId(),"DictDetail","id",id);
return dictDetailMapper.toDto(dictDetail);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(DictDetail resources) {
dictDetailRepository.save(resources);
// 清理缓存
delCaches(resources);
}
@Override
@ -70,11 +74,27 @@ public class DictDetailServiceImpl implements DictDetailService {
ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId());
resources.setId(dictDetail.getId());
dictDetailRepository.save(resources);
// 清理缓存
delCaches(resources);
}
@Override
@Cacheable(key = "'name:' + #p0")
public List<DictDetailDto> getDictByName(String name) {
return dictDetailMapper.toDto(dictDetailRepository.findByDictName(name));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new);
// 清理缓存
delCaches(dictDetail);
dictDetailRepository.deleteById(id);
}
public void delCaches(DictDetail dictDetail){
Dict dict = dictRepository.findById(dictDetail.getDict().getId()).orElseGet(Dict::new);
redisUtils.del("dept::name:" + dict.getName());
}
}

View File

@ -25,6 +25,8 @@ import me.zhengjie.modules.system.repository.DictRepository;
import me.zhengjie.modules.system.service.DictService;
import me.zhengjie.modules.system.service.dto.DictDto;
import me.zhengjie.modules.system.service.mapstruct.DictMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@ -40,6 +42,7 @@ import java.util.*;
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "dict")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DictServiceImpl implements DictService {
@ -59,13 +62,6 @@ public class DictServiceImpl implements DictService {
return dictMapper.toDto(list);
}
@Override
public DictDto findById(Long id) {
Dict dict = dictRepository.findById(id).orElseGet(Dict::new);
ValidationUtil.isNull(dict.getId(),"Dict","id",id);
return dictMapper.toDto(dict);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(Dict resources) {
@ -75,6 +71,8 @@ public class DictServiceImpl implements DictService {
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Dict resources) {
// 清理缓存
delCaches(resources);
Dict dict = dictRepository.findById(resources.getId()).orElseGet(Dict::new);
ValidationUtil.isNull( dict.getId(),"Dict","id",resources.getId());
resources.setId(dict.getId());
@ -84,8 +82,12 @@ public class DictServiceImpl implements DictService {
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
// 清理缓存
List<Dict> dicts = dictRepository.findByIdIn(ids);
for (Dict dict : dicts) {
delCaches(dict);
}
dictRepository.deleteByIdIn(ids);
redisUtils.delByKeys("dict::", ids);
}
@Override
@ -114,4 +116,8 @@ public class DictServiceImpl implements DictService {
}
FileUtil.downloadExcel(list, response);
}
public void delCaches(Dict dict){
redisUtils.del("dept::name:" + dict.getName());
}
}

View File

@ -24,6 +24,9 @@ import me.zhengjie.modules.system.repository.JobRepository;
import me.zhengjie.modules.system.service.JobService;
import me.zhengjie.modules.system.service.dto.JobDto;
import me.zhengjie.modules.system.service.mapstruct.JobMapper;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@ -39,6 +42,7 @@ import java.util.*;
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "job")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JobServiceImpl implements JobService {
@ -59,6 +63,7 @@ public class JobServiceImpl implements JobService {
}
@Override
@Cacheable(key = "'id:' + #p0")
public JobDto findById(Long id) {
Job job = jobRepository.findById(id).orElseGet(Job::new);
ValidationUtil.isNull(job.getId(),"Job","id",id);
@ -76,6 +81,7 @@ public class JobServiceImpl implements JobService {
}
@Override
@CacheEvict(key = "'id:' + #p0.id")
@Transactional(rollbackFor = Exception.class)
public void update(Job resources) {
Job job = jobRepository.findById(resources.getId()).orElseGet(Job::new);
@ -91,11 +97,9 @@ public class JobServiceImpl implements JobService {
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
for (Long id : ids) {
jobRepository.deleteById(id);
// 删除缓存
redisUtils.del("job::"+id);
}
jobRepository.deleteAllByIdIn(ids);
// 删除缓存
redisUtils.delByKeys("job::id:", ids);
}
@Override

View File

@ -19,21 +19,22 @@ import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.domain.vo.MenuMetaVo;
import me.zhengjie.modules.system.domain.vo.MenuVo;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.system.repository.MenuRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.MenuService;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.MenuDto;
import me.zhengjie.modules.system.service.dto.MenuQueryCriteria;
import me.zhengjie.modules.system.service.dto.RoleSmallDto;
import me.zhengjie.modules.system.service.mapstruct.MenuMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.StringUtils;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.utils.*;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
@ -49,12 +50,15 @@ import java.util.stream.Collectors;
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "menu")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class MenuServiceImpl implements MenuService {
private final MenuRepository menuRepository;
private final UserRepository userRepository;
private final MenuMapper menuMapper;
private final RoleService roleService;
private final RedisUtils redisUtils;
@Override
public List<MenuDto> queryAll(MenuQueryCriteria criteria, Boolean isQuery) throws Exception {
@ -79,16 +83,24 @@ public class MenuServiceImpl implements MenuService {
}
@Override
@Cacheable(key = "'id:' + #p0")
public MenuDto findById(long id) {
Menu menu = menuRepository.findById(id).orElseGet(Menu::new);
ValidationUtil.isNull(menu.getId(),"Menu","id",id);
return menuMapper.toDto(menu);
}
/**
*
* @param currentUserId /
* @return /
*/
@Override
public List<MenuDto> findByRoles(List<RoleSmallDto> roles) {
@Cacheable(key = "'user:' + #p0")
public List<MenuDto> findByUser(Long currentUserId) {
List<RoleSmallDto> roles = roleService.findByUsersId(currentUserId);
Set<Long> roleIds = roles.stream().map(RoleSmallDto::getId).collect(Collectors.toSet());
LinkedHashSet<Menu> menus = menuRepository.findByRoles_IdInAndTypeNotOrderByMenuSortAsc(roleIds, 2);
LinkedHashSet<Menu> menus = menuRepository.findByRoleIdsAndTypeNot(roleIds, 2);
return menus.stream().map(menuMapper::toDto).collect(Collectors.toList());
}
@ -116,6 +128,8 @@ public class MenuServiceImpl implements MenuService {
// 计算子节点数目
resources.setSubCount(0);
if(resources.getPid() != null){
// 清理缓存
redisUtils.del("menu::pid:" + resources.getPid());
updateSubCnt(resources.getPid());
}
}
@ -128,7 +142,7 @@ public class MenuServiceImpl implements MenuService {
}
Menu menu = menuRepository.findById(resources.getId()).orElseGet(Menu::new);
// 记录旧的父节点ID
Long oldPid = menu.getPid();
Long pid = menu.getPid();
ValidationUtil.isNull(menu.getId(),"Permission","id",resources.getId());
if(resources.getIFrame()){
@ -167,10 +181,13 @@ public class MenuServiceImpl implements MenuService {
menuRepository.save(menu);
// 计算子节点数目
if(resources.getPid() == null){
updateSubCnt(oldPid);
updateSubCnt(pid);
} else {
pid = resources.getPid();
updateSubCnt(resources.getPid());
}
// 清理缓存
delCaches(resources.getId(), pid);
}
@Override
@ -192,6 +209,8 @@ public class MenuServiceImpl implements MenuService {
for (Menu menu : menuSet) {
roleService.untiedMenu(menu.getId());
menuRepository.deleteById(menu.getId());
// 清理缓存
delCaches(menu.getId(), menu.getPid());
if(menu.getPid() != null){
updateSubCnt(menu.getPid());
}
@ -199,7 +218,8 @@ public class MenuServiceImpl implements MenuService {
}
@Override
public Object getMenus(Long pid) {
@Cacheable(key = "'pid:' + #p0")
public List<MenuDto> getMenus(Long pid) {
List<Menu> menus;
if(pid != null && !pid.equals(0L)){
menus = menuRepository.findByPid(pid);
@ -219,11 +239,6 @@ public class MenuServiceImpl implements MenuService {
return getSuperior(findById(menuDto.getPid()), menus);
}
@Override
public List<Menu> findByPid(long pid) {
return menuRepository.findByPid(pid);
}
@Override
public List<MenuDto> buildTree(List<MenuDto> menuDtos) {
List<MenuDto> trees = new ArrayList<>();
@ -326,4 +341,18 @@ public class MenuServiceImpl implements MenuService {
int count = menuRepository.countByPid(menuId);
menuRepository.updateSubCntById(count, menuId);
}
/**
*
* @param id ID
* @param pid ID
*/
public void delCaches(Long id, Long pid){
List<User> users = userRepository.findByMenuId(id);
redisUtils.del("menu::id:" +id);
redisUtils.delByKeys("menu::user:",users.stream().map(User::getId).collect(Collectors.toSet()));
if(pid != null){
redisUtils.del("menu::pid:" + pid);
}
}
}

View File

@ -15,14 +15,13 @@
*/
package me.zhengjie.modules.system.service.impl;
import cn.hutool.core.collection.CollectionUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.system.domain.Dept;
import me.zhengjie.modules.system.domain.Menu;
import me.zhengjie.modules.system.domain.Role;
import me.zhengjie.exception.EntityExistException;
import me.zhengjie.modules.system.repository.DeptRepository;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.RoleRepository;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.modules.system.service.RoleService;
import me.zhengjie.modules.system.service.dto.RoleDto;
import me.zhengjie.modules.system.service.dto.RoleQueryCriteria;
@ -31,7 +30,8 @@ import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.mapstruct.RoleMapper;
import me.zhengjie.modules.system.service.mapstruct.RoleSmallMapper;
import me.zhengjie.utils.*;
import me.zhengjie.utils.enums.DataScopeEnum;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -51,14 +51,15 @@ import java.util.stream.Collectors;
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "role")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class RoleServiceImpl implements RoleService {
private final RoleRepository roleRepository;
private final RoleMapper roleMapper;
private final RoleSmallMapper roleSmallMapper;
private final DeptRepository deptRepository;
private final RedisUtils redisUtils;
private final UserRepository userRepository;
@Override
public List<RoleDto> queryAll() {
@ -78,6 +79,7 @@ public class RoleServiceImpl implements RoleService {
}
@Override
@Cacheable(key = "'id:' + #p0")
public RoleDto findById(long id) {
Role role = roleRepository.findById(id).orElseGet(Role::new);
ValidationUtil.isNull(role.getId(),"Role","id",id);
@ -90,7 +92,6 @@ public class RoleServiceImpl implements RoleService {
if(roleRepository.findByName(resources.getName()) != null){
throw new EntityExistException(Role.class,"username",resources.getName());
}
checkDataScope(resources);
roleRepository.save(resources);
}
@ -105,54 +106,52 @@ public class RoleServiceImpl implements RoleService {
if(role1 != null && !role1.getId().equals(role.getId())){
throw new EntityExistException(Role.class,"username",resources.getName());
}
checkDataScope(resources);
role.setName(resources.getName());
role.setDescription(resources.getDescription());
role.setDataScope(resources.getDataScope());
role.setDepts(resources.getDepts());
role.setLevel(resources.getLevel());
roleRepository.save(role);
}
private void checkDataScope(Role resources){
if(CollectionUtil.isNotEmpty(resources.getDepts()) && resources.getDepts().size() == 1){
for (Dept dept : resources.getDepts()) {
dept = deptRepository.findById(dept.getId()).orElseGet(Dept::new);
if(dept.getPid() == 0 || dept.getPid() == null){
resources.setDepts(null);
resources.setDataScope(DataScopeEnum.ALL.getValue());
}
}
}
// 更新相关缓存
delCaches(role.getId());
}
@Override
public void updateMenu(Role resources, RoleDto roleDTO) {
Role role = roleMapper.toEntity(roleDTO);
// 清理缓存
List<User> users = userRepository.findByRoleId(role.getId());
Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet());
redisUtils.delByKeys("menu::user:",userIds);
// 更新菜单
role.setMenus(resources.getMenus());
roleRepository.save(role);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void untiedMenu(Long id) {
roleRepository.untiedMenu(id);
public void untiedMenu(Long menuId) {
// 清理缓存
List<User> users = userRepository.findByMenuId(menuId);
Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet());
redisUtils.delByKeys("menu::user:",userIds);
// 更新菜单
roleRepository.untiedMenu(menuId);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
for (Long id : ids) {
roleRepository.deleteById(id);
// 删除缓存
redisUtils.del("role::"+id);
// 更新相关缓存
delCaches(id);
}
roleRepository.deleteAllByIdIn(ids);
}
@Override
public List<RoleSmallDto> findByUsersId(Long id) {
return roleSmallMapper.toDto(new ArrayList<>(roleRepository.findByUsers_Id(id)));
return roleSmallMapper.toDto(new ArrayList<>(roleRepository.findByUserId(id)));
}
@Override
@ -165,6 +164,7 @@ public class RoleServiceImpl implements RoleService {
}
@Override
@Cacheable(key = "'auth:' + #p0")
public List<GrantedAuthority> mapToGrantedAuthorities(UserDto user) {
Set<String> permissions = new HashSet<>();
// 如果是管理员直接返回
@ -173,7 +173,7 @@ public class RoleServiceImpl implements RoleService {
return permissions.stream().map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
Set<Role> roles = roleRepository.findByUsers_Id(user.getId());
Set<Role> roles = roleRepository.findByUserId(user.getId());
permissions = roles.stream().flatMap(role -> role.getMenus().stream())
.filter(menu -> StringUtils.isNotBlank(menu.getPermission()))
.map(Menu::getPermission).collect(Collectors.toSet());
@ -194,4 +194,16 @@ public class RoleServiceImpl implements RoleService {
}
FileUtil.downloadExcel(list, response);
}
/**
*
* @param id /
*/
public void delCaches(Long id){
List<User> users = userRepository.findByRoleId(id);
Set<Long> userIds = users.stream().map(User::getId).collect(Collectors.toSet());
redisUtils.delByKeys("data::user:",userIds);
redisUtils.delByKeys("menu::user:",userIds);
redisUtils.delByKeys("role::auth:",userIds);
}
}

View File

@ -28,6 +28,8 @@ import me.zhengjie.modules.system.service.dto.UserDto;
import me.zhengjie.modules.system.service.dto.UserQueryCriteria;
import me.zhengjie.modules.system.service.mapstruct.UserMapper;
import me.zhengjie.utils.*;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
@ -46,13 +48,14 @@ import java.util.stream.Collectors;
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "user")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
private final UserRepository userRepository;
private final UserMapper userMapper;
private final RedisUtils redisUtils;
private final FileProperties properties;
private final RedisUtils redisUtils;
@Override
public Object queryAll(UserQueryCriteria criteria, Pageable pageable) {
@ -67,6 +70,7 @@ public class UserServiceImpl implements UserService {
}
@Override
@Cacheable(key = "'id:' + #p0")
public UserDto findById(long id) {
User user = userRepository.findById(id).orElseGet(User::new);
ValidationUtil.isNull(user.getId(),"User","id",id);
@ -100,15 +104,12 @@ public class UserServiceImpl implements UserService {
if(user2!=null&&!user.getId().equals(user2.getId())){
throw new EntityExistException(User.class,"email",resources.getEmail());
}
// 如果用户的角色改变了,需要手动清理下缓存
// 如果用户的角色改变
if (!resources.getRoles().equals(user.getRoles())) {
String key = "role::permission:" + user.getUsername();
redisUtils.del(key);
key = "role::user:" + user.getId();
redisUtils.del(key);
redisUtils.del("data::user:" + resources.getId());
redisUtils.del("menu::user:" + resources.getId());
redisUtils.del("role::auth:" + resources.getId());
}
user.setUsername(resources.getUsername());
user.setEmail(resources.getEmail());
user.setEnabled(resources.getEnabled());
@ -119,6 +120,8 @@ public class UserServiceImpl implements UserService {
user.setNickName(resources.getNickName());
user.setGender(resources.getGender());
userRepository.save(user);
// 清除缓存
delCaches(user.getId(), user.getUsername());
}
@Override
@ -129,24 +132,25 @@ public class UserServiceImpl implements UserService {
user.setPhone(resources.getPhone());
user.setGender(resources.getGender());
userRepository.save(user);
// 清理缓存
delCaches(user.getId(), user.getUsername());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
for (Long id : ids) {
userRepository.deleteById(id);
// 清理缓存
UserDto user = findById(id);
delCaches(user.getId(), user.getUsername());
}
userRepository.deleteAllByIdIn(ids);
}
@Override
@Cacheable(key = "'username:' + #p0")
public UserDto findByName(String userName) {
User user;
if(ValidationUtil.isEmail(userName)){
user = userRepository.findByEmail(userName);
} else {
user = userRepository.findByUsername(userName);
}
User user = userRepository.findByUsername(userName);
if (user == null) {
throw new EntityNotFoundException(User.class, "name", userName);
} else {
@ -158,6 +162,7 @@ public class UserServiceImpl implements UserService {
@Transactional(rollbackFor = Exception.class)
public void updatePass(String username, String pass) {
userRepository.updatePass(username,pass,new Date());
redisUtils.del("user::username:" + username);
}
@Override
@ -172,12 +177,14 @@ public class UserServiceImpl implements UserService {
if(StringUtils.isNotBlank(oldPath)){
FileUtil.del(oldPath);
}
redisUtils.del("user::username:" + user.getUsername());
}
@Override
@Transactional(rollbackFor = Exception.class)
public void updateEmail(String username, String email) {
userRepository.updateEmail(username,email);
redisUtils.del("user::username:" + username);
}
@Override
@ -199,4 +206,13 @@ public class UserServiceImpl implements UserService {
}
FileUtil.downloadExcel(list, response);
}
/**
*
* @param id /
*/
public void delCaches(Long id, String username){
redisUtils.del("user::id:" + id);
redisUtils.del("user::username:" + username);
}
}

View File

@ -53,9 +53,9 @@ jwt:
# 令牌过期时间 此处单位/毫秒 默认4小时可在此网站生成 https://www.convertworld.com/zh-hans/time/milliseconds.html
token-validity-in-seconds: 14400000
# 在线用户key
online-key: online-token
online-key: online-token-
# 验证码
code-key: code-key
code-key: code-key-
# token 续期检查时间范围默认30分钟单位毫秒在token即将过期的一段时间内用户操作了则给用户的token续期
detect: 1800000
# 续期时间范围默认1小时单位毫秒

View File

@ -55,9 +55,9 @@ jwt:
# 令牌过期时间 此处单位/毫秒 默认2小时可在此网站生成 https://www.convertworld.com/zh-hans/time/milliseconds.html
token-validity-in-seconds: 7200000
# 在线用户key
online-key: online-token
online-key: online-token-
# 验证码
code-key: code-key
code-key: code-key-
# token 续期检查时间范围默认30分钟单位默认毫秒在token即将过期的一段时间内用户操作了则给用户的token续期
detect: 1800000
# 续期时间范围,默认 1小时这里单位毫秒

View File

@ -6,12 +6,11 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class EladminSystemApplicationTests {
@Test
public void contextLoads() {
}
public static void main(String[] args) {