little login fixum

This commit is contained in:
Stepan Usatiuk
2023-12-16 16:48:58 +01:00
parent ab566ebf24
commit 22aa0585ea
7 changed files with 53 additions and 5 deletions

View File

@@ -6,11 +6,16 @@ import jakarta.validation.ConstraintViolationException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.util.List;
import java.util.Objects;
@ControllerAdvice
public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(value = {ConstraintViolationException.class})
@@ -19,4 +24,25 @@ public class ApiExceptionHandler extends ResponseEntityExceptionHandler {
new ErrorTo(ex.getConstraintViolations().stream().map(ConstraintViolation::getMessage), HttpStatus.BAD_REQUEST.value()),
new HttpHeaders(), HttpStatus.BAD_REQUEST, request);
}
@ExceptionHandler(value = {AuthenticationException.class})
protected ResponseEntity<Object> handleAuthenticationException(AuthenticationException ex, WebRequest request) {
return handleExceptionInternal(ex,
new ErrorTo(List.of(ex.getMessage()), HttpStatus.UNAUTHORIZED.value()),
new HttpHeaders(), HttpStatus.UNAUTHORIZED, request);
}
@ExceptionHandler(value = {ResponseStatusException.class})
protected ResponseEntity<Object> handleResponseStatusException(ResponseStatusException ex, WebRequest request) {
return handleExceptionInternal(ex,
new ErrorTo(List.of(Objects.requireNonNullElse(ex.getReason(), ex.getStatusCode().toString())), ex.getStatusCode().value()),
new HttpHeaders(), ex.getStatusCode(), request);
}
@ExceptionHandler(value = {Exception.class})
protected ResponseEntity<Object> handleGenericException(Exception ex, WebRequest request) {
return handleExceptionInternal(ex,
new ErrorTo(List.of("Error"), HttpStatus.INTERNAL_SERVER_ERROR.value()),
new HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR, request);
}
}

View File

@@ -28,7 +28,7 @@ public class TokenController {
public TokenResponseTo request(@RequestBody TokenRequestTo tokenRequestTo) throws UserNotFoundException {
Optional<Person> found = personService.login(tokenRequestTo.username(), tokenRequestTo.password());
if (found.isEmpty()) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
if (found.isEmpty()) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Couldn't find user");
return new TokenResponseTo(tokenService.generateToken(found.get().getId()));
}