package cc.smtweb.framework.core.mvc.filter;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @Author yaoq
 * @Date 2022年07月20日 10:38
 * @Description
 */
@Slf4j
@Component
@Data
@ConfigurationProperties(prefix = "http-config.xss")
public class XssSecurityConfig implements InitializingBean {

    private boolean checkHeader;

    private boolean checkParameter;

    private boolean logIs;

    private boolean chain;

    private boolean replace;

    private boolean checkUrl;

    private List<String> regex;


    /**
     * 替换非法字符的字符串
     */
    private String REPLACEMENT = "";

    /**
     * FILTER_ERROR_PAGE:过滤后错误页面
     */
    private String FILTER_ERROR_PAGE = "/jsp/framework/error/405.jsp";

    /**
     * REGEX：校验正则表达式
     */
    private String regexStr;

    /**
     * 特殊字符匹配
     */
    private Pattern XSS_PATTERN;


    @Override
    public void afterPropertiesSet() throws Exception {
        if (!initSuccess()) {
            return;
        }
        StringBuffer tempStr = new StringBuffer("^");
        regex.forEach(k -> {
            tempStr.append(k);
            tempStr.append("|");
        });
        regexStr = tempStr.substring(0, tempStr.length() - 1) + "$";
        XSS_PATTERN = Pattern.compile(regexStr);
    }

    @Override
    public String toString() {
        return "XssSecurityConfig{" +
                "checkHeader=" + checkHeader +
                ", checkParameter=" + checkParameter +
                ", logIs=" + logIs +
                ", chain=" + chain +
                ", replace=" + replace +
                ", checkUrl=" + checkUrl +
                ", regex=" + regex +
                '}';
    }

    /**
     * 对非法字符进行替换
     *
     * @param text
     * @return
     */
    public String securityReplace(String text) {
        if (!initSuccess()) return text;
        if (StringUtils.isEmpty(text)) {
            return text;
        } else {
            return text.replaceAll(regexStr, REPLACEMENT);
        }
    }

    /**
     * 匹配字符是否含特殊字符
     *
     * @param text
     * @return
     */
    public boolean matches(String text) {
        if (!initSuccess()) return false;
        if (StringUtils.isEmpty(text)) {
            return false;
        }
        return XSS_PATTERN.matcher(text).matches();
    }

    private boolean initSuccess() {
        return regex != null && regex.size() > 0;
    }
}


