package com.atlassian.stash.internal.auth;

import com.atlassian.bitbucket.auth.HttpAuthenticationContext;
import com.atlassian.bitbucket.auth.HttpAuthenticationSuccessContext;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import javax.servlet.http.HttpServletRequest;

public class HttpAuthUtils {

    public static final String HEADER_AUTHORIZATION = "Authorization";
    public static final String AUTH_PREFIX_BASIC = "Basic ";

    private HttpAuthUtils() {
    }

    public static boolean isBasicAuth(@Nonnull HttpAuthenticationSuccessContext context) {
        return HttpAuthenticationContext.METHOD_BASIC.equals(context.getMethod());
    }

    public static boolean isBasicAuth(@Nonnull HttpServletRequest request) {
        String authorization = request.getHeader(HEADER_AUTHORIZATION);
        return authorization != null && authorization.startsWith(AUTH_PREFIX_BASIC);
    }

    public static boolean isRestCall(@Nonnull HttpAuthenticationSuccessContext context) {
        return isRestCall(context.getRequest());
    }

    public static boolean isRestCall(@Nonnull HttpServletRequest request) {
        String relativeUrl = request.getRequestURI();
        if (StringUtils.isBlank(request.getContextPath()) || StringUtils.isBlank(relativeUrl)) {
            return false;
        }
        relativeUrl = relativeUrl.substring(request.getContextPath().length());
        return relativeUrl.startsWith("/rest/") || relativeUrl.equals("/status");
    }

    @Nullable
    public static String getBasicAuthHeaderValue(@Nonnull HttpServletRequest request) {
        if (!isBasicAuth(request)) {
            return null;
        }

        return request.getHeader(HEADER_AUTHORIZATION).substring(AUTH_PREFIX_BASIC.length());
    }
}
