You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.0 KiB
69 lines
2.0 KiB
package com.example.utils;
|
|
|
|
import cn.hutool.core.date.DateUtil;
|
|
import cn.hutool.core.util.ObjectUtil;
|
|
import com.auth0.jwt.JWT;
|
|
import com.auth0.jwt.JWTVerifier;
|
|
import com.auth0.jwt.algorithms.Algorithm;
|
|
import com.example.common.Constants;
|
|
import com.example.entity.UserInfo;
|
|
import com.example.mapper.SystemMapper;
|
|
import com.example.service.UserService;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.stereotype.Component;
|
|
import org.springframework.web.context.request.RequestContextHolder;
|
|
import org.springframework.web.context.request.ServletRequestAttributes;
|
|
|
|
import javax.annotation.PostConstruct;
|
|
import javax.annotation.Resource;
|
|
import javax.servlet.http.HttpServletRequest;
|
|
import java.util.Date;
|
|
|
|
/**
|
|
* Token工具类
|
|
*/
|
|
@Component
|
|
public class TokenUtils {
|
|
|
|
private static final Logger log = LoggerFactory.getLogger(TokenUtils.class);
|
|
|
|
private static UserService staticUserService;
|
|
|
|
@Resource
|
|
UserService userService;
|
|
|
|
@PostConstruct
|
|
public void setUserService() {
|
|
staticUserService = userService;
|
|
}
|
|
|
|
/**
|
|
* 生成token
|
|
*/
|
|
public static String createToken(String data, String sign) {
|
|
return JWT.create().withAudience(data)
|
|
.withExpiresAt(DateUtil.offsetHour(new Date(), 2))
|
|
.sign(Algorithm.HMAC256(sign));
|
|
}
|
|
|
|
/**
|
|
* 获取当前登录的用户信息
|
|
*/
|
|
public static UserInfo getCurrentUser() {
|
|
try {
|
|
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
|
String token = request.getHeader(Constants.TOKEN);
|
|
if (ObjectUtil.isNotEmpty(token)) {
|
|
|
|
String userId = JWT.decode(token).getAudience().get(0);
|
|
return staticUserService.selectById(Integer.valueOf(userId));
|
|
}
|
|
} catch (Exception e) {
|
|
log.error("获取当前用户信息出错", e);
|
|
}
|
|
return new UserInfo(); // 返回空的账号对象
|
|
}
|
|
}
|
|
|