数据合法性验证

添加AOP校验进行数据合法性验证,使用时间戳进行前后验证(误差前后5秒)
This commit is contained in:
筱锋xiao_lfeng 2023-12-21 00:21:19 +08:00
parent 7711f6c28a
commit 31e96a2a4e
Signed by: XiaoLFeng
GPG Key ID: F693AA12AABBFA87
3 changed files with 85 additions and 0 deletions

View File

@ -62,6 +62,10 @@
<artifactId>spring-boot-starter-validation</artifactId>
<version>3.1.5</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,80 @@
package com.jsl.oa.aspect;
import com.jsl.oa.utils.ErrorCode;
import com.jsl.oa.utils.ResultUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
/**
* <h1>用户控制器切面</h1>
* <hr/>
* 用于用户控制器的切面
*
* @since v1.0.0
* @version v1.0.0
* @author 筱锋xiao_lfeng
*/
@Aspect
@Component
public class UserControllerAspect {
/**
* <h1>用户控制器切面</h1>
* <hr/>
* 用于用户控制器的切面
*
* @since v1.0.0
* @param pjp ProceedingJoinPoint对象
* @return {@link Object}
* @throws Throwable 异常
*/
@Around("execution(* com.jsl.oa.controllers.UserController.*(..))")
public Object controllerAround(ProceedingJoinPoint pjp) throws Throwable {
// 获取HttpServletRequest对象
HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
// 时间戳检查
if (checkTimestamp(request)) {
pjp.proceed();
// TODO: 2023/12/21 0001 后期固定业务日志处理
return null;
} else {
return ResultUtil.error(ErrorCode.TIMESTAMP_ERROR);
}
}
/**
* <h1>时间戳检查</h1>
* <hr/>
* 用于检查时间戳是否合法合法时间范围正负5秒
*
* @since v1.0.0
* @param request HttpServletRequest对象
* @return {@link Boolean}
*/
public Boolean checkTimestamp(HttpServletRequest request) {
// 获取请求头中的时间戳
String getTimestamp = request.getHeader("Timestamp");
// 判断是否为空
if (getTimestamp == null || getTimestamp.isEmpty()) {
return false;
} else {
if (getTimestamp.length() == 10) {
getTimestamp += "000";
}
}
// 获取当前时间戳
long nowTimestamp = System.currentTimeMillis();
// 时间误差允许前后五秒钟
return nowTimestamp - Long.parseLong(getTimestamp) <= 5000 && nowTimestamp - Long.parseLong(getTimestamp) >= -5000;
}
}

View File

@ -7,6 +7,7 @@ public enum ErrorCode {
WRONG_PASSWORD("WrongPassword", 40010, "密码错误"),
PARAMETER_ERROR("ParameterError", 40011, "参数错误"),
USERNAME_EXIST("UsernameExist", 40012, "用户名已存在"),
TIMESTAMP_ERROR("TimestampError", 40013, "时间戳错误"),
DATABASE_INSERT_ERROR("DatabaseInsertError", 50010, "数据库插入错误"),
DATABASE_UPDATE_ERROR("DatabaseUpdateError", 50011, "数据库更新错误"),
DATABASE_DELETE_ERROR("DatabaseDeleteError", 50012, "数据库删除错误");