package com.wb.common;

import com.ag.base.IRedisService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private HttpServletRequest orgRequest = null;
    private List<KvBean> filterKeys;
    private List<KvBean> permitUrls;

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        orgRequest = request;
        WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
        IRedisService redisService = (IRedisService)wac.getBean("redisServiceImpl");
        this.filterKeys = redisService.getAllByKey("XSS_FILTER_KEY");
        this.permitUrls = redisService.getAllByKey("XSS_PERMIT_URL");
    }

    /**
     * 针对wb获取请求参数的方法重写
     * @return
     */
    @Override
    public Map<String, String[]> getParameterMap(){
        Map<String, String[]> map = new HashMap<>();
        for (Map.Entry<String, String[]> entry : orgRequest.getParameterMap().entrySet()) {
            String val = entry.getValue()[0];
            map.put(xssEncode(entry.getKey()), new String[]{xssEncode(val)});
        }
        return map;
    }

    /**
     * 覆盖getParameter方法，将参数名和参数值都做xss过滤
     */
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(xssEncode(name));
        if (value != null) {
            value = xssEncode(value);
        }
        return value;
    }
    /**
     * 覆盖getParameterValues方法，将参数名和参数值都做xss过滤
     */
    public String[] getParameterValues(String parameter) {
        String[] values = super.getParameterValues(parameter);
        if (values==null)  {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = xssEncode(values[i]);
        }
        return encodedValues;
    }

    /**
     * 获取request的属性时，做xss过滤
     */
    @Override
    public Object getAttribute(String name) {
        Object value = super.getAttribute(xssEncode(name));
        if (null != value && value instanceof String) {
            value = xssEncode((String) value);
        }
        return value;
    };

    /**
     * 覆盖getHeader方法，将参数名和参数值都做xss过滤。<br/>
     */
    @Override
    public String getHeader(String name) {
        String value = super.getHeader(xssEncode(name));
        if (value != null) {
            value = xssEncode(value);
        }
        return value;
    }


    /**
     * 将容易引起xss漏洞的半角字符直接替换成全角字符
     *
     * @param
     * @return
     */
//    private static String xssEncode(String s) {
//        return XssEncode.xssEncode(s);
//    }
    private String xssEncode(String value) {
        //You'll need to remove the spaces from the html entities below
//        value = value.replaceAll("\\<", "& lt;").replaceAll("\\>", "& gt;");
//        value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
//        value = value.replaceAll("'", "& #39;");
        if (value == null){
            return null;
        }
        String upperVal = value.toUpperCase();
        if (upperVal.contains("HTTP:") || upperVal.contains("HTTPS:")){
            boolean isHold = true;//默认拦截
            //url存在列表中，不拦截
            for (KvBean kvBean : permitUrls){
                //强验证url路径必须一致，防止参数里传url
                if (upperVal.indexOf(kvBean.getV().toUpperCase()) == 0){
                    isHold = false;
                    break;
                }
            }
            if (isHold){
                return XssEncode.xssEncode(value);
            }
        }

        //只要含有过滤关键字，直接进行xss处理
        for (KvBean kvBean : filterKeys){
            if (upperVal.contains(kvBean.getV().toUpperCase())){
                return XssEncode.xssEncode(value);
            }
        }
        //正常结果
        return value;
    }

    /**
     * 获取最原始的request
     *
     * @return
     */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }

    /**
     * 获取最原始的request的静态方法
     *
     * @return
     */
    public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
        if (req instanceof XssHttpServletRequestWrapper) {
            return ((XssHttpServletRequestWrapper) req).getOrgRequest();
        }

        return req;
    }


}