001package com.thetransactioncompany.cors;
002
003
004import javax.servlet.http.HttpServletRequest;
005
006
007/**
008 * Request tagger. Tags HTTP servlet requests to provide CORS information to 
009 * downstream handlers.
010 *
011 * @author Vladimir Dzhuvinov
012 */
013public final class RequestTagger {
014
015
016        /**
017         * Tags an HTTP servlet request to provide CORS information to 
018         * downstream handlers.
019         *
020         * <p>Tagging is provided via {@code HttpServletRequest.setAttribute()}.
021         *
022         * <ul>
023         *     <li>{@code cors.isCorsRequest} set to {@code true} or 
024         *         {@code false}.
025         *     <li>{@code cors.origin} set to the value of the "Origin" header, 
026         *         {@code null} if undefined.
027         *     <li>{@code cors.requestType} set to "actual" or "preflight" (for 
028         *         CORS requests).
029         *     <li>{@code cors.requestHeaders} set to the value of the 
030         *         "Access-Control-Request-Headers" or {@code null} if 
031         *         undefined (added for preflight CORS requests only).
032         * </ul>
033         *
034         * @param request The servlet request to inspect and tag. Must not be
035         *                {@code null}.
036         * @param type    The detected request type. Must not be {@code null}.
037         */
038        public static void tag(final HttpServletRequest request,
039                               final CORSRequestType type) {
040
041                switch (type) {
042
043                        case ACTUAL:
044                                request.setAttribute("cors.isCorsRequest", true);
045                                request.setAttribute("cors.origin", request.getHeader(HeaderName.ORIGIN));
046                                request.setAttribute("cors.requestType", "actual");
047                                break;
048
049                        case PREFLIGHT:
050                                request.setAttribute("cors.isCorsRequest", true);
051                                request.setAttribute("cors.origin", request.getHeader(HeaderName.ORIGIN));
052                                request.setAttribute("cors.requestType", "preflight");
053                                request.setAttribute("cors.requestHeaders", request.getHeader(HeaderName.ACCESS_CONTROL_REQUEST_HEADERS));
054                                break;
055
056                        case OTHER:
057                                request.setAttribute("cors.isCorsRequest", false);
058                }
059        }
060}