Skip to content
Merged

Dev #18

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.security.config.auth;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
Expand All @@ -25,11 +26,14 @@ public class AuthorizationServerConfig {
private final AuthProperties authProperties;
private final PasswordEncoder passwordEncoder;

@Value("${gateway.secret}")
private String GATEWAY_SECRET;

@Bean
public RegisteredClientRepository registeredClientRepository() {
RegisteredClient.Builder clientBuilder = RegisteredClient.withId(UUID.randomUUID().toString())
.clientId("gateway-client")
.clientSecret(passwordEncoder.encode("gateway-secret"))
.clientSecret(passwordEncoder.encode(GATEWAY_SECRET))
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
Expand Down
6 changes: 4 additions & 2 deletions src/main/java/com/security/config/auth/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
Expand All @@ -25,6 +24,7 @@
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CookieCsrfTokenRepository;

import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -100,7 +100,9 @@ public SecurityFilterChain defaultSecurityFilterChain(
.oauth2ResourceServer(oauth2ResourceServer ->
oauth2ResourceServer.jwt(Customizer.withDefaults())
)
.csrf(AbstractHttpConfigurer::disable)
.csrf(csrf-> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers("/auth/register")
)
.build();
}

Expand Down
9 changes: 5 additions & 4 deletions src/main/java/com/security/controllers/AuthController.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class AuthController {

private final AuthService authService;
private final CookieService cookieService;
// private final LoginResponseService loginResponseService;


@Operation(summary = "Iniciar sesión con email", description = "Autentica un usuario y establece cookies seguras")
@PostMapping("/login")
Expand Down Expand Up @@ -102,11 +102,12 @@ public ResponseEntity<AuthResponseDTO> logout(
cookieService.clearTokenCookies(response);
return ResponseEntity.ok(new AuthResponseDTO(true, "Sesión cerrada exitosamente", Instant.now()));

} catch (
Exception e) {
} catch (Exception e) {
log.error("Logout failed", e);
cookieService.clearTokenCookies(response);
return ResponseEntity.ok(new AuthResponseDTO(false, "Error al cerrar sesion", Instant.now()));
return ResponseEntity
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body(new AuthResponseDTO(false, "Error al cerrar sesión", Instant.now()));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ public record CreatedUserEvent(
String lastName,
String dni,
String phone,
String email,
String profileImageUrl
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ public LoginResponseDTO registerUser(RegisterRequestDto registerRequestDto) {
registerRequestDto.lastName(),
registerRequestDto.dni(),
registerRequestDto.phone(),
registerRequestDto.email(),
null
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
@RequiredArgsConstructor
Expand All @@ -15,10 +18,26 @@ public class NotificationServiceImpl {

@Transactional
public void sendNotification(String message) {
log.info("Antes de publicar el mensaje");
NotificationEvent event = new NotificationEvent(message);
kafkaTemplate.send("user-created-event-topic", event);
log.info("Mensaje enviado {}", event);
}
try {
log.info("Enviando notificación: {}", message);
NotificationEvent event = new NotificationEvent(message);

// Envío asíncrono con callback
CompletableFuture<SendResult<String, Object>> future =
kafkaTemplate.send("user-created-event-topic", event);

}
future.whenComplete((result, exception) -> {
if (exception == null) {
log.info("✅ Notificación enviada exitosamente: offset={}",
result.getRecordMetadata().offset());
} else {
log.error("❌ Error enviando notificación", exception);
}
});

} catch (Exception e) {
log.error("❌ Error en sendNotification", e);
throw e;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ private void publishUserCreatedEvent(UserEntity user, OAuth2UserInfo userInfo) {
userInfo.getLastName(),
null,
null,
userInfo.getEmail(),
userInfo.getProfileImageUrl()
);

Expand All @@ -160,6 +161,7 @@ private void publishUserUpdateEvent(UserEntity user, OAuth2UserInfo userInfo) {
userInfo.getLastName(),
null,
null,
userInfo.getEmail(),
userInfo.getProfileImageUrl()
);

Expand Down