package com.example.mtusi_messenger.security; import com.example.mtusi_messenger.dto.ErrorResponse; import com.example.mtusi_messenger.web.RequestIdFilter; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import org.springframework.http.MediaType; import org.springframework.security.core.AuthenticationException; import org.springframework.security.authentication.AuthenticationServiceException; import org.springframework.security.web.AuthenticationEntryPoint; import java.io.IOException; public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { private final ObjectMapper mapper; private final String challenge; public RestAuthenticationEntryPoint(ObjectMapper mapper, String challenge) { this.mapper = mapper; this.challenge = challenge; } @Override public void commence( HttpServletRequest request, HttpServletResponse response, AuthenticationException exception ) throws IOException { String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE); boolean unavailable = exception instanceof AuthenticationServiceException; response.setStatus(unavailable ? HttpServletResponse.SC_SERVICE_UNAVAILABLE : HttpServletResponse.SC_UNAUTHORIZED); response.setContentType(MediaType.APPLICATION_JSON_VALUE); response.setCharacterEncoding("UTF-8"); if (!unavailable) { response.setHeader("WWW-Authenticate", challenge); } mapper.writeValue(response.getOutputStream(), new ErrorResponse( new ErrorResponse.ErrorBody( unavailable ? "unavailable" : "unauthorized", unavailable ? "Authentication service temporarily unavailable" : "Authentication required", requestId))); } }