package com.securitycontrol.common.security.interceptor;

import com.securitycontrol.common.security.utils.XssRequestWrapper;

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

/**
 * @author：cwchen
 * @date：2024-03-01-15:07
 * @version：1.0
 * @description：过滤器，处理request
 */
@WebFilter
public class MyFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        if (servletRequest instanceof HttpServletRequest && !isFileUpload(request)) {
            requestWrapper = new XssRequestWrapper((HttpServletRequest) servletRequest);
        }
        if (requestWrapper == null) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            filterChain.doFilter(requestWrapper, servletResponse);
        }
    }

    public static final String[] EXCLUDE_URLS = {"/sys/pro/addPro","/sys/pro/editPro","/sys/pro/importProData","/back/personnel/addPersonnel","/back/personnel/editPersonnel"};

    public boolean isFileUpload(HttpServletRequest request) {
        for (String excludeUrl : EXCLUDE_URLS) {
            if (Objects.equals(excludeUrl, request.getRequestURI()) || request.getRequestURI().contains("file") || request.getRequestURI().contains("File")) {
                return true;
            }
        }
        return false;
    }
}
