package @app.group.id@.@app.name@.security;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

// Prevents non-ajax requests for REST services. This is to prevent Cross-Site Request Forgery (CSRF) attacks.
public class CsrfPreventionFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
        // do nothing
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String origin = request.getHeader("Origin");
        if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With")) || "OPTIONS".equalsIgnoreCase(request.getMethod()) || (origin != null && origin.trim().length() > 0)) {
            response.addHeader("Content-Security-Policy", "default-src 'self'; connect-src 'self'; font-src 'none'; img-src 'self'; media-src 'self'; object-src 'self'; plugin-types application/pdf audio/x-wav; referrer no-referrer; reflected-xss block; script-src 'self'; style-src 'self'");
            response.addHeader("X-Content-Security-Policy", "default-src 'self'; connect-src 'self'; font-src 'none'; img-src 'self'; media-src 'self'; object-src 'self'; plugin-types application/pdf audio/x-wav; referrer no-referrer; reflected-xss block; script-src 'self'; style-src 'self'");
            response.addHeader("X-Content-Type-Options", "nosniff");
            if (filterChain != null) {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("The REST service can only be accessed programmatically.");
        }
    }

    public void destroy() {
        // do nothing
    }
}
