package com.huimv.apiservice.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.huimv.common.utils.R;

import com.huimv.common.utils.TokenUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

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

/**
 * <p>
 *  jwt拦截器
 * </p>
 * @author yinhao
 * @since 2021/4/19
 */

public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法，则直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }

        if (response.getStatus() == 404 || response.getStatus() == 500) {
            return false;
        }

        response.setContentType("application/json;charset=utf-8");

        // 获取token
        String accessToken = request.getParameter("accessToken");

        if (StringUtils.isEmpty(accessToken) || !TokenUtil.verify(accessToken)) {
            response.getWriter().write(JSONObject.toJSONString(R.error(1007,"无效令牌,请重新申请!")));
            return false;
        }
        return true;
    }


}