package org.keycloak.adapters.springsecurity.authentication;

import org.apache.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.servlet.http.HttpServletRequest;

/**
 * {@link RequestMatcher} that determines if a given request is an API request or an
 * interactive login request.
 *
 * @author <a href="mailto:srossillo@smartling.com">Scott Rossillo</a>
 * @see RequestMatcher
 */
public class HttpHeaderInspectingApiRequestMatcher implements RequestMatcher {

    protected static final String X_REQUESTED_WITH_HEADER = "X-Requested-With";
    protected static final String X_REQUESTED_WITH_HEADER_AJAX_VALUE = "XMLHttpRequest";

    /**
     * Returns true if the given request is an API request or false if it's an interactive
     * login request.
     *
     * @param request the <code>HttpServletRequest</code>
     * @return <code>true</code> if the given <code>request</code> is an API request;
     * <code>false</code> otherwise
     */
    @Override
    public boolean matches(HttpServletRequest request) {
        boolean ajax = X_REQUESTED_WITH_HEADER_AJAX_VALUE.equals(request.getHeader(X_REQUESTED_WITH_HEADER));
        boolean html = request.getHeader(HttpHeaders.ACCEPT) != null && request.getHeader(HttpHeaders.ACCEPT).contains(
                MediaType.TEXT_HTML_VALUE);

        return ajax || !html;
    }

}
