package com.test.bijihoudaun.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HtmlUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Arrays;
import java.util.Map;

public class XSSInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 清理请求参数中的XSS内容
        Map<String, String[]> parameterMap = request.getParameterMap();
        parameterMap.forEach((key, values) -> {
            String[] newValues = Arrays.stream(values)
                    .map(v -> StrUtil.isBlank(v) ? v : HtmlUtil.filter(v))
                    .toArray(String[]::new);
            request.setAttribute("filtered_" + key, newValues);
        });
        return true;
    }
}
