|
| 1 | +package org.lucoenergia.conluz.infrastructure.admin.user.get; |
| 2 | + |
| 3 | +import io.swagger.v3.oas.annotations.Operation; |
| 4 | +import io.swagger.v3.oas.annotations.responses.ApiResponse; |
| 5 | +import io.swagger.v3.oas.annotations.responses.ApiResponses; |
| 6 | +import io.swagger.v3.oas.annotations.security.SecurityRequirement; |
| 7 | +import org.lucoenergia.conluz.domain.admin.user.User; |
| 8 | +import org.lucoenergia.conluz.domain.admin.user.auth.AuthService; |
| 9 | +import org.lucoenergia.conluz.infrastructure.admin.user.UserResponse; |
| 10 | +import org.lucoenergia.conluz.infrastructure.shared.web.apidocs.ApiTag; |
| 11 | +import org.lucoenergia.conluz.infrastructure.shared.web.apidocs.response.InternalServerErrorResponse; |
| 12 | +import org.lucoenergia.conluz.infrastructure.shared.web.apidocs.response.UnauthorizedErrorResponse; |
| 13 | +import org.springframework.http.ResponseEntity; |
| 14 | +import org.springframework.security.access.prepost.PreAuthorize; |
| 15 | +import org.springframework.web.bind.annotation.GetMapping; |
| 16 | +import org.springframework.web.bind.annotation.RequestMapping; |
| 17 | +import org.springframework.web.bind.annotation.RestController; |
| 18 | + |
| 19 | +import java.util.Optional; |
| 20 | + |
| 21 | +/** |
| 22 | + * Returns the currently authenticated user basic information |
| 23 | + */ |
| 24 | +@RestController |
| 25 | +@RequestMapping("/api/v1/users/current") |
| 26 | +public class GetCurrentUserController { |
| 27 | + |
| 28 | + private final AuthService authService; |
| 29 | + |
| 30 | + public GetCurrentUserController(AuthService authService) { |
| 31 | + this.authService = authService; |
| 32 | + } |
| 33 | + |
| 34 | + @GetMapping |
| 35 | + @Operation( |
| 36 | + summary = "Get current authenticated user", |
| 37 | + description = "Returns basic information about the currently authenticated user.", |
| 38 | + tags = ApiTag.USERS, |
| 39 | + operationId = "getCurrentUser", |
| 40 | + security = @SecurityRequirement(name = "bearerToken") |
| 41 | + ) |
| 42 | + @ApiResponses(value = { |
| 43 | + @ApiResponse( |
| 44 | + responseCode = "200", |
| 45 | + description = "Query executed successfully", |
| 46 | + useReturnTypeSchema = true |
| 47 | + ) |
| 48 | + }) |
| 49 | + @UnauthorizedErrorResponse |
| 50 | + @InternalServerErrorResponse |
| 51 | + @PreAuthorize("isAuthenticated()") |
| 52 | + public ResponseEntity<UserResponse> getCurrentUser() { |
| 53 | + Optional<User> currentUser = authService.getCurrentUser(); |
| 54 | + // Although the endpoint is protected, in case the authentication is missing/invalid, respond 401 |
| 55 | + return currentUser.map(user -> ResponseEntity.ok(new UserResponse(user))) |
| 56 | + .orElseGet(() -> ResponseEntity.status(401).build()); |
| 57 | + } |
| 58 | +} |
0 commit comments