package com.jiayue.ssi.interceptor;

import com.jiayue.ssi.constant.CacheConstants;
import com.jiayue.ssi.util.JwtTokenUtil;
import com.jiayue.ssi.util.LocalCache;
import com.jiayue.ssi.util.ResponseInfo;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 提前判断token是否需要刷新
*
* @author xsl
* @since 2023/03/07
*/
public class TokenStatusInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object handler) throws IOException {
        // 统一拦截
        String token = request.getHeader("Authorization");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        Claims claims = jwtTokenUtil.getClaimsFromToken(token);
        if (claims!=null){
            // 获取失效时间
            long expirationTime = claims.getExpiration().getTime();
            if (System.currentTimeMillis()>(expirationTime-(1000*60*4))){
                // 刷新token
                ResponseInfo.doResponse(response,"token即将失效,需要刷新!",409);
                return false;
            }
        }
        return true;
    }
}
