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;

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

  @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 {
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
          "Unauthorized: Authentication token was either missing or invalid."
      );
    }
  }
}
