Refactor getAuthenticatedUserUuid - extract getAuthentication method for improved null handling and clarity

This commit is contained in:
akastijn 2025-10-24 21:46:07 +02:00
parent 6531526278
commit 4b466f314e

View File

@ -25,16 +25,14 @@ public class AuthenticatedUuid {
* @throws ResponseStatusException with 401 status if authentication is invalid
*/
public UUID getAuthenticatedUserUuid() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
Authentication authentication = getAuthentication();
if (authentication == null || !(authentication.getPrincipal() instanceof Jwt jwt)) {
log.error("Authentication principal is null {} or not a JWT {}",
authentication == null, authentication == null ?
"null" : authentication.getPrincipal() instanceof JWT);
if (!(authentication.getPrincipal() instanceof Jwt jwt)) {
log.error("Authentication principal is not a JWT {}", authentication.getPrincipal() instanceof JWT);
if (unsecured) {
return UUID.fromString("55e46bc3-2a29-4c53-850f-dbd944dc5c5f");
}
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authentication required");
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authentication should be JWT");
}
String stringUuid = jwt.getSubject();
@ -45,4 +43,13 @@ public class AuthenticatedUuid {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid UUID format");
}
}
private static Authentication getAuthentication() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
log.error("Authentication is null");
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Authentication required");
}
return authentication;
}
}