From 4b466f314e23fc9174713ea93565fb11e4d85fae Mon Sep 17 00:00:00 2001 From: akastijn Date: Fri, 24 Oct 2025 21:46:07 +0200 Subject: [PATCH] Refactor `getAuthenticatedUserUuid` - extract `getAuthentication` method for improved null handling and clarity --- .../data_from_auth/AuthenticatedUuid.java | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/backend/src/main/java/com/alttd/altitudeweb/controllers/data_from_auth/AuthenticatedUuid.java b/backend/src/main/java/com/alttd/altitudeweb/controllers/data_from_auth/AuthenticatedUuid.java index c5ea419..8d5cc52 100644 --- a/backend/src/main/java/com/alttd/altitudeweb/controllers/data_from_auth/AuthenticatedUuid.java +++ b/backend/src/main/java/com/alttd/altitudeweb/controllers/data_from_auth/AuthenticatedUuid.java @@ -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; + } }