package egovframework.filter;

import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * XSS 공격 방지를 위한 필터
 * 모든 요청과 응답에 대해 XSS 필터링을 적용
 */
public class XssFilter extends OncePerRequestFilter {

    private final XssUtil xssUtil;

    public XssFilter(XssUtil xssUtil) {
        this.xssUtil = xssUtil;
    }

    @Override
    protected void doFilterInternal(@Nullable HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        // XSS 방지를 위한 헤더 설정
        response.setHeader("X-XSS-Protection", "1; mode=block");
        response.setHeader("X-Content-Type-Options", "nosniff");

        // 요청을 래핑하여 XSS 필터링 적용
        XssRequestWrapper xssRequestWrapper = new XssRequestWrapper(request, xssUtil);

        // 필터 체인 실행
        filterChain.doFilter(xssRequestWrapper, response);
    }
}
