11package com .otavio .aifoodapp .controller ;
22
3+ import java .util .HashMap ;
34import java .util .Map ;
5+ import java .util .Optional ;
46import java .util .concurrent .ConcurrentHashMap ;
57
68import org .springframework .http .HttpStatus ;
79import org .springframework .http .ResponseEntity ;
810import org .springframework .security .core .Authentication ;
911import org .springframework .security .core .context .SecurityContextHolder ;
1012import org .springframework .security .oauth2 .client .authentication .OAuth2AuthenticationToken ;
13+ import org .springframework .security .oauth2 .core .user .OAuth2User ;
14+ import org .springframework .security .web .authentication .logout .SecurityContextLogoutHandler ;
1115import org .springframework .web .bind .annotation .GetMapping ;
1216import org .springframework .web .bind .annotation .PostMapping ;
1317import org .springframework .web .bind .annotation .RequestMapping ;
1418import org .springframework .web .bind .annotation .RestController ;
1519
20+ import com .otavio .aifoodapp .dto .UserDTO ;
1621import com .otavio .aifoodapp .model .User ;
22+ import com .otavio .aifoodapp .repository .UserRepository ;
1723import com .otavio .aifoodapp .security .TokenService ;
1824import com .otavio .aifoodapp .service .FoodItemService ;
1925
2026import jakarta .servlet .http .Cookie ;
2127import jakarta .servlet .http .HttpServletRequest ;
28+ import jakarta .servlet .http .HttpServletResponse ;
2229import jakarta .servlet .http .HttpSession ;
2330import lombok .extern .slf4j .Slf4j ;
2431
2532/**
26- * Controller for authentication related endpoints
33+ * Controlador consolidado para autenticação
34+ * Combina funcionalidades de status, login, logout e gerenciamento de tokens
2735 */
2836@ RestController
2937@ RequestMapping ("/api/auth" )
@@ -32,22 +40,79 @@ public class AuthController {
3240
3341 private final FoodItemService foodItemService ;
3442 private final TokenService tokenService ;
43+ private final UserRepository userRepository ;
3544
3645 // Cache para controlar a frequência de verificações por sessão
3746 private final Map <String , Long > lastStatusChecks = new ConcurrentHashMap <>();
3847 private static final long STATUS_CHECK_THROTTLE_MS = 2000 ; // 2 segundos
3948
40- public AuthController (FoodItemService foodItemService , TokenService tokenService ) {
49+ public AuthController (FoodItemService foodItemService , TokenService tokenService , UserRepository userRepository ) {
4150 this .foodItemService = foodItemService ;
4251 this .tokenService = tokenService ;
52+ this .userRepository = userRepository ;
4353 }
4454
55+
4556 /**
46- * Check if user is authenticated and return user details
47- * Used by the frontend to verify persistent authentication
48- * @return User authentication status and details
57+ * Verificar informações do usuário atual
58+ * Endpoint alternativo para obter dados do usuário autenticado
59+ */
60+ @ GetMapping ("/me" )
61+ public ResponseEntity <UserDTO > getCurrentUser (Authentication authentication ) {
62+ if (authentication == null || !authentication .isAuthenticated ()) {
63+ return ResponseEntity .status (401 ).build ();
64+ }
65+
66+ if (authentication .getPrincipal () instanceof OAuth2User oauth2User ) {
67+ String email = oauth2User .getAttribute ("email" );
68+ String name = oauth2User .getAttribute ("name" );
69+
70+ Optional <User > dbUser = (email != null ) ? userRepository .findByEmail (email ) : Optional .empty ();
71+ if (dbUser .isPresent ()) {
72+ return ResponseEntity .ok (UserDTO .fromUser (dbUser .get ()));
73+ } else {
74+ UserDTO dto = new UserDTO (null , email , name , "USER" );
75+ return ResponseEntity .ok (dto );
76+ }
77+ }
78+
79+ if (authentication .getPrincipal () instanceof User user ) {
80+ return ResponseEntity .ok (UserDTO .fromUser (user ));
81+ }
82+
83+ return ResponseEntity .status (401 ).build ();
84+ }
85+
86+ /**
87+ * Endpoint para logout
88+ */
89+ @ PostMapping ("/logout" )
90+ public ResponseEntity <Map <String , String >> logout (HttpServletRequest request ,
91+ HttpServletResponse response ,
92+ Authentication authentication ) {
93+ if (authentication != null ) {
94+ new SecurityContextLogoutHandler ().logout (request , response , authentication );
95+ }
96+ Map <String , String > result = new HashMap <>();
97+ result .put ("message" , "Logged out successfully" );
98+ return ResponseEntity .ok (result );
99+ }
100+
101+ /**
102+ * Endpoint para obter URL de login do Google
103+ */
104+ @ GetMapping ("/login/google" )
105+ public ResponseEntity <Map <String , String >> getGoogleLoginUrl () {
106+ Map <String , String > response = new HashMap <>();
107+ response .put ("loginUrl" , "/oauth2/authorization/google" );
108+ response .put ("message" , "Redirect to this URL to login with Google" );
109+ return ResponseEntity .ok (response );
110+ }
111+
112+ /**
113+ * Verificar se o usuário está autenticado e retornar detalhes
114+ * Usado pelo frontend para verificar autenticação persistente
49115 */
50-
51116 @ GetMapping ("/status" )
52117 public ResponseEntity <?> authStatus (HttpServletRequest request ) {
53118 log .info ("=== AUTH STATUS CHECK ===" );
0 commit comments