package cn.com.victorysoft.business.filter;

import cn.com.victorysoft.business.util.JwtUtils;
import cn.com.victorysoft.business.util.StringUtils;
import org.springframework.util.AntPathMatcher;

import javax.servlet.FilterConfig;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * JWT过滤器
 */
public class JwtFilter implements Filter {

    private String[] noFilterUrls;
    private final org.springframework.util.PathMatcher pathMatcher = new AntPathMatcher();
    private final String TOKEN_PREFIX = "Bearer";
    private final String HEADER_STRING = "Authorization";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        noFilterUrls = filterConfig.getInitParameter("noFilterUrls").split(";");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String path = httpRequest.getServletPath();
        String token = httpRequest.getHeader(HEADER_STRING);
        // 不受保护的接口
        for (String url : noFilterUrls) {
            if (pathMatcher.match(url, path)) {
                chain.doFilter(request, response);
                return;
            }
        }
        if (StringUtils.isEmpty(token)) {
            httpResponse.sendRedirect("/siam");
            return;
        }
        boolean success = JwtUtils.verifyToken(token);
        if (!success) {
//            httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "未授权或者授权已经过期");
            httpResponse.sendRedirect("/siam");
            return;
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
