package com.ag.secp.platform.jwt;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTException;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: JWT拦截类
 * Author: songwp
 * Version: 1.0
 * Create Date: 2021/12/24
 */
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头里的令牌
        String token = request.getHeader(ResultCode.TOKEN_KEY);
        //ResultCode.TOKEN_KEY_HEADER_AUTHORIZATION
        //ResultCode.TOKEN_KEY_HEADER_AUTHORIZATION_BEARER
        boolean isSuccess;
        try {
            //验证签名
            isSuccess = JWTUtil.verify(token, JWTTokenForHS256.getTokenSecretByte());
            //验证算法
            JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256(JWTTokenForHS256.getTokenSecretByte()))
                    .validateDate(DateUtil.date());
        }catch (ValidateException exception){
            isSuccess = false;
        }catch(JWTException e){
            isSuccess = false;
        }
        if(isSuccess){
            return true;
        }else {
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().println(JSONUtil.parseObj(R.failedToken()));
            return false;
        }

    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
