feat(修改): 🚀 user登录时判断并放入全局上下文

This commit is contained in:
Bunny 2024-06-03 21:37:11 +08:00
parent 817d0d33b2
commit 25cbfb643d
5 changed files with 106 additions and 39 deletions

View File

@ -1,10 +1,13 @@
package cn.bunny.common.service.context;
import cn.bunny.vo.system.login.LoginVo;
public class BaseContext {
private static final ThreadLocal<Long> userId = new ThreadLocal<>();
private static final ThreadLocal<String> username = new ThreadLocal<String>();
private static final ThreadLocal<Long> adminId = new ThreadLocal<>();
private static final ThreadLocal<String> adminName = new ThreadLocal<>();
private static final ThreadLocal<LoginVo> loginVo = new ThreadLocal<>();
// 用户id相关
public static Long getUserId() {
@ -23,9 +26,18 @@ public class BaseContext {
username.set(_username);
}
public static LoginVo getLoginVo() {
return loginVo.get();
}
public static void setLoginVo(LoginVo _loginVo) {
loginVo.set(_loginVo);
}
public static void removeUser() {
username.remove();
userId.remove();
loginVo.remove();
}
// adminId 相关

View File

@ -2,6 +2,8 @@ package cn.bunny.common.service.interceptor;
import cn.bunny.common.service.context.BaseContext;
import cn.bunny.common.service.utils.JwtHelper;
import cn.bunny.common.service.utils.ResponseUtil;
import cn.bunny.pojo.result.Result;
import cn.bunny.pojo.result.ResultCodeEnum;
import cn.bunny.pojo.result.constant.RedisUserConstant;
import cn.bunny.vo.system.login.LoginVo;
@ -18,51 +20,41 @@ import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Map;
import static cn.bunny.common.service.utils.ResponseHandlerUtil.loginAuthHandler;
@Component
@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("UserTokenInterceptor===>设置拦截器");
// 获取token
String token = request.getHeader("token");
// token为空时
if (token == null) {
return loginAuthHandler(response, ResultCodeEnum.LOGIN_AUTH);
}
// 当token过期
if (JwtHelper.isExpired(token)) {
return loginAuthHandler(response, ResultCodeEnum.AUTHENTICATION_EXPIRED);
}
// 将token转成实体类
Map<String, Object> tokenByMap = JwtHelper.getMapByToken(token);
LoginVo loginVo = JSONObject.parseObject(JSONObject.toJSONString(tokenByMap), LoginVo.class);
// 获取用户id和用户邮箱
Long userId = loginVo.getId();
String email = loginVo.getEmail();
String redisKey = RedisUserConstant.getUserLoginInfoPrefix(email);
Object redisUserinfo = redisTemplate.opsForValue().get(redisKey);
Map<String, Object> mapByToken = JwtHelper.getMapByToken(token);
LoginVo loginVo = JSONObject.parseObject(JSONObject.toJSONString(mapByToken), LoginVo.class);
Object redisUserinfo = redisTemplate.opsForValue().get(RedisUserConstant.getUserLoginInfoPrefix(loginVo.getEmail()));
// 不是动态方法直接返回
if (!(handler instanceof HandlerMethod)) return true;
// 解析不到userIdRedis中没有这个用户
if (userId == null || redisUserinfo == null) {
return loginAuthHandler(response, ResultCodeEnum.LOGIN_AUTH);
// token过期-提示身份验证过期
if (JwtHelper.isExpired(token)) {
ResponseUtil.out(response, Result.error(ResultCodeEnum.AUTHENTICATION_EXPIRED));
return false;
}
// 解析不到userId
if (loginVo.getId() == null) {
ResponseUtil.out(response, Result.error(ResultCodeEnum.LOGIN_AUTH));
return false;
}
if (redisUserinfo == null) {
ResponseUtil.out(response, Result.error(ResultCodeEnum.LOGIN_AUTH));
return false;
}
BaseContext.setUserId(userId);
BaseContext.setUsername(email);
BaseContext.setUserId(loginVo.getId());
BaseContext.setUsername(loginVo.getEmail());
BaseContext.setLoginVo(loginVo);
return true;
}

View File

@ -0,0 +1,57 @@
package cn.bunny.common.service.utils;
import cn.bunny.common.service.exception.BunnyException;
import cn.bunny.pojo.result.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import java.net.Inet6Address;
import java.net.InetAddress;
public class RequestUtil {
public static String getHttpIpAddress(HttpServletRequest request) {
String ipv6Address = request.getRemoteAddr();
try {
InetAddress inetAddress = InetAddress.getByName(ipv6Address);
if (inetAddress.isAnyLocalAddress() || inetAddress.isLoopbackAddress()) {
System.out.println("IPv4 Address: " + inetAddress.getHostAddress());
} else {
InetAddress ipv4Address = Inet6Address.getByAddress(null, inetAddress.getAddress(), 0);
System.out.println("IPv4 Address: " + ipv4Address.getHostAddress());
}
} catch (Exception e) {
throw new BunnyException(ResultCodeEnum.SERVICE_ERROR);
}
String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_FORWARDED");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_X_CLUSTER_CLIENT_IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_FORWARDED_FOR");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("HTTP_FORWARDED");
}
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("REMOTE_ADDR");
}
return ipAddress;
}
}

View File

@ -41,7 +41,7 @@ public class SystemLog implements Serializable {
private String methodName;
@ApiModelProperty("入参内容")
private Object args;
private String args;
@ApiModelProperty("返回参数")
private String result;
@ -61,6 +61,9 @@ public class SystemLog implements Serializable {
@ApiModelProperty("当前用户token")
private String token;
@ApiModelProperty("当前用户IP地址")
private String ipAddress;
@ApiModelProperty("创建时间")
private LocalDateTime createTime;
@ -72,4 +75,4 @@ public class SystemLog implements Serializable {
@ApiModelProperty("是否被删除")
private Boolean isDeleted;
}
}

View File

@ -54,24 +54,27 @@ public class AutoLogAspect {
Map<String, Object> mapByToken = JwtHelper.getMapByToken(token);
LoginVo loginVo = JSONObject.parseObject(JSONObject.toJSONString(mapByToken), LoginVo.class);
// 插入Ip地址
systemLog.setIpAddress(request.getRemoteHost());
try {
// 当为null时跳过执行
if (annotation != null) return joinPoint.proceed();
// TODO 将请求头token全部转成 map
systemLog.setClassPath(classPath);
systemLog.setMethodName(methodName);
if (args.equals("[null]")) {
systemLog.setArgs(null);
} else {
systemLog.setArgs(args);
}
systemLog.setToken(token);
// 登录返回Vo不为空即插入
if (loginVo != null) {
systemLog.setNickname(loginVo.getNickName());
systemLog.setEmail(loginVo.getEmail());
systemLog.setUpdateUser(loginVo.getId());
}
systemLog.setNickname(loginVo.getNickName());
systemLog.setEmail(loginVo.getEmail());
systemLog.setUpdateUser(loginVo.getId());
systemLog.setClassPath(classPath);
systemLog.setMethodName(methodName);
systemLog.setToken(token);
// 目标对象连接点方法的执行
result = joinPoint.proceed();