package com.ningdatech.carapi.common.filter;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description: sql注入过滤
 * @author: liushuai
 * @date: 2022/3/25 11:42
 */
@Component
@Configuration
@ConfigurationProperties(prefix = "security.sql")
@WebFilter(filterName = "SqlInjectFilter", urlPatterns = "/*")
public class SqlInjectFilter implements Filter {
    /**
     * 过滤器配置对象
     */
    FilterConfig filterConfig = null;

    /**
     * 忽略的URL
     */
    private List<String> excludes;

    public void setExcludes(List<String> excludes) {
        this.excludes = excludes;
    }

    /**
     * 初始化
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    /**
     * 拦截
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 已忽略的URL不拦截
        if (isExcludeUrl(request.getServletPath())) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        //获得所有请求参数名
        Enumeration<String> names = request.getParameterNames();
        while (names.hasMoreElements()) {
            //得到参数名
            String name = names.nextElement();
            //得到参数对应值
            String[] values = request.getParameterValues(name);
            for (String value : values) {
                if (sqlValidate(value)) {
                    throw new IOException("您发送请求中的参数中含有非法字符");
                }
            }
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 销毁
     */
    @Override
    public void destroy() {
        this.filterConfig = null;
    }

    /**
     * 判断是否为忽略的URL
     *
     * @param url URL路径
     * @return true-忽略，false-过滤
     */
    private boolean isExcludeUrl(String url) {
        if (excludes == null || excludes.isEmpty()) {
            return false;
        }
        return excludes.stream().map(pattern -> Pattern.compile("^" + pattern)).map(p -> p.matcher(url))
                .anyMatch(Matcher::find);
    }

    protected static boolean sqlValidate(String str) {
        //统一转为小写
        String s = str.toLowerCase();
        //过滤掉的sql关键字，特殊字符前面需要加\\进行转义
        String badStr =
                "select|update|and|or|delete|insert|truncate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute|table|" +
                        "char|declare|sitename|xp_cmdshell|like|from|grant|use|group_concat|column_name|" +
                        "information_schema.columns|table_schema|union|where|order|by";
        //使用正则表达式进行匹配
        return s.matches(badStr);
    }
}
