package com.wsm.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.regex.Pattern;

@Component
public class CommonInterceptor implements HandlerInterceptor {

    // \\b表示限定单词边界,比如 select不通过,1select则是可以的
    private static String reg = "(?:')|(?:--)|(/\\*(?:.|[\\n\\r])*?\\*/)|"
            + "(select|update|union|and|or|delete|insert|trancate|char|into|substr|ascii|declare|exec|count|master|into|drop|execute)";

    private static Pattern sqlPattern = Pattern.compile(reg, Pattern.CASE_INSENSITIVE);

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse resp, Object handler) throws Exception {
        //获得所有请求参数名
        /*Enumeration params = request.getParameterNames();
        String sql = "";
        while (params.hasMoreElements()) {
            //得到参数名
            String name = params.nextElement().toString();
            //得到参数对应值
            String[] value = request.getParameterValues(name);
            for (int i = 0; i < value.length; i++) {
                sql = sql + value[i];
            }
        }
        if (!isSQLValid(sql)){
            resp.setCharacterEncoding("UTF-8");
            resp.setContentType("application/json; charset=utf-8");

            JSONObject res = new JSONObject();
            res.put("code", -1);
            res.put("msg", "您发送请求中的参数中含有非法字符");
            PrintWriter out = resp.getWriter();
            out.append(res.toString());
            out.flush();
            out.close();
            return false;
        }*/
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        request.setAttribute("ctx", request.getContextPath());
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {

    }

    private static boolean isSQLValid(String str) {
        if (sqlPattern.matcher(str.toLowerCase()).find()) {
            return false;
        }
        return true;
    }
}
