diff --git a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java index f441f96..1c45c26 100644 --- a/src/main/java/com/podzilla/auth/controller/AuthenticationController.java +++ b/src/main/java/com/podzilla/auth/controller/AuthenticationController.java @@ -12,10 +12,12 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.security.core.userdetails.UserDetails; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.bind.annotation.GetMapping; @RestController @RequestMapping("/auth") @@ -101,4 +103,19 @@ public ResponseEntity refreshToken( "User " + email + " refreshed tokens successfully", HttpStatus.OK); } + + @GetMapping("/me") + @Operation( + summary = "Get Current User", + description = "Fetches the details of the currently logged-in user." + ) + @ApiResponse( + responseCode = "200", + description = "User details fetched successfully" + ) + public UserDetails getCurrentUser() { + UserDetails userDetails = authenticationService.getCurrentUserDetails(); + LOGGER.info("Fetched details for user {}", userDetails.getUsername()); + return userDetails; + } } diff --git a/src/main/java/com/podzilla/auth/service/AuthenticationService.java b/src/main/java/com/podzilla/auth/service/AuthenticationService.java index ae40a1e..038a35c 100644 --- a/src/main/java/com/podzilla/auth/service/AuthenticationService.java +++ b/src/main/java/com/podzilla/auth/service/AuthenticationService.java @@ -122,6 +122,19 @@ public String refreshToken(final HttpServletRequest request, } } + public UserDetails getCurrentUserDetails() { + Authentication authentication = + SecurityContextHolder.getContext().getAuthentication(); + + Object principal = authentication.getPrincipal(); + if (principal instanceof UserDetails) { + return (UserDetails) principal; + } else { + throw new InvalidActionException( + "User details not saved correctly."); + } + } + private void checkNotNullValidationException(final String value, final String message) { if (value == null || value.isEmpty()) {