package ru.yandex.qe.dispenser.security;

import java.io.IOException;
import java.io.PrintWriter;

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

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

/**
 * @author lvovich
 */
public class Http401UnauthorizedEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
        final int status;
        if (authException instanceof AuthenticationServiceException) {
            status = HttpServletResponse.SC_SERVICE_UNAVAILABLE;
        } else {
            status = HttpServletResponse.SC_UNAUTHORIZED;
        }
        response.setStatus(status);
        response.setHeader("DeniedReason", "Invalid or missing credentials");
        response.setHeader("WWW-Authenticate", "OAuth realm=\"https://auth.yandex-team.ru/\"");
        final PrintWriter writer = response.getWriter();
        writer.println(authException.getMessage());
        writer.close();
    }
}
