Commit 9202d753 authored by zhouxudong's avatar zhouxudong

调整日志输出 调整认证token方式 添加token续期功能

parent a44cbde1
......@@ -3,6 +3,8 @@ package com.lyy.user.config.auth;
import com.lyy.user.config.exception.ServiceException;
import com.lyy.user.config.other.BaseContextHandler;
import com.lyy.user.constant.Constants;
import com.lyy.user.constant.RedisConstants;
import com.lyy.user.domain.JwtInfo;
import com.lyy.user.util.jwt.JwtTokenUtil;
import com.lyy.user.util.redis.RedisUtil;
import org.apache.commons.lang3.ObjectUtils;
......@@ -11,6 +13,7 @@ import org.springframework.web.servlet.AsyncHandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
/** 服务拦截器,根据配置的请求路径,进行请求的拦截,执行preHandle方法 */
public class CurrentUserInterceptor implements AsyncHandlerInterceptor {
......@@ -19,16 +22,24 @@ public class CurrentUserInterceptor implements AsyncHandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 从header中获取权限请求头
String token = request.getHeader(Constants.TOKEN_HEADER);
if(StringUtils.isBlank(token)){
String authToken = request.getHeader(Constants.TOKEN_HEADER);
if(StringUtils.isBlank(authToken)){
throw new ServiceException("未授权,登录失败");
}
Object redisToken = RedisUtil.get(Constants.token + token);
String token = authToken.substring("Bearer".length() + 1).trim();
JwtInfo jwtUser = JwtTokenUtil.getJwtUser(token);
Object redisToken = RedisUtil.get(RedisConstants.token + jwtUser.getPhone());
if(ObjectUtils.isEmpty(redisToken)){
throw new ServiceException("请重新登录");
}
//判断是否续期
Long expire = RedisUtil.getExpire(RedisConstants.token + jwtUser.getPhone());
if(expire<Constants.addTime){
RedisUtil.set(RedisConstants.token + jwtUser.getPhone(), token, Constants.expireTime, TimeUnit.SECONDS);
}
// 根据token信息,生成当前登录用户信息的设置,存放容器threadlocal
BaseContextHandler.setCurrentUserInfo(JwtTokenUtil.getJwtUser(token));
BaseContextHandler.setCurrentUserInfo(jwtUser);
return true;
}
......
......@@ -121,16 +121,8 @@ public class Constants {
public static final int EXPIRE_TIME =5;
//秒
public static final int INTERVAL_TIME =4*60;
//------------------redis key--------------------------
public static final String token="Bearer ";
//手机验证码 规则: 手机验证码:验证码类型:手机号
public static final String MSG_KEY="phone:message:";
//用户查看数据详情 使用额度 map存储: 格式: key phone + ":" + type value
public static final String LIMIT_NUM="limit_num";
public static final String LIMIT_SMS="limit_sms:";
//---------------------end------------------------------
//token 过期时间
public static Long expireTime = 86400L;
//token 续期时间 12小时
public static Long addTime = 43200L;
}
package com.lyy.user.constant;
/**
* @Author:zhouxudong
* @version: 1.0
* @Date: 2023/12/1 11:55
* @Description: redis key
*/
public class RedisConstants {
//------------------redis key--------------------------
public static final String token="Token:";
//手机验证码 规则: 手机验证码:验证码类型:手机号
public static final String MSG_KEY="phone:message:";
//用户查看数据详情 使用额度 map存储: 格式: key phone + ":" + type value
public static final String LIMIT_NUM="limit_num";
public static final String LIMIT_SMS="limit_sms:";
//---------------------end------------------------------
}
......@@ -17,8 +17,6 @@ public class TokenConstants {
public static final class TOKEN_RESULT {
public static final String TOKEN_PARSE_SUCCESS = "token解析成功";
public static final String TOKEN_EXPIRED = "token已过期";
public static final String TOKEN_PARSE_FAILED = "无效的token";
}
public static final String DATA = "data";
......
package com.lyy.user.moudle.login.controller;
import com.lyy.user.constant.Constants;
import com.lyy.user.enums.SendMsgTypeEnum;
import com.lyy.user.moudle.user.service.SysUserInfoService;
import com.lyy.user.moudle.user.vo.*;
import com.lyy.user.util.redis.RedisUtil;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* @Author:zhouxudong
*
......@@ -96,5 +92,4 @@ public class SysPcLoginController {
public boolean forget(@RequestBody @Validated ForgetVo forgetVo) {
return this.sysUserInfoService.forget(forgetVo, SendMsgTypeEnum.FORGOT_PASSWORD.getCode());
}
}
package com.lyy.user.moudle.user.controller;
import com.lyy.user.config.auth.CurrentUserInterceptor;
import com.lyy.user.config.other.BaseContextHandler;
import com.lyy.user.constant.Constants;
import com.lyy.user.domain.JwtInfo;
import com.lyy.user.enums.SendMsgTypeEnum;
import com.lyy.user.moudle.user.service.SysUserInfoService;
......@@ -10,14 +7,12 @@ import com.lyy.user.moudle.user.vo.ForgetVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* @Author:zhouxudong
......@@ -39,8 +34,8 @@ public class SysUserController {
*/
@PostMapping("/logout")
@ApiOperation(value = "退出登录")
public boolean logout(HttpServletRequest request) {
return this.sysUserInfoService.logout(request.getHeader(Constants.TOKEN_HEADER));
public boolean logout() {
return this.sysUserInfoService.logout();
}
/**
......@@ -55,13 +50,12 @@ public class SysUserController {
return this.sysUserInfoService.forget(forgetVo, SendMsgTypeEnum.UPDATE_PASSWORD.getCode());
}
/**
* @description: 获取用户信息
* @date: 2023/11/23 10:21
* @param: [token]
* @return: String
**/
*/
@PostMapping("/detail")
@ApiOperation(value = "获取用户信息")
public JwtInfo detail() {
......
......@@ -5,7 +5,6 @@ import com.lyy.user.domain.JwtInfo;
import com.lyy.user.moudle.user.entity.SysUserInfo;
import com.lyy.user.moudle.user.vo.*;
import javax.servlet.http.HttpServletRequest;
/**
* @author 26996
......@@ -35,7 +34,7 @@ public interface SysUserInfoService extends IService<SysUserInfo> {
* @param: []
* @return: boolean
**/
boolean logout(String token);
boolean logout();
/**
* @description: 核对手机号是否已经注册
* @date: 2023/11/16 18:36
......
package com.lyy.user.moudle.user.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyy.user.config.LyyConfig;
import com.lyy.user.config.exception.ServiceException;
import com.lyy.user.config.other.BaseContextHandler;
import com.lyy.user.constant.Constants;
import com.lyy.user.constant.RedisConstants;
import com.lyy.user.domain.JwtInfo;
import com.lyy.user.enums.BusinessTypeEnum;
import com.lyy.user.enums.SendMsgTypeEnum;
......@@ -83,7 +83,7 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
}
/**
* @description: pc端登录--->复用登录
* @description: pc端登录
* @date: 2023/11/16 17:32
* @param: [loginVo]
* @return: java.lang.String token
......@@ -103,7 +103,11 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
throw new ServiceException("当前用户密码输入错误");
}
String token = JwtTokenUtil.createToken(sysUserInfo, null);
RedisUtil.set(Constants.token + token, sysUserInfo.getUserId(), JwtTokenUtil.expireTime, TimeUnit.MILLISECONDS);
RedisUtil.set(
RedisConstants.token + sysUserInfo.getPhonenumber(),
token,
Constants.expireTime,
TimeUnit.SECONDS);
return token;
}
......@@ -131,7 +135,11 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
throw new ServiceException("验证码有误");
}
String token = JwtTokenUtil.createToken(sysUserInfo, null);
RedisUtil.set(Constants.token + token, sysUserInfo.getUserId(), JwtTokenUtil.expireTime, TimeUnit.MILLISECONDS);
RedisUtil.set(
RedisConstants.token + sysUserInfo.getPhonenumber(),
token,
Constants.expireTime,
TimeUnit.SECONDS);
return token;
}
/**
......@@ -142,7 +150,7 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
* @return: java.lang.String
*/
private Object getPhoneKey(String phone, Integer type) {
return RedisUtil.get(Constants.MSG_KEY + type + ":" + phone);
return RedisUtil.get(RedisConstants.MSG_KEY + type + ":" + phone);
}
/**
* @description: 退出
......@@ -151,8 +159,10 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
* @return: boolean
*/
@Override
public boolean logout(String token) {
return Boolean.TRUE.equals(RedisUtil.del(Constants.token + token));
public boolean logout() {
JwtInfo currentUserInfo = BaseContextHandler.getCurrentUserInfo();
String phone = currentUserInfo.getPhone();
return Boolean.TRUE.equals(RedisUtil.del(RedisConstants.token + phone));
}
/**
......@@ -175,7 +185,7 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
* @return: void
*/
private void limitSms(String phone) {
String key = Constants.LIMIT_SMS + phone;
String key = RedisConstants.LIMIT_SMS + phone;
DateTime now = DateUtil.date();
DateTime startTime = DateUtil.offsetDay(now, this.intervalTime * -1);
RedisUtil.delZset(key, 0, startTime.getTime());
......@@ -200,7 +210,7 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
throw new ServiceException("参数有误");
}
limitSms(sendPhoneVo.getPhone());
String key = Constants.MSG_KEY + sendPhoneVo.getType() + ":" + sendPhoneVo.getPhone();
String key = RedisConstants.MSG_KEY + sendPhoneVo.getType() + ":" + sendPhoneVo.getPhone();
//
Long expire = RedisUtil.getExpire(key);
// 间隔 1分钟内
......@@ -230,9 +240,10 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
.setPhone(sendPhoneVo.getPhone());
this.sysSmsLogService.save(sysSmsLog);
if (!"000000".equals(smsVo.getCode())) {
log.error("短信发送失败:{},手机号:{}", smsVo, sendPhoneVo.getPhone());
throw new ServiceException("短信发送失败,请稍后重试");
}
RedisUtil.set(key, String.valueOf(randomInt), 5, TimeUnit.MINUTES);
RedisUtil.set(key, String.valueOf(randomInt), Constants.EXPIRE_TIME, TimeUnit.MINUTES);
return true;
}
......@@ -271,11 +282,11 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
userInfo.setSalt(lyyConfig.getPasswordSalt());
// 给当前用户存储 解锁次数
RedisUtil.hPut(
Constants.LIMIT_NUM,
RedisConstants.LIMIT_NUM,
phone + ":" + BusinessTypeEnum.PARK.getCode(),
BusinessTypeEnum.PARK.getNumber());
RedisUtil.hPut(
Constants.LIMIT_NUM,
RedisConstants.LIMIT_NUM,
phone + ":" + BusinessTypeEnum.CARRIER.getCode(),
BusinessTypeEnum.CARRIER.getNumber());
// 保存一条线索信息
......@@ -303,7 +314,7 @@ public class SysUserInfoServiceImpl extends ServiceImpl<SysUserInfoMapper, SysUs
if (ObjectUtils.isEmpty(sysUserInfo)) {
throw new ServiceException("该用户不存在,请先注册");
}
String key = Constants.MSG_KEY + type + ":" + forgetVo.getPhone();
String key = RedisConstants.MSG_KEY + type + ":" + forgetVo.getPhone();
Object code = RedisUtil.get(key);
if (ObjectUtils.isEmpty(code)) {
throw new ServiceException("验证码无效,请重新发送");
......
package com.lyy.user.util.jwt;
import cn.hutool.core.bean.BeanUtil;
import com.lyy.user.config.exception.ServiceException;
import com.lyy.user.constant.TokenConstants;
import com.lyy.user.domain.JwtInfo;
import com.lyy.user.moudle.user.entity.SysUserInfo;
......@@ -9,8 +10,6 @@ import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jose.shaded.json.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import java.text.ParseException;
import java.util.HashMap;
......@@ -25,8 +24,6 @@ import java.util.Map;
*/
@Slf4j
public class JwtTokenUtil {
//15天
public static Long expireTime = 1296000000L;
/**
* 采用HS256算法生成token
......@@ -46,9 +43,7 @@ public class JwtTokenUtil {
JSONObject jsonObject = new JSONObject();
jsonObject.appendField(TokenConstants.DETAILS, jwtUser);
jsonObject.appendField(TokenConstants.AUTHORITIES, authorities);
Long current_time = System.currentTimeMillis();
Long expire_time = current_time + expireTime;
jsonObject.appendField(TokenConstants.EXPIRE_TIME, expire_time);
Payload payload = new Payload(jsonObject);
JWSObject jwsObject = new JWSObject(jwsHeader, payload);
JWSSigner jwsSigner;
......@@ -84,8 +79,8 @@ public class JwtTokenUtil {
jwsObject = JWSObject.parse(token);
jwsVerifier = new MACVerifier(TokenConstants.SECRET);
} catch (ParseException | JOSEException e) {
log.error("解析token报错", e);
return null;
log.error("解析token报错", e);
throw new ServiceException("认证失败,请重新登录");
}
return verify(jwsObject, jwsVerifier);
}
......@@ -107,7 +102,7 @@ public class JwtTokenUtil {
resultMap.put(TokenConstants.RESULT, TokenConstants.TOKEN_RESULT.TOKEN_PARSE_SUCCESS);
Map<String, Object> jsonObject = payload.toJSONObject();
resultMap.put(TokenConstants.DATA, jsonObject);
if (jsonObject.containsKey(TokenConstants.EXPIRE_TIME)) {
/*if (jsonObject.containsKey(TokenConstants.EXPIRE_TIME)) {
Long expireTime = Long.valueOf(jsonObject.get(TokenConstants.EXPIRE_TIME).toString());
Long nowTime = System.currentTimeMillis();
log.debug("nowTime : " + nowTime);
......@@ -116,13 +111,14 @@ public class JwtTokenUtil {
flag = false;
resultMap.put(TokenConstants.RESULT, TokenConstants.TOKEN_RESULT.TOKEN_EXPIRED);
}
}
}*/
} else {
flag = false;
resultMap.put(TokenConstants.RESULT, TokenConstants.TOKEN_RESULT.TOKEN_PARSE_FAILED);
throw new ServiceException("认证失败");
// resultMap.put(TokenConstants.RESULT, TokenConstants.TOKEN_RESULT.TOKEN_PARSE_FAILED);
}
} catch (JOSEException e) {
log.error("解析token报错", e);
throw new ServiceException("认证失败");
}
resultMap.put(TokenConstants.SUCCESS, flag);
return resultMap;
......@@ -138,11 +134,6 @@ public class JwtTokenUtil {
Map<String, Object> objectMap = parseToken(token);
Map<String, Object> data = (Map<String, Object>) objectMap.get(TokenConstants.DATA);
JwtInfo jwtUser = BeanUtil.toBean(data.get(TokenConstants.DETAILS), JwtInfo.class);
/*Map<String, Object> detail = (Map<String, Object>) data.get(TokenConstants.DETAILS);
JwtUser jwtUser = new JwtUser();
jwtUser.setUserId(detail.get("userId").toString());
jwtUser.setUserName(detail.get("userName").toString());
jwtUser.setPhone(detail.get("phone").toString());*/
return jwtUser;
}
}
......@@ -111,7 +111,7 @@ public class RedisUtil {
return redisTemplate.opsForValue().get(key);
}
/**
* @description: 获取key的剩余过期时间 如果key不存在 或者没有设置过期时间 返回 -1
* @description: 获取key的剩余过期时间 如果key不存在 或者没有设置过期时间 返回 -1 单位 为秒
* @date: 2023/11/23 9:53
* @param: [key]
* @return: java.lang.Long
......
......@@ -42,7 +42,7 @@ knife4j:
logging:
level:
com.lyy: debug
com.lyy.user: debug
root: info
business:
......
spring:
profiles:
active: test
active: dev
application:
name: cfld-liyeyun-user-web
main:
......
......@@ -109,7 +109,13 @@
<onMismatch>DENY</onMismatch>
</filter>
</appender>
<!--dev环境 info界别 输出到控制台-->
<springProfile name="dev">
<root level="info">
<appender-ref ref="CONSOLE"/>
</root>
</springProfile>
<!--test环境 info界别 输出到三个日志文件中-->
<springProfile name="test">
<root level="info">
<appender-ref ref="INFO_FILE"/>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment