package org.jeecg.common.filter;

import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.ProductAuthUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

@WebFilter(urlPatterns = "/*")
public class XssFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(XssFilter.class);

    FilterConfig filterConfig = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        logger.info("自定义过滤器->doFilter");
        if (!ProductAuthUtil.verify()) {
            throw new JeecgBootException("程序异常，请联系供应商");
        }
        //自加响应头
        HttpServletResponse resp = (HttpServletResponse)response;
        resp.addHeader("Content-Security-Policy","policy");
        resp.addHeader("X-Content-Type-Options","niff");
        resp.addHeader("X-XSS-Protection","1");

        chain.doFilter(new XssHttpServletRequestWrapper(
                (HttpServletRequest) request), response);
    }
}
