package net.curisit.securis; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.ForbiddenException; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import net.curisit.securis.services.exception.SeCurisServiceException; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; @Provider public class DefaultExceptionHandler implements ExceptionMapper { private static final Logger LOG = LogManager.getLogger(DefaultExceptionHandler.class); public static final String ERROR_MESSAGE_HEADER = "X-SECURIS-ERROR"; public DefaultExceptionHandler() { LOG.info("Creating DefaultExceptionHandler "); } @Context HttpServletRequest request; @Context SecurityContext bsc; @Override public Response toResponse(Exception e) { if (e instanceof ForbiddenException) { LOG.warn("Unauthorized access to {}, user: {}", request.getPathInfo(), bsc.getUserPrincipal()); return Response.status(Status.UNAUTHORIZED).header(ERROR_MESSAGE_HEADER, "Unathorized access to the application").type(MediaType.APPLICATION_JSON).build(); } if (e instanceof SeCurisServiceException) { LOG.warn("SeCurisServiceException accessing to {}, user: {}", request.getPathInfo(), bsc.getUserPrincipal()); return Response.status(Status.fromStatusCode(((SeCurisServiceException) e).getStatus())).header(ERROR_MESSAGE_HEADER, e.getMessage()).type(MediaType.APPLICATION_JSON).build(); } LOG.error("Unexpected error accesing to '{}' by user: {}", request.getPathInfo(), bsc.getUserPrincipal()); LOG.error("Request sent from {}, with User-Agent: {}", request.getRemoteHost(), request.getHeader("User-Agent")); LOG.error("Request url: " + request.getRequestURL(), e); return Response.serverError().header(ERROR_MESSAGE_HEADER, "Unexpected error: " + e.toString()).type(MediaType.APPLICATION_JSON).build(); } }