init
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
package org.nl.common.domain;
|
||||
package org.nl.common.domain.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.http.HttpStatus;
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* 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 org.nl.common.domain.exception.handler;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import lombok.Data;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2018-11-23
|
||||
*/
|
||||
@Data
|
||||
class ApiError {
|
||||
|
||||
private Integer status = 400;
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime timestamp;
|
||||
private String message;
|
||||
|
||||
private ApiError() {
|
||||
timestamp = LocalDateTime.now();
|
||||
}
|
||||
|
||||
public static ApiError error(String message){
|
||||
ApiError apiError = new ApiError();
|
||||
apiError.setMessage(message);
|
||||
return apiError;
|
||||
}
|
||||
|
||||
public static ApiError error(Integer status, String message){
|
||||
ApiError apiError = new ApiError();
|
||||
apiError.setStatus(status);
|
||||
apiError.setMessage(message);
|
||||
return apiError;
|
||||
}
|
||||
|
||||
public static String getStackTrace(Throwable throwable){
|
||||
StringWriter sw = new StringWriter();
|
||||
try (PrintWriter pw = new PrintWriter(sw)) {
|
||||
throwable.printStackTrace(pw);
|
||||
return sw.toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* 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 org.nl.common.domain.exception.handler;
|
||||
|
||||
import cn.dev33.satoken.exception.NotLoginException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* @author Zheng Jie
|
||||
* @date 2018-11-23
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/**
|
||||
* 处理所有不可知的异常
|
||||
*/
|
||||
@ExceptionHandler(Throwable.class)
|
||||
public ResponseEntity<ApiError> handleException(Throwable e){
|
||||
// 打印堆栈信息
|
||||
log.error(ApiError.getStackTrace(e));
|
||||
return buildResponseEntity(ApiError.error(e.getMessage()));
|
||||
}
|
||||
|
||||
/**
|
||||
* token 无效的异常拦截
|
||||
* @param e
|
||||
* @return
|
||||
*/
|
||||
@ExceptionHandler(value = NotLoginException.class)
|
||||
public ResponseEntity<ApiError> notLoginException(Exception e) {
|
||||
log.error("token超时:-------------------------------------"+e.getMessage());
|
||||
return buildResponseEntity(ApiError.error(401,"token 失效"));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 处理自定义异常
|
||||
*/
|
||||
@ExceptionHandler(value = BadRequestException.class)
|
||||
public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
|
||||
// 打印堆栈信息
|
||||
log.error(ApiError.getStackTrace(e));
|
||||
return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理所有接口数据验证异常
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
|
||||
// 打印堆栈信息
|
||||
log.error(ApiError.getStackTrace(e));
|
||||
String[] str = Objects.requireNonNull(e.getBindingResult().getAllErrors().get(0).getCodes())[1].split("\\.");
|
||||
String message = e.getBindingResult().getAllErrors().get(0).getDefaultMessage();
|
||||
String msg = "不能为空";
|
||||
if(msg.equals(message)){
|
||||
message = str[1] + ":" + message;
|
||||
}
|
||||
return buildResponseEntity(ApiError.error(message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一返回
|
||||
*/
|
||||
private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) {
|
||||
return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus()));
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,7 @@ import cn.hutool.poi.excel.BigExcelWriter;
|
||||
import cn.hutool.poi.excel.ExcelUtil;
|
||||
import org.apache.poi.xssf.streaming.SXSSFSheet;
|
||||
import org.apache.tomcat.util.http.fileupload.IOUtils;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@@ -2,7 +2,7 @@ package org.nl.common.utils;
|
||||
|
||||
|
||||
import net.coobird.thumbnailator.Thumbnails;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package org.nl.common.utils;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.interfaces.LockProcess;
|
||||
import org.nl.common.domain.interfaces.ReturnLockProcess;
|
||||
import org.redisson.api.RLock;
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
package org.nl.common.utils;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
|
||||
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 Rsa 工具类,公钥私钥生成,加解密
|
||||
* @date 2020-05-18
|
||||
**/
|
||||
public class RsaUtils {
|
||||
|
||||
private static final String SRC = "123456";
|
||||
|
||||
public static final String KEY = "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEA0vfvyTdGJkdbHkB8mp0f3FE0GYP3AYPaJF7jUd1M0XxFSE2ceK3k2kw20YvQ09NJKk+OMjWQl9WitG9pB6tSCQIDAQABAkA2SimBrWC2/wvauBuYqjCFwLvYiRYqZKThUS3MZlebXJiLB+Ue/gUifAAKIg1avttUZsHBHrop4qfJCwAI0+YRAiEA+W3NK/RaXtnRqmoUUkb59zsZUBLpvZgQPfj1MhyHDz0CIQDYhsAhPJ3mgS64NbUZmGWuuNKp5coY2GIj/zYDMJp6vQIgUueLFXv/eZ1ekgz2Oi67MNCk5jeTF2BurZqNLR3MSmUCIFT3Q6uHMtsB9Eha4u7hS31tj1UWE+D+ADzp59MGnoftAiBeHT7gDMuqeJHPL4b+kC+gzV4FGTfhR9q3tTbklZkD2A==";
|
||||
|
||||
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) {
|
||||
try {
|
||||
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);
|
||||
}catch (Exception ex){
|
||||
throw new BadRequestException(ex.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 公钥加密
|
||||
*
|
||||
* @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;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -39,14 +39,13 @@ public class DruidFilter extends FilterEventAdapter {
|
||||
|
||||
@Override
|
||||
protected void statementExecuteAfter(StatementProxy statement, String sql, boolean result) {
|
||||
String traceId = MDC.get("traceId");
|
||||
int size = statement.getParametersSize();
|
||||
String executeSql = sql;
|
||||
int count = 0;
|
||||
try {
|
||||
count=statement.getUpdateCount();
|
||||
}catch (Exception ex){ }
|
||||
if (StringUtils.isNotBlank(traceId) && count>0) {
|
||||
if (count>0) {
|
||||
if (size > 0) {
|
||||
Collection<JdbcParameter> values = statement.getParameters().values();
|
||||
List<Object> params = new ArrayList<>();
|
||||
@@ -63,8 +62,7 @@ public class DruidFilter extends FilterEventAdapter {
|
||||
public ResultSetProxy statement_getResultSet(FilterChain chain, StatementProxy statement) throws SQLException {
|
||||
ResultSetProxy rs = super.statement_getResultSet(chain, statement);
|
||||
String executeSql = statement.getLastExecuteSql();
|
||||
String traceId = MDC.get("traceId");
|
||||
if (StringUtils.isNotBlank(traceId)){
|
||||
if (true){
|
||||
int result = 0;
|
||||
if (rs != null) {
|
||||
ResultSetImpl rss = rs.getResultSetRaw().unwrap(ResultSetImpl.class);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package org.nl.config.satoken;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
|
||||
|
||||
/**
|
||||
* @author: lyd
|
||||
* @description:
|
||||
* @Date: 2022/10/8
|
||||
*/
|
||||
@Configuration
|
||||
public class RedisListenerConfig {
|
||||
@Bean
|
||||
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
|
||||
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
|
||||
container.setConnectionFactory(connectionFactory);
|
||||
return container;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package org.nl.config.satoken;
|
||||
|
||||
import cn.dev33.satoken.interceptor.SaInterceptor;
|
||||
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
|
||||
import cn.dev33.satoken.stp.StpLogic;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* @author: lyd
|
||||
* @description: sa-token的配置路由拦截
|
||||
* @Date: 2022-09-20
|
||||
*/
|
||||
@Slf4j
|
||||
@ConfigurationProperties(prefix = "security")
|
||||
@Configuration
|
||||
@Data
|
||||
public class SaTokenConfigure implements WebMvcConfigurer {
|
||||
|
||||
// 白名单
|
||||
private String[] excludes;
|
||||
// Sa-Token 整合 jwt (Simple 简单模式)
|
||||
@Bean
|
||||
public StpLogic getStpLogicJwt() {
|
||||
return new StpLogicJwtForSimple();
|
||||
}
|
||||
|
||||
// 注册 Sa-Token 拦截器,打开注解式鉴权功能
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
// 注册 Sa-Token 拦截器,打开注解式鉴权功能
|
||||
registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
|
||||
.addPathPatterns("/**")
|
||||
.excludePathPatterns(excludes); // 白名单
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package org.nl.config.satoken;
|
||||
|
||||
import cn.dev33.satoken.stp.StpInterface;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* @author: lyd
|
||||
* @description: stp接口impl 自定义权限验证接口扩展 保证此类被springboot扫描,即可完成sa-token的自定义权限验证扩展
|
||||
* @Date: 2022-09-20
|
||||
*/
|
||||
@Component
|
||||
public class StpInterfaceImpl implements StpInterface {
|
||||
|
||||
/**
|
||||
* 用户权限获取
|
||||
* @param o login存入的值,此处存放用户id
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public List<String> getPermissionList(Object o, String s) {
|
||||
return SecurityUtils.getCurrentUserPermissions();
|
||||
}
|
||||
|
||||
/**
|
||||
* 角色权限获取 - 数据库没有设计角色code,因此不推荐使用角色鉴权
|
||||
* @param o
|
||||
* @param s
|
||||
* @return
|
||||
*/
|
||||
@Override
|
||||
public List<String> getRoleList(Object o, String s) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
## 关于satoken的提示
|
||||
### 本系统采用两个session存放相关信息
|
||||
1、其中tokenSession存放的是
|
||||
提供公共模块使用,获取是Object可以直接强转此实体.
|
||||
主要使用在 SecurityUtils类上,使用的key: userInfo
|
||||
```java
|
||||
@Data
|
||||
public class CurrentUser implements Serializable {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long id;
|
||||
|
||||
private String username;
|
||||
|
||||
private Object user;
|
||||
|
||||
private List<String> permissions = new ArrayList<>();
|
||||
}
|
||||
```
|
||||
2、Session存放的是UserDto,提供业务模块使用使用的key: UserDto
|
||||
```java
|
||||
@Getter
|
||||
@Setter
|
||||
public class UserDto extends BaseDTO implements Serializable {
|
||||
@JsonSerialize(using = ToStringSerializer.class)
|
||||
private Long id;
|
||||
|
||||
private Set<RoleSmallDto> roles;
|
||||
|
||||
private Set<JobSmallDto> jobs;
|
||||
|
||||
private DeptSmallDto dept;
|
||||
|
||||
private Long deptId;
|
||||
|
||||
private String username;
|
||||
|
||||
private String nickName;
|
||||
|
||||
private String email;
|
||||
|
||||
private String phone;
|
||||
|
||||
private String gender;
|
||||
|
||||
private String avatarName;
|
||||
|
||||
private String avatarPath;
|
||||
|
||||
private String extId;
|
||||
|
||||
private String extuserId;
|
||||
|
||||
|
||||
@JsonIgnore
|
||||
private String password;
|
||||
|
||||
private Boolean enabled;
|
||||
|
||||
@JsonIgnore
|
||||
private Boolean isAdmin = false;
|
||||
|
||||
private Date pwdResetTime;
|
||||
}
|
||||
```
|
||||
|
||||
### 加密规则
|
||||
```
|
||||
SaSecureUtil.md5BySalt("123456", "salt")
|
||||
```
|
||||
|
||||
### 另一种拦截
|
||||
```
|
||||
registry.addInterceptor(new SaRouteInterceptor((request, response, handler) -> {
|
||||
System.out.println(SaHolder.getRequest().getRequestPath());
|
||||
// 登录验证 -- 排除多个路径
|
||||
SaRouter
|
||||
// 获取所有的
|
||||
.match("/**")
|
||||
// 排除下不需要拦截的
|
||||
.notMatch(securityProperties.getExcludes())
|
||||
// 对未排除的路径进行检查
|
||||
.check(() -> {
|
||||
// 检查是否登录 是否有token
|
||||
StpUtil.checkLogin();
|
||||
});
|
||||
})).addPathPatterns("/**");
|
||||
registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");
|
||||
```
|
||||
@@ -23,7 +23,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.nl.common.anno.Log;
|
||||
import org.nl.common.TableDataInfo;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
|
||||
|
||||
|
||||
@@ -66,11 +66,8 @@ public class AuthorizationController {
|
||||
|
||||
//("登录授权")
|
||||
@PostMapping(value = "/login")
|
||||
public ResponseEntity<Object> login(@RequestBody Map authMap) throws Exception {
|
||||
if (ObjectUtil.isEmpty(authMap)){
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
return new ResponseEntity(HttpStatus.OK);
|
||||
public ResponseEntity<Object> login(@RequestBody JSONObject authMap) throws Exception {
|
||||
return new ResponseEntity(userService.login(authMap),HttpStatus.OK);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import cn.dev33.satoken.annotation.SaCheckPermission;
|
||||
import org.nl.common.anno.Log;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.nl.common.TableDataInfo;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.nl.common.anno.Log;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
|
||||
@@ -38,7 +38,6 @@ import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
|
||||
@@ -8,7 +8,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.MapOf;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
|
||||
@@ -8,7 +8,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.CopyUtil;
|
||||
import org.nl.common.utils.IdUtil;
|
||||
|
||||
@@ -9,7 +9,7 @@ import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.compress.utils.Lists;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.constant.DictConstantPool;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.CopyUtil;
|
||||
|
||||
@@ -8,7 +8,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.MapOf;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
|
||||
@@ -9,7 +9,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
|
||||
|
||||
@@ -7,8 +7,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.RedisUtils;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
|
||||
@@ -2,7 +2,7 @@ package org.nl.wms.system_manage.service.quartz.utils;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.wms.system_manage.service.quartz.dao.SysQuartzJob;
|
||||
import org.quartz.*;
|
||||
import org.quartz.impl.triggers.CronTriggerImpl;
|
||||
|
||||
@@ -11,7 +11,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
|
||||
|
||||
@@ -13,13 +13,15 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.nl.modules.security.config.bean;
|
||||
package org.nl.wms.system_manage.service.secutiry.entity;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.wf.captcha.*;
|
||||
import com.wf.captcha.base.Captcha;
|
||||
import lombok.Data;
|
||||
import org.nl.modules.common.exception.BadConfigurationException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.wms.system_manage.service.secutiry.enums.LoginCodeEnum;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.awt.*;
|
||||
import java.util.Objects;
|
||||
@@ -31,6 +33,7 @@ import java.util.Objects;
|
||||
* @date loginCode.length0loginCode.length0/6/10 17:loginCode.length6
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
public class LoginProperties {
|
||||
|
||||
/**
|
||||
@@ -100,7 +103,7 @@ public class LoginProperties {
|
||||
captcha.setLen(loginCode.getLength());
|
||||
break;
|
||||
default:
|
||||
throw new BadConfigurationException("验证码配置信息错误!正确配置查看 LoginCodeEnum ");
|
||||
throw new BadRequestException("验证码配置信息错误!正确配置查看 LoginCodeEnum ");
|
||||
}
|
||||
}
|
||||
if(StrUtil.isNotEmpty(loginCode.getFontName())){
|
||||
@@ -6,15 +6,12 @@ import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.alibaba.fastjson.JSON;
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.utils.RedisUtils;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
|
||||
import org.nl.wms.system_manage.service.role.ISysRoleService;
|
||||
import org.nl.wms.system_manage.service.secutiry.HandLoginService;
|
||||
|
||||
@@ -31,6 +31,8 @@ public interface ISysUserService extends IService<SysUser> {
|
||||
|
||||
void update(JSONObject userDetail);
|
||||
|
||||
JSONObject login(JSONObject userDetail);
|
||||
|
||||
List<UserDataPermissionDto> getUserDataPermissionByPermissionId(String permissionId);
|
||||
|
||||
List<UserDataPermissionDto> getUserDataPermissionByUserId(String userId);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package org.nl.wms.system_manage.service.user.impl;
|
||||
|
||||
import cn.dev33.satoken.secure.SaSecureUtil;
|
||||
import cn.dev33.satoken.stp.SaLoginModel;
|
||||
import cn.dev33.satoken.stp.StpUtil;
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
@@ -13,27 +15,27 @@ import com.github.pagehelper.PageHelper;
|
||||
import lombok.SneakyThrows;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.nl.common.TableDataInfo;
|
||||
import org.nl.common.domain.BadRequestException;
|
||||
import org.nl.common.domain.exception.BadRequestException;
|
||||
import org.nl.common.domain.constant.FileProperties;
|
||||
import org.nl.common.domain.entity.PageQuery;
|
||||
import org.nl.common.utils.FileUtil;
|
||||
import org.nl.common.utils.IdUtil;
|
||||
import org.nl.common.utils.SecurityUtils;
|
||||
import org.nl.common.utils.*;
|
||||
import org.nl.wms.system_manage.service.dept.ISysDeptService;
|
||||
import org.nl.wms.system_manage.service.role.ISysRoleService;
|
||||
import org.nl.wms.system_manage.service.secutiry.dto.AuthUserDto;
|
||||
import org.nl.wms.system_manage.service.user.ISysUserService;
|
||||
import org.nl.wms.system_manage.service.user.dao.SysUser;
|
||||
import org.nl.wms.system_manage.service.user.dao.mapper.SysUserMapper;
|
||||
import org.nl.wms.system_manage.service.user.dto.CurrentUser;
|
||||
import org.nl.wms.system_manage.service.user.dto.SysUserDetail;
|
||||
import org.nl.wms.system_manage.service.user.dto.UserDataPermissionDto;
|
||||
import org.nl.wms.system_manage.service.user.dto.UserQuery;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.CollectionUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.File;
|
||||
import java.util.*;
|
||||
|
||||
@@ -54,6 +56,11 @@ public class ISysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> imp
|
||||
private ISysDeptService deptService;
|
||||
@Autowired
|
||||
private ISysRoleService roleService;
|
||||
@Autowired
|
||||
private RedisUtils redisUtils;
|
||||
|
||||
@Value("${sa-token.cookie.domain}")
|
||||
private String domain;
|
||||
|
||||
@Override
|
||||
public Map<String, String> updateAvatar(MultipartFile multipartFile) {
|
||||
@@ -172,4 +179,44 @@ public class ISysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> imp
|
||||
user.setPassword(SaSecureUtil.md5BySalt(newPass, "salt"));
|
||||
this.updateById(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public JSONObject login(JSONObject userDetail) {
|
||||
AuthUserDto authUser = userDetail.toJavaObject(AuthUserDto.class);
|
||||
// 查询验证码
|
||||
String code = (String) redisUtils.get(authUser.getUuid());
|
||||
redisUtils.del(authUser.getUuid());
|
||||
// if (StrUtil.isEmpty(code)) {
|
||||
// throw new BadRequestException("验证码不存在或已过期");
|
||||
// }
|
||||
// if (StrUtil.isEmpty(authUser.getCode()) || !authUser.getCode().equalsIgnoreCase(code)) {
|
||||
// throw new BadRequestException("验证码错误");
|
||||
// }
|
||||
SysUser userInfo = this.getOne(new QueryWrapper<SysUser>().eq("username",authUser.getUsername()));
|
||||
if (userInfo == null||!userInfo.getPassword().equals(SaSecureUtil.md5BySalt(RsaUtils.decryptByPrivateKey(RsaUtils.KEY, authUser.getPassword()), "salt"))) { // 这里需要密码加密
|
||||
throw new BadRequestException("账号或密码错误");
|
||||
}
|
||||
if (!userInfo.getIs_used()) {
|
||||
throw new BadRequestException("账号未激活");
|
||||
}
|
||||
List<String> permissionList = roleService.getPermissionList((JSONObject) JSON.toJSON(userInfo));
|
||||
// 登录输入,登出删除
|
||||
CurrentUser user = new CurrentUser();
|
||||
user.setId(userInfo.getUser_id());
|
||||
user.setUsername(userInfo.getUsername());
|
||||
user.setPresonName((userInfo.getPerson_name()));
|
||||
user.setUser(userInfo);
|
||||
user.setPermissions(permissionList);
|
||||
// SaLoginModel 配置登录相关参数
|
||||
StpUtil.login(userInfo.getUser_id(), new SaLoginModel()
|
||||
.setDevice("PC") // 此次登录的客户端设备类型, 用于[同端互斥登录]时指定此次登录的设备类型
|
||||
.setExtra("loginInfo", user) // Token挂载的扩展参数 (此方法只有在集成jwt插件时才会生效)
|
||||
);
|
||||
JSONObject result = new JSONObject();
|
||||
result.put("token", StpUtil.getTokenValue());
|
||||
result.put("roles", permissionList);
|
||||
result.put("domain", domain);
|
||||
result.put("user", user);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ spring:
|
||||
druid:
|
||||
db-type: com.alibaba.druid.pool.DruidDataSource
|
||||
driverClassName: com.mysql.cj.jdbc.Driver
|
||||
url: jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:hl_one_mes}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&allowPublicKeyRetrieval=true&useSSL=false
|
||||
url: jdbc:mysql://${DB_HOST:localhost}:${DB_PORT:3306}/${DB_NAME:wms}?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false&useOldAliasMetadataBehavior=true&allowPublicKeyRetrieval=true&useSSL=false
|
||||
username: ${DB_USER:root}
|
||||
password: ${DB_PWD:942464Yy}
|
||||
|
||||
@@ -151,32 +151,6 @@ sa-token:
|
||||
# 配置 Cookie 作用域:根据二级域名实现sso登入如lms.sso.com;acs.sso.com
|
||||
domain:
|
||||
is-read-cookie: false
|
||||
|
||||
#jetcache:
|
||||
# defaultCacheType: LOCAL
|
||||
# statIntervalMinutes: 15
|
||||
# areaInCacheName: false
|
||||
# hiddenPackages: com.yb
|
||||
# local:
|
||||
# default:
|
||||
# type: caffeine
|
||||
# limit: 100
|
||||
# keyConvertor: fastjson
|
||||
# expireAfterWriteInMillis: 60000
|
||||
# remote:
|
||||
# default:
|
||||
# type: redis.lettuce
|
||||
# keyConvertor: fastjson
|
||||
# valueEncoder: kryo
|
||||
# valueDecoder: kryo
|
||||
# poolConfig:
|
||||
# minIdle: 5
|
||||
# maxIdle: 200
|
||||
# maxTotal: 1000
|
||||
# uri:
|
||||
# - redis://127.0.0.1:6379
|
||||
es:
|
||||
index: mes_log
|
||||
schedulerFile: /Users/mima0000/Desktop/scheduler.xml
|
||||
lucene:
|
||||
index:
|
||||
|
||||
@@ -77,8 +77,8 @@
|
||||
</appender>
|
||||
|
||||
<!--开发环境:打印控制台-->
|
||||
<springProfile name="dev">
|
||||
<root level="debug">
|
||||
<springProfile name="dev3">
|
||||
<root level="info">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
</root>
|
||||
<logger name="jdbc" level="ERROR" additivity="true">
|
||||
@@ -106,13 +106,6 @@
|
||||
<appender-ref ref="asyncFileAppender"/>
|
||||
</logger>
|
||||
</springProfile>
|
||||
|
||||
<springProfile name="dev3">
|
||||
<root level="info">
|
||||
<appender-ref ref="asyncLuceneAppender"/>
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
</root>
|
||||
</springProfile>
|
||||
<springProfile name="prod">
|
||||
<root level="info">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
@@ -144,15 +137,6 @@
|
||||
</logger>
|
||||
</springProfile>
|
||||
<!--测试环境:打印控制台-->
|
||||
<springProfile name="test">
|
||||
<!-- 打印sql -->
|
||||
<logger name="org.nl.start.Init" level="info" additivity="false">
|
||||
<appender-ref ref="FILE"/>
|
||||
</logger>
|
||||
<root level="info">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
</root>
|
||||
</springProfile>
|
||||
|
||||
<!--生产环境:打印控制台和输出到文件-->
|
||||
|
||||
|
||||
Reference in New Issue
Block a user