package com.jiayue.ssi.filter;


import com.jiayue.ssi.servlet.XssKeywordsHttpServletRequestWrapper;
import com.jiayue.ssi.util.ResponseInfo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * xss和sql过滤器
 *
 * @author xsl
 * @since 2023/05/16
 */
@RequiredArgsConstructor
@Order(5)
@Slf4j
public class XssKeywordsFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) {
        try {
            XssKeywordsHttpServletRequestWrapper xssRequest = new XssKeywordsHttpServletRequestWrapper(request);
            if (xssRequest.checkParameter()) {
                ResponseInfo.doResponse(response, "您所访问的页面请求中有违反安全规则元素存在，拒绝访问!", 410);
                return;
            }
            filterChain.doFilter(xssRequest, response);
        } catch (Exception e) {
            ResponseInfo.doResponse(response, "访问失败,联系管理员！", 401);
            return;
        }
    }

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

    @Override
    public void destroy() {

    }
}
