package com.nbclass.Interceptor;

import com.alibaba.druid.util.StringUtils;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.nbclass.exception.ParameterException;
import com.nbclass.util.JWTUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author admin
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)){
            throw new ParameterException("token不能为空");
        }
        try {
            Claims claims = JWTUtils.parseJWT(token);
            //获取token的签发时间
            long issuedAt = claims.getIssuedAt().getTime();
            //获取token的过期时间
            long expiration = claims.getExpiration().getTime();
            if(expiration < issuedAt){
                throw new  ParameterException("token已过期!");
            }
        } catch (Exception e) {
            log.error("token无效！ 错误 ->", e);
            throw new ParameterException("token无效!");
        }
        return true;
    }
}
