package com.hotent.base.filter;

import com.hotent.base.conf.SecurityConfig;
import com.hotent.base.request.SqlInjectHttpServletRequestWrapper;
import com.hotent.base.util.AppUtil;
import com.hotent.base.util.BeanUtils;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.FilterConfig;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SQL注入过滤器
 *
 * @author jason
 *
 */
@Component
@WebFilter(filterName = "SqlInjectFilter", urlPatterns = "/*")
public class SqlInjectFilter implements Filter {
    private SecurityConfig securityConfig;
    /**
     * 拦截
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        //获取安全配置
        if(securityConfig == null){
            securityConfig = AppUtil.getBean(SecurityConfig.class, request);
        }
        // 不启用或者已忽略的URL不拦截
        if (!securityConfig.isEnabled() || isExcludeUrl(request.getServletPath())) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }
        SqlInjectHttpServletRequestWrapper sqlInjectHttpServletRequestWrapper = new SqlInjectHttpServletRequestWrapper(
                request);
        filterChain.doFilter(sqlInjectHttpServletRequestWrapper, servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}
    /**
     * 销毁
     */
    @Override
    public void destroy() {
    }
    /**
     * 判断是否为忽略的URL
     *
     * @param url URL路径
     * @return true-忽略，false-过滤
     */
    private boolean isExcludeUrl(String url) {
        List<String> sqlExcludes = securityConfig.getSqlExcludes();

        if (BeanUtils.isEmpty(sqlExcludes)) {
            return false;
        }
        return sqlExcludes .stream().map(pattern -> Pattern.compile("^" + pattern)).map(p -> p.matcher(url))
                .anyMatch(Matcher::find);
    }
}
