package com.atlassian.stash.internal.auth;

import com.atlassian.bitbucket.auth.HttpAuthenticationContext;
import com.atlassian.bitbucket.auth.HttpAuthenticationFailureContext;
import com.atlassian.bitbucket.auth.HttpAuthenticationFailureHandler;
import com.atlassian.bitbucket.nav.NavBuilder;
import org.apache.commons.lang3.StringUtils;

import javax.annotation.Nonnull;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Authentication failure handler that redirects to the login page. Handles all authentication failures, except for
 * BASIC auth failures.
 */
public class RedirectingAuthenticationFailureHandler implements HttpAuthenticationFailureHandler {

    private static final String[] PARAMS_TO_COPY = new String[] {"next", "embedded", "permission"};

    private final NavBuilder navBuilder;

    public RedirectingAuthenticationFailureHandler(NavBuilder navBuilder) {
        this.navBuilder = navBuilder;
    }

    @Override
    public boolean onAuthenticationFailure(
            @Nonnull HttpAuthenticationFailureContext context) throws ServletException, IOException {
        if (HttpAuthenticationContext.METHOD_BASIC.equals(context.getMethod())) {
            // don't redirect on BASIC authentication
            return false;
        }

        context.getResponse().sendRedirect(buildRedirectUrl(context.getRequest()));
        return true;
    }

    private String buildRedirectUrl(HttpServletRequest request) {
        NavBuilder.Builder<?> login = navBuilder.login();

        for (String paramName : PARAMS_TO_COPY) {
            String paramValue = request.getParameter(paramName);
            if (StringUtils.isNotBlank(paramValue)) {
                login = login.withParam(paramName, paramValue);
            }
        }

        return login.buildRelative();
    }
}
