package ru.micord.ervu.security.webbpm.jwt;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import ru.micord.ervu.security.webbpm.jwt.helper.SecurityHelper;

/**
 * {@link AuthenticationEntryPoint} that rejects all requests with an unauthorized error message.
 */
public class UnauthorizedEntryPoint implements AuthenticationEntryPoint {

  private final SecurityHelper securityHelper;

  public UnauthorizedEntryPoint(SecurityHelper securityHelper) {
    this.securityHelper = securityHelper;
  }

  @Override
  public void commence(HttpServletRequest request, HttpServletResponse response,
                       AuthenticationException exception) throws IOException {

    //for correct work with cross domain request
    if ("OPTIONS".equals(request.getMethod())) {
      response.setStatus(HttpServletResponse.SC_OK);
    }
    else {
      securityHelper.clearAccessCookies(response);
      response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      response.setContentType("application/json;charset=UTF-8");
      response.getWriter()
          .write("\"Unauthorized: Authentication token was either missing or invalid.\"");
    }
  }
}
