package com.ssj.framework.core.xss;

import com.alibaba.fastjson.JSON;
import com.ssj.bean.common.framework.core.domain.Response;
import org.apache.commons.lang3.StringUtils;

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




@WebFilter(filterName = "xssFilter", urlPatterns = { "/*" })
public class XssFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) {
        // no init operation
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String contentType = ((HttpServletRequest) request).getHeader("Content-Type");
        if(contentType!=null && contentType.contains("multipart/form-data")) {
            filterChain.doFilter(request, servletResponse);
        }else{
            XssAndSqlHttpServletRequestWrapper xssRequest = new XssAndSqlHttpServletRequestWrapper(
                    request);
            String method = ((HttpServletRequest) request).getMethod();
            String param = "";
            if ("POST".equalsIgnoreCase(method)) {
                param = XssFilter.getBodyString(xssRequest.getReader());
                if (StringUtils.isNotBlank(param)) {
                    if (xssRequest.checkXSSAndSql(param)) {
                        servletResponse.setCharacterEncoding("UTF-8");
                        servletResponse.setContentType("application/json;charset=UTF-8");
                        PrintWriter out = servletResponse.getWriter();
                        out.write(JSON.toJSONString(new Response().failure()));
                        return;
                    }
                }
            }
            if (xssRequest.checkParameter()) {
                servletResponse.setCharacterEncoding("UTF-8");
                servletResponse.setContentType("application/json;charset=UTF-8");
                PrintWriter out = servletResponse.getWriter();
                out.write(JSON.toJSONString(new Response().failure()));
                return;
            }
            filterChain.doFilter(xssRequest, servletResponse);
        }


    }

    // 获取request请求body中参数
    public static String getBodyString(BufferedReader br) {
        String inputLine;
        String str = "";
        try {
            while ((inputLine = br.readLine()) != null) {
                str += inputLine;
            }
            br.close();
        } catch (IOException e) {
            System.out.println("IOException: " + e);
        }
        return str;

    }

    @Override
    public void destroy() {
        // no destroy operation
    }
}


