package eu.dnetlib.simplesso;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

public class SimpleSSOAuthenticationEntryPoint implements AuthenticationEntryPoint {

	private static final Log log = LogFactory.getLog(SimpleSSOAuthenticationEntryPoint.class); // NOPMD by marko on 11/24/08 5:02 PM

	private String authUrl;

	private boolean enabled = false;

	@Override
	public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException,
			ServletException {
		if (!enabled) {
			log.error("sso disabled but anon auth failed, sending error", authException);
			HttpServletResponse httpResponse = response;
			httpResponse.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");

		} else {
			log.debug("redirecting to auth server");

			HttpServletRequest httpRequest = request;
			HttpServletResponse httpResponse = response;

			String redirectUrl = authUrl + "?url=" + URLEncoder.encode(httpRequest.getRequestURL().toString(), "UTF-8");
			httpResponse.sendRedirect(redirectUrl);
		}

	}

	public String getAuthUrl() {
		return authUrl;
	}

	public void setAuthUrl(final String authUrl) {
		this.authUrl = authUrl;
	}

	public boolean isEnabled() {
		return enabled;
	}

	public void setEnabled(final boolean enabled) {
		this.enabled = enabled;
	}

}
