package com.lovenav.filter;


import com.alibaba.fastjson.JSON;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovenav.utils.TokenUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class UserInterceptor implements HandlerInterceptor {


    //Controller逻辑执行之前
@Autowired
    private TokenUtils tokenUtils;

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object obj, Exception e)
            throws Exception {

    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object obj, ModelAndView mav)
            throws Exception {

    }

    // 拦截每个请求
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws IOException {
        Map<String,Object> map=new HashMap<>();
        System.out.println("开始进入拦截器检验jwt头部是否含有Authorization方法！");
        // 通过url得到token请求头是否包含Authorization
        response.setCharacterEncoding("UTF-8");
        String jwt = request.getHeader("Authorization");
        if (jwt==null){
            map.put("msg","请求头中不含token");
            response.getWriter().print(JSON.toJSONString(map));
            return false;
        }
        try {
            Claims c = TokenUtils.verifyJwt(jwt);
            return true;
            // 检测请求头是否为空
        } catch (TokenExpiredException e) {
            map.put("state", false);
            map.put("msg", "Token已经过期!!!");
        }  catch (SignatureVerificationException e){
            map.put("state", false);
            map.put("msg", "签名错误!!!");
        } catch (AlgorithmMismatchException e){
            map.put("state", false);
            map.put("msg", "加密算法不匹配!!!");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", "无效token");
        }
        response.getWriter().print(JSON.toJSONString(map));
        return false;
    }

}