package org.jeecg.config.init;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
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.ArrayList;
import java.util.Arrays;
import java.util.List;


/**
 * http host头攻击漏洞处理过滤器，
 * 需要在配置文件添加allowed.servernames可访问host白名单，
 * 多个host用逗号隔开，本地开发使用127.0.0.1,localhost
 * @author liufr
 */
@Component
@Order(1)
public class HostFilter implements Filter{
    /**
     * 自定义实现host白名单添加
     */
    @Value("${allowed.servernames}")
    private String ALLOWED_SERVERNAMES;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//	    System.out.println("Filter初始化中");
    }

    /**
     * host拦截
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
	    String host = request.getHeader("host");
//        String serverName = request.getServerName();
        response.addHeader("X-XSS-Protection","1;mode=block");
        response.addHeader("Content-Security-Policy","object-src 'self'");
        response.addHeader("X-frame-options","ALLOW-FROM 'https://10.68.224.124:8081'");
        response.addHeader("X-Content-Type-Options","nosniff");

        if (!isEmpty(host)) {
            if (checkBlankList(host)) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                System.out.println("[serverName deny access tips]->" + host);
//	        response.getWriter().print("host deny");
                response.setStatus(403);
                response.flushBuffer();
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }

    @Override
    public void destroy() {
//	    System.out.println("Filter销毁");
    }

    /**
     * 校验当前host是否在白名单中
     */
    private boolean checkBlankList(String serverName) {
        String[] allowdServerName = ALLOWED_SERVERNAMES.split(",");
        List<String> serverNameList = Arrays.asList(allowdServerName);
        for(String str : serverNameList){
            if(!isEmpty(str) && str.equals(serverName)){
                return true;
            }
        }
        return false;
    }

    /**
     * 判空
     */
    public boolean isEmpty(Object str) {
        return str == null || "".equals(str);
    }


}