3 import jakarta.servlet.http.HttpServletRequest;
4 import jakarta.servlet.http.HttpServletResponse;
5 import lombok.extern.slf4j.Slf4j;
6 import org.springframework.http.HttpStatus;
7 import org.springframework.stereotype.Component;
8 import org.springframework.web.method.HandlerMethod;
9 import org.springframework.web.servlet.HandlerInterceptor;
11 import java.io.IOException;
16 public class RequestTypeInterceptor implements HandlerInterceptor
18 public final static String REQUEST_TYPE = "X-Request-Type";
20 public enum RequestType { HUMAN, MACHINE };
24 public boolean preHandle(
25 HttpServletRequest request,
26 HttpServletResponse response,
27 Object handler) throws IOException
29 // Only instances of HandlerMethod are intercepted for the type of the request
30 if (!(handler instanceof HandlerMethod))
32 log.trace("Ignoring handler of type {}", handler);
36 String requestTypeHeader = request.getHeader(REQUEST_TYPE);
37 if (requestTypeHeader == null)
39 sendBadRequest(response, "Ignoring request without header");
45 RequestType requestType = RequestType.valueOf(requestTypeHeader.toUpperCase());
47 if (requestType == RequestType.MACHINE)
49 log.debug("Accepting machine-request for {}", handler);
53 if (((HandlerMethod)handler).getMethod().getAnnotation(RequestableByHumans.class) != null)
55 log.info("Accepting human request for {}", handler);
60 sendForbidden(response, "Human requests are not allowed for " + handler);
64 catch (IllegalArgumentException e)
66 log.warn("Invalid RequestType: {}", e.toString());
69 sendBadRequest(response, requestTypeHeader);
74 HttpServletResponse response,
75 String message) throws IOException
77 log.warn("Forbidden: {}", message);
78 response.sendError(HttpStatus.FORBIDDEN.value(), message);
82 HttpServletResponse response,
83 String message) throws IOException
85 log.warn("Bad request: {}", message);
86 response.sendError(HttpStatus.BAD_REQUEST.value(), message);