diff --git a/.agents/task.md b/.agents/task.md deleted file mode 100644 index 0fa7163..0000000 --- a/.agents/task.md +++ /dev/null @@ -1,11 +0,0 @@ -# Unified API Response Wrapper Tasks - -- `[x]` Create `ApiResponse.java` -- `[x]` Create `TraceIdFilter.java` -- `[x]` Refactor `ResponseBuilderService.java` -- `[x]` Update `GlobalExceptionHandler.java` -- `[x]` Update `PayPalGlobalExceptionHandler.java` and `PaystackGlobalExceptionHandler.java` -- `[x]` Run PowerShell migration script for `XtractionResponse` -> `ApiResponse` replacements -- `[x]` Delete `XtractionResponse.java` and `ErrorResponse.java` -- `[/]` Run Maven test suite to verify no compile-time or serialization issues exist -- `[ ]` Verify root endpoint and validation errors manually diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 8a3ac34..74df67d 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -11,10 +11,11 @@ env: ECR_REGISTRY: 315084008680.dkr.ecr.eu-central-1.amazonaws.com jobs: - deploy: - name: Build, Push and Deploy + build: + name: Build and Push Image runs-on: ubuntu-latest - environment: production + outputs: + image: ${{ steps.build-image.outputs.image }} steps: - name: Checkout @@ -45,6 +46,13 @@ jobs: docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT + deploy: + name: Deploy to AWS EC2 + needs: build + runs-on: ubuntu-latest + environment: production + + steps: - name: Deploy to EC2 instance uses: appleboy/ssh-action@v1.0.3 with: @@ -57,7 +65,7 @@ jobs: aws ecr get-login-password --region ${{ env.AWS_REGION }} | docker login --username AWS --password-stdin ${{ env.ECR_REGISTRY }} # Pull the latest image from ECR - docker pull ${{ steps.build-image.outputs.image }} + docker pull ${{ needs.build.outputs.image }} # Execute the deployment script located in the EC2 user's home directory # Pass environment variables to the script diff --git a/.gitignore b/.gitignore index e44551e..1f5fce2 100644 --- a/.gitignore +++ b/.gitignore @@ -43,4 +43,4 @@ http-client.private.env.json src/main/resources/google-credentials.json src/main/resources/firebase-service-account.json -*.iml +.agents diff --git a/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentEventListener.java b/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentEventListener.java index 02cd83a..f93ca24 100644 --- a/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentEventListener.java +++ b/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentEventListener.java @@ -1,5 +1,6 @@ package com.xtraction.api.billing.payment.common.events; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -39,9 +40,9 @@ public PaymentEventListener(PaymentEventProcessor eventProcessor) { * spring.kafka.listener.concurrency=6 */ @KafkaListener( - topics = PaymentTopicConfig.TOPIC_PAYMENT_EVENTS, + topics = KafkaTopicRegistry.PAYMENT_EVENTS, groupId = "unraveldocs-payment-processor", - containerFactory = "paymentBatchListenerContainerFactory", + containerFactory = "kafkaBatchListenerContainerFactory", concurrency = "${payment.kafka.consumer.concurrency:6}" ) public void onPaymentEvents( @@ -81,9 +82,9 @@ public void onPaymentEvents( * Separate consumer group for independent scaling. */ @KafkaListener( - topics = PaymentTopicConfig.TOPIC_PAYMENT_WEBHOOKS, + topics = KafkaTopicRegistry.PAYMENT_WEBHOOKS, groupId = "unraveldocs-webhook-processor", - containerFactory = "paymentBatchListenerContainerFactory", + containerFactory = "kafkaBatchListenerContainerFactory", concurrency = "${payment.kafka.webhook-consumer.concurrency:4}" ) public void onWebhookEvents( @@ -111,7 +112,7 @@ public void onWebhookEvents( * Lower volume, so single processing is fine. */ @KafkaListener( - topics = PaymentTopicConfig.TOPIC_SUBSCRIPTION_EVENTS, + topics = KafkaTopicRegistry.SUBSCRIPTION_EVENTS, groupId = "unraveldocs-subscription-processor", containerFactory = "kafkaListenerContainerFactory" ) diff --git a/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentEventPublisher.java b/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentEventPublisher.java index 214a1ff..99f9861 100644 --- a/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentEventPublisher.java +++ b/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentEventPublisher.java @@ -1,5 +1,6 @@ package com.xtraction.api.billing.payment.common.events; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.core.Message; import com.xtraction.api.integration.broker.core.MessageResult; import com.xtraction.api.integration.broker.kafka.producer.KafkaMessageProducer; @@ -120,7 +121,7 @@ public MessageResult publishSync(PaymentEvent event) { * This allows for separate topics for different event categories if needed. */ private String resolveTopicForEvent() { - return PaymentTopicConfig.TOPIC_PAYMENT_EVENTS; + return KafkaTopicRegistry.PAYMENT_EVENTS; } /** diff --git a/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentKafkaConsumerConfig.java b/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentKafkaConsumerConfig.java deleted file mode 100644 index 71370ab..0000000 --- a/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentKafkaConsumerConfig.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.xtraction.api.billing.payment.common.events; - -import com.xtraction.api.integration.broker.config.MessagingProperties; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.common.serialization.StringDeserializer; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; -import org.springframework.kafka.core.ConsumerFactory; -import org.springframework.kafka.core.DefaultKafkaConsumerFactory; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.listener.ContainerProperties; -import org.springframework.kafka.listener.DeadLetterPublishingRecoverer; -import org.springframework.kafka.listener.DefaultErrorHandler; -import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer; -import org.springframework.kafka.support.serializer.JacksonJsonDeserializer; -import org.springframework.util.backoff.ExponentialBackOff; - -import java.util.HashMap; -import java.util.Map; - -@Slf4j -@Configuration -@RequiredArgsConstructor -@ConditionalOnProperty(name = "spring.kafka.bootstrap-servers") -public class PaymentKafkaConsumerConfig { - - private final MessagingProperties messagingProperties; - - @Value("${spring.kafka.bootstrap-servers}") - private String bootstrapServers; - - // ==================== Consumer Configuration ==================== - - /** - * Max records to fetch per poll. Higher = better throughput, more memory. - * Recommended: 100-500 for payment processing. - */ - @Value("${payment.kafka.consumer.max-poll-records:500}") - private int maxPollRecords; - - /** - * Max time to wait for records. Lower = lower latency, higher = better - * batching. - */ - @Value("${payment.kafka.consumer.fetch-max-wait-ms:500}") - private int fetchMaxWaitMs; - - /** - * Session timeout for consumer group coordination. - */ - @Value("${payment.kafka.consumer.session-timeout-ms:30000}") - private int sessionTimeoutMs; - - /** - * Heartbeat interval (should be 1/3 of session timeout). - */ - @Value("${payment.kafka.consumer.heartbeat-interval-ms:10000}") - private int heartbeatIntervalMs; - - /** - * Max time between polls before consumer is considered dead. - */ - @Value("${payment.kafka.consumer.max-poll-interval-ms:300000}") - private int maxPollIntervalMs; - - // ==================== Consumer Factory ==================== - - @Bean - public ConsumerFactory paymentEventConsumerFactory() { - Map props = new HashMap<>(); - - // Connection - props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); - - // Consumer group - props.put(ConsumerConfig.GROUP_ID_CONFIG, "unraveldocs-payment-processor"); - - // Offset handling - props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); - props.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false); - - // Deserialization - props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class); - props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class); - props.put(ErrorHandlingDeserializer.KEY_DESERIALIZER_CLASS, StringDeserializer.class); - props.put(ErrorHandlingDeserializer.VALUE_DESERIALIZER_CLASS, JacksonJsonDeserializer.class); - - // JSON deserializer config - props.put(JacksonJsonDeserializer.TRUSTED_PACKAGES, "com.xtraction.api.billing.payment.*"); - props.put(JacksonJsonDeserializer.USE_TYPE_INFO_HEADERS, true); - - // ==================== Throughput Optimizations ==================== - - // Fetch more records per poll for better throughput - props.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, maxPollRecords); - - // Fetch settings - props.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 1); - props.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, fetchMaxWaitMs); - props.put(ConsumerConfig.FETCH_MAX_BYTES_CONFIG, 52428800); // 50MB - props.put(ConsumerConfig.MAX_PARTITION_FETCH_BYTES_CONFIG, 10485760); // 10MB per partition - - // Session and heartbeat - props.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeoutMs); - props.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, heartbeatIntervalMs); - props.put(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, maxPollIntervalMs); - - return new DefaultKafkaConsumerFactory<>(props); - } - - // ==================== Batch Listener Container Factory ==================== - - /** - * Batch listener factory for high-throughput payment event processing. - */ - @Bean - public ConcurrentKafkaListenerContainerFactory paymentBatchListenerContainerFactory( - ConsumerFactory paymentEventConsumerFactory, - KafkaTemplate kafkaTemplate) { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - - factory.setConsumerFactory(paymentEventConsumerFactory); - - // Enable batch listening for throughput - factory.setBatchListener(true); - - // Manual acknowledgment for reliability - factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL); - - // Concurrency - number of consumer threads per listener - // Can be overridden per-listener with @KafkaListener(concurrency = "...") - factory.setConcurrency(6); - - // Error handling with DLQ - factory.setCommonErrorHandler(createErrorHandler(kafkaTemplate)); - - log.info("Created payment batch listener factory with concurrency=6, batchListener=true"); - - return factory; - } - - // ==================== Error Handler with DLQ ==================== - - private DefaultErrorHandler createErrorHandler(KafkaTemplate kafkaTemplate) { - // Dead Letter Queue recoverer - DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer( - kafkaTemplate, - (record, exception) -> { - // Route to appropriate DLQ based on original topic - String originalTopic = record.topic(); - if (originalTopic.contains("webhook")) { - return new org.apache.kafka.common.TopicPartition( - PaymentTopicConfig.TOPIC_PAYMENT_WEBHOOKS_DLQ, - record.partition() % 3); - } - return new org.apache.kafka.common.TopicPartition( - PaymentTopicConfig.TOPIC_PAYMENT_EVENTS_DLQ, - record.partition() % 3); - }); - - // Exponential backoff: 1s, 2s, 4s, 8s, 16s (max 5 retries) - ExponentialBackOff backOff = new ExponentialBackOff(1000L, 2.0); - backOff.setMaxElapsedTime(30000L); // Max 30 seconds total - - DefaultErrorHandler errorHandler = new DefaultErrorHandler(recoverer, backOff); - - // Don't retry these exceptions - errorHandler.addNotRetryableExceptions( - IllegalArgumentException.class, - NullPointerException.class); - - log.info("Created error handler with exponential backoff and DLQ"); - - return errorHandler; - } -} diff --git a/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentTopicConfig.java b/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentTopicConfig.java deleted file mode 100644 index 999a999..0000000 --- a/src/main/java/com/xtraction/api/billing/payment/common/events/PaymentTopicConfig.java +++ /dev/null @@ -1,174 +0,0 @@ -package com.xtraction.api.billing.payment.common.events; - -import org.apache.kafka.clients.admin.NewTopic; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.config.TopicBuilder; - -/** - * Kafka topic configuration optimized for high-throughput payment processing. - * - *

Design for Thousands of TPS:

- *
    - *
  • High Partition Count: 12 partitions allow for parallel processing - * by multiple consumers. For very high throughput, increase to 24-48.
  • - *
  • Retention: 30 days for audit/compliance, with compaction for state topics.
  • - *
  • Separate Topics by Purpose: Different topics for events, webhooks, - * and notifications to allow independent scaling.
  • - *
- * - *

Scaling Recommendations:

- *
    - *
  • For 1,000 TPS: 12 partitions, 3-4 consumer instances
  • - *
  • For 5,000 TPS: 24 partitions, 8-12 consumer instances
  • - *
  • For 10,000+ TPS: 48 partitions, 16+ consumer instances
  • - *
- */ -@Configuration -@ConditionalOnProperty(name = "spring.kafka.bootstrap-servers") -public class PaymentTopicConfig { - - // ==================== Main Payment Topics ==================== - - /** - * Main topic for all payment events (succeeded, failed, refunded, etc.) - */ - public static final String TOPIC_PAYMENT_EVENTS = "unraveldocs-payment-events"; - - /** - * Topic for raw webhook events from all payment providers. - * High throughput topic - receives webhooks from Stripe, Paystack, etc. - */ - public static final String TOPIC_PAYMENT_WEBHOOKS = "unraveldocs-payment-webhooks"; - - /** - * Topic for subscription lifecycle events. - */ - public static final String TOPIC_SUBSCRIPTION_EVENTS = "unraveldocs-subscription-events"; - - /** - * Topic for payment notifications (emails, push notifications, etc.) - */ - public static final String TOPIC_PAYMENT_NOTIFICATIONS = "unraveldocs-payment-notifications"; - - // ==================== Retry Topics ==================== - - public static final String TOPIC_PAYMENT_EVENTS_RETRY = "unraveldocs-payment-events-retry"; - public static final String TOPIC_PAYMENT_WEBHOOKS_RETRY = "unraveldocs-payment-webhooks-retry"; - - // ==================== Dead Letter Queue Topics ==================== - - public static final String TOPIC_PAYMENT_EVENTS_DLQ = "unraveldocs-payment-events-dlq"; - public static final String TOPIC_PAYMENT_WEBHOOKS_DLQ = "unraveldocs-payment-webhooks-dlq"; - - // ==================== Partition Configuration ==================== - - /** - * Partition count for high-throughput payment topics. - * 12 partitions support ~3,000-5,000 TPS with proper consumer scaling. - * Increase to 24-48 for higher throughput requirements. - */ - private static final int HIGH_THROUGHPUT_PARTITIONS = 12; - - /** - * Partition count for lower-volume topics. - */ - private static final int STANDARD_PARTITIONS = 6; - - /** - * Partition count for DLQ/retry topics. - */ - private static final int DLQ_PARTITIONS = 3; - - // ==================== Retention Configuration ==================== - - private static final String RETENTION_30_DAYS = "2592000000"; // 30 days - private static final String RETENTION_7_DAYS = "604800000"; // 7 days - private static final String RETENTION_1_DAY = "86400000"; // 1 day - private static final String RETENTION_90_DAYS = "7776000000"; // 90 days (for audit) - - // ==================== Topic Beans ==================== - - @Bean - public NewTopic paymentEventsTopic() { - return TopicBuilder.name(TOPIC_PAYMENT_EVENTS) - .partitions(HIGH_THROUGHPUT_PARTITIONS) - .replicas(1) // Set to 3 in production for HA - .config("retention.ms", RETENTION_30_DAYS) - .config("cleanup.policy", "delete") - // Optimize for throughput - .config("min.insync.replicas", "1") // Set to 2 in production - .config("segment.bytes", "1073741824") // 1GB segments - .build(); - } - - @Bean - public NewTopic paymentWebhooksTopic() { - return TopicBuilder.name(TOPIC_PAYMENT_WEBHOOKS) - .partitions(HIGH_THROUGHPUT_PARTITIONS) - .replicas(1) - .config("retention.ms", RETENTION_7_DAYS) - .config("cleanup.policy", "delete") - .build(); - } - - @Bean - public NewTopic subscriptionEventsTopic() { - return TopicBuilder.name(TOPIC_SUBSCRIPTION_EVENTS) - .partitions(STANDARD_PARTITIONS) - .replicas(1) - .config("retention.ms", RETENTION_30_DAYS) - .build(); - } - - @Bean - public NewTopic paymentNotificationsTopic() { - return TopicBuilder.name(TOPIC_PAYMENT_NOTIFICATIONS) - .partitions(STANDARD_PARTITIONS) - .replicas(1) - .config("retention.ms", RETENTION_7_DAYS) - .build(); - } - - // ==================== Retry Topics ==================== - - @Bean - public NewTopic paymentEventsRetryTopic() { - return TopicBuilder.name(TOPIC_PAYMENT_EVENTS_RETRY) - .partitions(DLQ_PARTITIONS) - .replicas(1) - .config("retention.ms", RETENTION_1_DAY) - .build(); - } - - @Bean - public NewTopic paymentWebhooksRetryTopic() { - return TopicBuilder.name(TOPIC_PAYMENT_WEBHOOKS_RETRY) - .partitions(DLQ_PARTITIONS) - .replicas(1) - .config("retention.ms", RETENTION_1_DAY) - .build(); - } - - // ==================== Dead Letter Queue Topics ==================== - - @Bean - public NewTopic paymentEventsDlqTopic() { - return TopicBuilder.name(TOPIC_PAYMENT_EVENTS_DLQ) - .partitions(DLQ_PARTITIONS) - .replicas(1) - .config("retention.ms", RETENTION_90_DAYS) // Long retention for investigation - .build(); - } - - @Bean - public NewTopic paymentWebhooksDlqTopic() { - return TopicBuilder.name(TOPIC_PAYMENT_WEBHOOKS_DLQ) - .partitions(DLQ_PARTITIONS) - .replicas(1) - .config("retention.ms", RETENTION_90_DAYS) - .build(); - } -} - diff --git a/src/main/java/com/xtraction/api/billing/payment/receipt/events/ReceiptEventPublisher.java b/src/main/java/com/xtraction/api/billing/payment/receipt/events/ReceiptEventPublisher.java index c8161bd..e107242 100644 --- a/src/main/java/com/xtraction/api/billing/payment/receipt/events/ReceiptEventPublisher.java +++ b/src/main/java/com/xtraction/api/billing/payment/receipt/events/ReceiptEventPublisher.java @@ -4,7 +4,7 @@ import com.xtraction.api.integration.broker.kafka.events.BaseEvent; import com.xtraction.api.integration.broker.kafka.events.EventMetadata; import com.xtraction.api.integration.broker.core.Message; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.kafka.producer.KafkaMessageProducer; import com.xtraction.api.billing.payment.receipt.dto.ReceiptData; import lombok.RequiredArgsConstructor; @@ -60,7 +60,7 @@ public void publishReceiptRequest(ReceiptData receiptData) { // Use the external payment ID as the partition key for ordering guarantees Message> message = Message.of( event, - KafkaTopicConfig.TOPIC_RECEIPTS, + KafkaTopicRegistry.RECEIPTS, receiptData.getExternalPaymentId() ); diff --git a/src/main/java/com/xtraction/api/billing/payment/receipt/events/ReceiptMessageListener.java b/src/main/java/com/xtraction/api/billing/payment/receipt/events/ReceiptMessageListener.java index 17842b2..e269797 100644 --- a/src/main/java/com/xtraction/api/billing/payment/receipt/events/ReceiptMessageListener.java +++ b/src/main/java/com/xtraction/api/billing/payment/receipt/events/ReceiptMessageListener.java @@ -1,6 +1,6 @@ package com.xtraction.api.billing.payment.receipt.events; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.kafka.events.BaseEvent; import com.xtraction.api.billing.payment.receipt.dto.ReceiptData; import com.xtraction.api.billing.payment.receipt.model.Receipt; @@ -30,7 +30,7 @@ public class ReceiptMessageListener { private final ReceiptEventMapper receiptEventMapper; private final ObjectMapper objectMapper; - @KafkaListener(topics = KafkaTopicConfig.TOPIC_RECEIPTS, groupId = "unraveldocs-receipt-group", containerFactory = "kafkaListenerContainerFactory") + @KafkaListener(topics = KafkaTopicRegistry.RECEIPTS, groupId = "unraveldocs-receipt-group", containerFactory = "kafkaListenerContainerFactory") @SuppressWarnings("unchecked") public void receiveReceiptRequestedEvent( ConsumerRecord> record, diff --git a/src/main/java/com/xtraction/api/billing/promocode/kafka/PromoCodeGenerationConsumer.java b/src/main/java/com/xtraction/api/billing/promocode/kafka/PromoCodeGenerationConsumer.java index 9f1400e..d307419 100644 --- a/src/main/java/com/xtraction/api/billing/promocode/kafka/PromoCodeGenerationConsumer.java +++ b/src/main/java/com/xtraction/api/billing/promocode/kafka/PromoCodeGenerationConsumer.java @@ -1,5 +1,6 @@ package com.xtraction.api.billing.promocode.kafka; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.billing.promocode.dto.request.BulkPromoCodeGenerationRequest; import com.xtraction.api.billing.promocode.dto.request.CreatePromoCodeRequest; import com.xtraction.api.billing.promocode.enums.RecipientCategory; @@ -52,7 +53,7 @@ public void cancelLocalJob(String jobId) { this.cancelledJobs.add(jobId); } - @KafkaListener(topics = "${promo.kafka.topic:promo-code-generation-events}", groupId = "${promo.kafka.consumer-group:promo-code-generation-consumer-group}", concurrency = "${promo.bulk.kafka.concurrency:3}") + @KafkaListener(topics = KafkaTopicRegistry.PROMO_CODE_EVENTS, groupId = "${promo.kafka.consumer-group:promo-code-generation-consumer-group}", concurrency = "${promo.bulk.kafka.concurrency:3}") public void processBulkGenerationCommand(BulkGenerationCommand command, Acknowledgment ack) { String jobId = command.getJobId(); log.info("Received bulk generation command. JobId: {}, Quantity: {}", diff --git a/src/main/java/com/xtraction/api/billing/promocode/kafka/PromoCodeGenerationProducer.java b/src/main/java/com/xtraction/api/billing/promocode/kafka/PromoCodeGenerationProducer.java index 4b3e666..7a308a1 100644 --- a/src/main/java/com/xtraction/api/billing/promocode/kafka/PromoCodeGenerationProducer.java +++ b/src/main/java/com/xtraction/api/billing/promocode/kafka/PromoCodeGenerationProducer.java @@ -1,5 +1,6 @@ package com.xtraction.api.billing.promocode.kafka; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.core.utils.logging.SanitizeLogging; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -24,8 +25,7 @@ public class PromoCodeGenerationProducer { private final KafkaTemplate kafkaTemplate; private final SanitizeLogging sanitizer; - @Value("${promo.kafka.topic:promo-code-generation-events}") - private String topic; + /** * Publishes a bulk generation command to Kafka. @@ -40,7 +40,7 @@ public CompletableFuture> publishBulkG sanitizer.sanitizeLoggingInteger(command.getRequest().getQuantity())); return (CompletableFuture>) (CompletableFuture) - kafkaTemplate.send(topic, command.getUserId(), command) + kafkaTemplate.send(KafkaTopicRegistry.PROMO_CODE_EVENTS, command.getUserId(), command) .whenComplete((result, ex) -> { if (ex != null) { log.error("Failed to publish bulk generation command for job: {}", diff --git a/src/main/java/com/xtraction/api/core/config/SecurityConfig.java b/src/main/java/com/xtraction/api/core/config/SecurityConfig.java index b6e41b2..ec35094 100644 --- a/src/main/java/com/xtraction/api/core/config/SecurityConfig.java +++ b/src/main/java/com/xtraction/api/core/config/SecurityConfig.java @@ -5,6 +5,9 @@ import com.xtraction.api.core.security.JwtAuthenticationEntryPoint; import com.xtraction.api.core.security.JwtAuthenticationFilter; import com.xtraction.api.core.utils.CustomPermissionEvaluator; +import com.xtraction.api.identity.auth.oauth2.handler.OAuth2AuthenticationFailureHandler; +import com.xtraction.api.identity.auth.oauth2.handler.OAuth2AuthenticationSuccessHandler; +import com.xtraction.api.identity.auth.oauth2.service.CustomOAuth2UserService; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Getter; import lombok.RequiredArgsConstructor; @@ -34,6 +37,9 @@ public class SecurityConfig { private final JwtAuthenticationEntryPoint authenticationEntryPoint; private final JwtAuthenticationFilter jwtAuthenticationFilter; + private final CustomOAuth2UserService customOAuth2UserService; + private final OAuth2AuthenticationSuccessHandler oAuth2SuccessHandler; + private final OAuth2AuthenticationFailureHandler oAuth2FailureHandler; @Getter private final ObjectMapper objectMapper; @@ -95,8 +101,7 @@ public SecurityFilterChain securityFilterChain( "/api/v1/auth/verify-email", "/api/v1/auth/refresh-token", "/api/v1/user/forgot-password", - "/api/v1/user/reset-password", - "/api/v1/auth/resend-verification-email", + "/api/v1/user/reset-password","/api/v1/auth/resend-verification-email", "/api/v1/auth/generate-password", "/api/v1/paystack/webhook/**", "/api/v1/paystack/callback", @@ -105,7 +110,9 @@ public SecurityFilterChain securityFilterChain( "/api/v1/paypal/return", "/api/v1/paypal/cancel", "/api/v1/currency/**", - "/ws/**") + "/ws/**", + "/oauth2/**", + "/login/oauth2/**") .permitAll() .requestMatchers( "/api/v1/admin/**") @@ -126,7 +133,12 @@ public SecurityFilterChain securityFilterChain( .authenticationEntryPoint(authenticationEntryPoint) .accessDeniedHandler(accessDeniedHandler)) .sessionManagement(session -> session - .sessionCreationPolicy(SessionCreationPolicy.STATELESS)); + .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)) + .oauth2Login(oauth2 -> oauth2 + .userInfoEndpoint(userInfo -> userInfo + .userService(customOAuth2UserService)) + .successHandler(oAuth2SuccessHandler) + .failureHandler(oAuth2FailureHandler)); http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); return http.build(); diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/ErrorCode.java b/src/main/java/com/xtraction/api/core/exceptions/custom/ErrorCode.java index 76327f3..2af322b 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/ErrorCode.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/ErrorCode.java @@ -9,6 +9,8 @@ public enum ErrorCode { INVALID_CREDENTIALS("AUTH_001", "Invalid credentials provided", HttpStatus.UNAUTHORIZED), TOKEN_EXPIRED("AUTH_002", "Authentication token has expired", HttpStatus.UNAUTHORIZED), ACCESS_DENIED("AUTH_003", "Access denied", HttpStatus.FORBIDDEN), + UNAUTHORIZED("AUTH_004", "Full authentication is required", HttpStatus.UNAUTHORIZED), + FORBIDDEN("AUTH_005", "Access denied", HttpStatus.FORBIDDEN), // Resource Errors RESOURCE_NOT_FOUND("RES_001", "Requested resource was not found", HttpStatus.NOT_FOUND), @@ -18,8 +20,6 @@ public enum ErrorCode { INTERNAL_SERVER_ERROR("SYS_001", "An unexpected error occurred", HttpStatus.INTERNAL_SERVER_ERROR), RATE_LIMIT_EXCEEDED("SYS_002", "Too many requests", HttpStatus.TOO_MANY_REQUESTS), BAD_REQUEST("SYS_003", "Invalid request payload", HttpStatus.BAD_REQUEST), - UNAUTHORIZED("AUTH_004", "Full authentication is required", HttpStatus.UNAUTHORIZED), - FORBIDDEN("AUTH_005", "Access denied", HttpStatus.FORBIDDEN), // Promo Code Errors PROMO_CODE_NOT_FOUND("PROMO_001", "Promo code not found", HttpStatus.NOT_FOUND), @@ -32,7 +32,8 @@ public enum ErrorCode { ACCOUNT_NOT_VERIFIED("AUTH_009", "Account is not verified", HttpStatus.FORBIDDEN), ACCOUNT_LOCKED("AUTH_010", "Account is locked", HttpStatus.FORBIDDEN), TOKEN_MISSING("AUTH_011", "Refresh token is missing", HttpStatus.UNAUTHORIZED), - TOKEN_INVALID("AUTH_012", "Invalid refresh token", HttpStatus.UNAUTHORIZED); + TOKEN_INVALID("AUTH_012", "Invalid refresh token", HttpStatus.UNAUTHORIZED), + OAUTH_ACCOUNT("AUTH_013", "Account uses OAuth provider", HttpStatus.BAD_REQUEST); private final String code; private final String defaultMessage; diff --git a/src/main/java/com/xtraction/api/core/kafka/KafkaTopicRegistry.java b/src/main/java/com/xtraction/api/core/kafka/KafkaTopicRegistry.java new file mode 100644 index 0000000..da989db --- /dev/null +++ b/src/main/java/com/xtraction/api/core/kafka/KafkaTopicRegistry.java @@ -0,0 +1,41 @@ +package com.xtraction.api.core.kafka; + +/** + * Central registry for all Kafka topic names. + * Standardizes topic names using the 'xtraction-' prefix. + */ +public final class KafkaTopicRegistry { + + private KafkaTopicRegistry() {} + + // Core messaging topics + public static final String EMAILS = "xtraction-emails"; + public static final String DOCUMENTS = "xtraction-documents"; + public static final String PAYMENTS = "xtraction-payments"; + public static final String USERS = "xtraction-users"; + public static final String NOTIFICATIONS = "xtraction-notifications"; + public static final String RECEIPTS = "xtraction-receipts"; + public static final String OCR = "xtraction-ocr"; + public static final String TEAM_EVENTS = "xtraction-team-events"; + public static final String ADMIN_EVENTS = "xtraction-admin-events"; + public static final String ELASTICSEARCH = "xtraction-elasticsearch"; + public static final String EXTRACTION_PROGRESS = "xtraction-extraction-progress"; + + // Payment-specific topics + public static final String PAYMENT_EVENTS = "xtraction-payment-events"; + public static final String PAYMENT_WEBHOOKS = "xtraction-payment-webhooks"; + public static final String SUBSCRIPTION_EVENTS = "xtraction-subscription-events"; + public static final String PAYMENT_NOTIFICATIONS = "xtraction-payment-notifications"; + + // Promo code topics + public static final String PROMO_CODE_EVENTS = "xtraction-promo-code-events"; + + // Helper methods for retry and DLQ naming conventions + public static String getRetryTopic(String baseTopic) { + return baseTopic + "-retry"; + } + + public static String getDlqTopic(String baseTopic) { + return baseTopic + "-dlq"; + } +} diff --git a/src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaConsumerConfig.java b/src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaConsumerConfig.java new file mode 100644 index 0000000..6ee68b4 --- /dev/null +++ b/src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaConsumerConfig.java @@ -0,0 +1,177 @@ +package com.xtraction.api.core.kafka.config; + +import com.xtraction.api.integration.broker.config.MessagingProperties; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.apache.kafka.clients.consumer.ConsumerConfig; +import org.apache.kafka.common.TopicPartition; +import org.apache.kafka.common.serialization.StringDeserializer; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; +import org.springframework.kafka.core.ConsumerFactory; +import org.springframework.kafka.core.DefaultKafkaConsumerFactory; +import org.springframework.kafka.core.KafkaTemplate; +import org.springframework.kafka.listener.ContainerProperties; +import org.springframework.kafka.listener.DeadLetterPublishingRecoverer; +import org.springframework.kafka.listener.DefaultErrorHandler; +import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer; +import org.springframework.kafka.support.serializer.JacksonJsonDeserializer; +import org.springframework.util.backoff.ExponentialBackOff; + +import java.util.HashMap; +import java.util.Map; + +/** + * Centralized, shared Kafka consumer configuration. + * Declares the core consumer factory, container factories, and error handler. + */ +@Slf4j +@Configuration +@RequiredArgsConstructor +@ConditionalOnProperty(name = "spring.kafka.bootstrap-servers") +public class SharedKafkaConsumerConfig { + + private final MessagingProperties messagingProperties; + + @Value("${spring.kafka.bootstrap-servers}") + private String bootstrapServers; + + @Value("${spring.kafka.consumer.group-id:unraveldocs-group}") + private String groupId; + + @Value("${spring.kafka.consumer.auto-offset-reset:earliest}") + private String autoOffsetReset; + + @Value("${spring.kafka.consumer.enable-auto-commit:false}") + private boolean enableAutoCommit; + + @Bean + public ConsumerFactory consumerFactory() { + Map configProps = new HashMap<>(); + var consumerProps = messagingProperties.getKafka().getConsumer(); + + // Connection settings + configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); + configProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); + + // Offset handling + configProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset); + configProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit); + + // Deserialization with error handling + configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class); + configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class); + configProps.put(ErrorHandlingDeserializer.KEY_DESERIALIZER_CLASS, StringDeserializer.class); + configProps.put(ErrorHandlingDeserializer.VALUE_DESERIALIZER_CLASS, JacksonJsonDeserializer.class); + + // JSON deserializer settings - trust all classes under com.xtraction.api + configProps.put(JacksonJsonDeserializer.TRUSTED_PACKAGES, "com.xtraction.api.*"); + configProps.put(JacksonJsonDeserializer.USE_TYPE_INFO_HEADERS, true); + + // Performance tuning + configProps.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, consumerProps.getMaxPollRecords()); + configProps.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 1); + configProps.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, 500); + + // Session and heartbeat settings + configProps.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, consumerProps.getSessionTimeoutMs()); + configProps.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, consumerProps.getHeartbeatIntervalMs()); + + return new DefaultKafkaConsumerFactory<>(configProps); + } + + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory( + ConsumerFactory consumerFactory, + DefaultErrorHandler errorHandler) { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + + factory.setConsumerFactory(consumerFactory); + factory.setCommonErrorHandler(errorHandler); + + // Manual acknowledgment for reliability + factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); + + // Concurrency (number of consumer threads) - configurable + factory.setConcurrency(messagingProperties.getKafka().getConsumer().getConcurrency()); + + log.info("Kafka listener container configured with concurrency: {}", + messagingProperties.getKafka().getConsumer().getConcurrency()); + + return factory; + } + + /** + * Centralized Batch Listener Container Factory for high-throughput consumers. + */ + @Bean + public ConcurrentKafkaListenerContainerFactory kafkaBatchListenerContainerFactory( + ConsumerFactory consumerFactory, + DefaultErrorHandler errorHandler) { + ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); + + factory.setConsumerFactory(consumerFactory); + factory.setCommonErrorHandler(errorHandler); + + // Enable batch listening for high throughput + factory.setBatchListener(true); + + // Manual acknowledgment for batch processing + factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); + + // Default concurrency for batch listener + factory.setConcurrency(messagingProperties.getKafka().getConsumer().getConcurrency()); + + log.info("Kafka batch listener container configured with concurrency: {}", + messagingProperties.getKafka().getConsumer().getConcurrency()); + + return factory; + } + + @Bean + public DefaultErrorHandler errorHandler(KafkaTemplate kafkaTemplate) { + var retryProps = messagingProperties.getKafka().getRetry(); + + // Configure exponential backoff + ExponentialBackOff backOff = new ExponentialBackOff( + retryProps.getInitialIntervalMs(), + retryProps.getMultiplier()); + backOff.setMaxInterval(retryProps.getMaxIntervalMs()); + backOff.setMaxElapsedTime(retryProps.getMaxIntervalMs() * retryProps.getMaxAttempts()); + + // Dead Letter Publishing Recoverer - routes to DLQ after all retries exhausted + DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer( + kafkaTemplate, + (record, ex) -> { + String dlqTopic = record.topic() + "-dlq"; + log.error( + "Exhausted retries. Routing to DLQ: {}. Original topic: {}, Partition: {}, Offset: {}, Error: {}", + dlqTopic, + record.topic(), + record.partition(), + record.offset(), + ex.getMessage(), + ex + ); + return new TopicPartition(dlqTopic, -1); + }); + + DefaultErrorHandler errorHandler = new DefaultErrorHandler(recoverer, backOff); + + // Don't retry for certain exceptions (non-recoverable) + errorHandler.addNotRetryableExceptions( + IllegalArgumentException.class, + NullPointerException.class, + ClassCastException.class); + + log.info("Kafka error handler configured with exponential backoff: initialInterval={}ms, multiplier={}, maxInterval={}ms", + retryProps.getInitialIntervalMs(), + retryProps.getMultiplier(), + retryProps.getMaxIntervalMs()); + + return errorHandler; + } +} diff --git a/src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaProducerConfig.java b/src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaProducerConfig.java similarity index 95% rename from src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaProducerConfig.java rename to src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaProducerConfig.java index 8f1a334..171d9d3 100644 --- a/src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaProducerConfig.java +++ b/src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaProducerConfig.java @@ -1,4 +1,4 @@ -package com.xtraction.api.integration.broker.kafka.config; +package com.xtraction.api.core.kafka.config; import com.xtraction.api.integration.broker.config.MessagingProperties; import lombok.RequiredArgsConstructor; @@ -19,14 +19,14 @@ import java.util.UUID; /** - * Kafka producer configuration. - * Only loaded when Kafka bootstrap servers are configured. + * Shared Kafka producer configuration. + * Declares the core producer factory and KafkaTemplate. */ @Slf4j @Configuration @RequiredArgsConstructor @ConditionalOnProperty(name = "spring.kafka.bootstrap-servers") -public class KafkaProducerConfig { +public class SharedKafkaProducerConfig { private final MessagingProperties messagingProperties; @@ -99,4 +99,3 @@ public KafkaTemplate kafkaTemplate(ProducerFactory(producerFactory); } } - diff --git a/src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaTopicConfig.java b/src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaTopicConfig.java new file mode 100644 index 0000000..7aa22c7 --- /dev/null +++ b/src/main/java/com/xtraction/api/core/kafka/config/SharedKafkaTopicConfig.java @@ -0,0 +1,380 @@ +package com.xtraction.api.core.kafka.config; + +import com.xtraction.api.core.kafka.KafkaTopicRegistry; +import org.apache.kafka.clients.admin.NewTopic; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.kafka.config.TopicBuilder; + +/** + * Shared Kafka topic declarations. + * Declares all topic beans (main, retry, DLQ) using KafkaTopicRegistry constants. + */ +@Configuration +@ConditionalOnProperty(name = "spring.kafka.bootstrap-servers") +public class SharedKafkaTopicConfig { + + private static final String RETENTION_MS = "retention.ms"; + + // Retention Durations in Milliseconds + private static final String RETENTION_1_DAY = "86400000"; + private static final String RETENTION_3_DAYS = "259200000"; + private static final String RETENTION_7_DAYS = "604800000"; + private static final String RETENTION_30_DAYS = "2592000000"; + private static final String RETENTION_90_DAYS = "7776000000"; + + // ==================== Core Messaging Topics ==================== + + @Bean + public NewTopic emailsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.EMAILS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + @Bean + public NewTopic documentsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.DOCUMENTS) + .partitions(6) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + @Bean + public NewTopic paymentsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.PAYMENTS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic usersTopic() { + return TopicBuilder.name(KafkaTopicRegistry.USERS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + @Bean + public NewTopic notificationsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.NOTIFICATIONS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_3_DAYS) + .build(); + } + + @Bean + public NewTopic receiptsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.RECEIPTS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic ocrTopic() { + return TopicBuilder.name(KafkaTopicRegistry.OCR) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + @Bean + public NewTopic teamEventsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.TEAM_EVENTS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + @Bean + public NewTopic adminEventsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.ADMIN_EVENTS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + @Bean + public NewTopic elasticsearchTopic() { + return TopicBuilder.name(KafkaTopicRegistry.ELASTICSEARCH) + .partitions(6) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + @Bean + public NewTopic extractionProgressTopic() { + return TopicBuilder.name(KafkaTopicRegistry.EXTRACTION_PROGRESS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_3_DAYS) + .build(); + } + + // ==================== Payment-specific Topics ==================== + + @Bean + public NewTopic paymentEventsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.PAYMENT_EVENTS) + .partitions(12) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic paymentWebhooksTopic() { + return TopicBuilder.name(KafkaTopicRegistry.PAYMENT_WEBHOOKS) + .partitions(12) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + @Bean + public NewTopic subscriptionEventsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.SUBSCRIPTION_EVENTS) + .partitions(6) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic paymentNotificationsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.PAYMENT_NOTIFICATIONS) + .partitions(6) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + // ==================== Promo Code Topics ==================== + + @Bean + public NewTopic promoCodeEventsTopic() { + return TopicBuilder.name(KafkaTopicRegistry.PROMO_CODE_EVENTS) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_7_DAYS) + .build(); + } + + // ==================== Core Retry Topics ==================== + + @Bean + public NewTopic emailsRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.EMAILS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic documentsRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.DOCUMENTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic paymentsRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.PAYMENTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic usersRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.USERS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic receiptsRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.RECEIPTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic ocrRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.OCR)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic teamEventsRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.TEAM_EVENTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic adminEventsRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.ADMIN_EVENTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic elasticsearchRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.ELASTICSEARCH)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + // ==================== Core DLQ Topics ==================== + + @Bean + public NewTopic emailsDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.EMAILS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic documentsDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.DOCUMENTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic paymentsDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.PAYMENTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic usersDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.USERS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic receiptsDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.RECEIPTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic ocrDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.OCR)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic teamEventsDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.TEAM_EVENTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic adminEventsDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.ADMIN_EVENTS)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + @Bean + public NewTopic elasticsearchDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.ELASTICSEARCH)) + .partitions(1) + .replicas(1) + .config(RETENTION_MS, RETENTION_30_DAYS) + .build(); + } + + // ==================== Payment Retry & DLQ Topics ==================== + + @Bean + public NewTopic paymentEventsRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.PAYMENT_EVENTS)) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic paymentWebhooksRetryTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getRetryTopic(KafkaTopicRegistry.PAYMENT_WEBHOOKS)) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_1_DAY) + .build(); + } + + @Bean + public NewTopic paymentEventsDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.PAYMENT_EVENTS)) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_90_DAYS) + .build(); + } + + @Bean + public NewTopic paymentWebhooksDlqTopic() { + return TopicBuilder.name(KafkaTopicRegistry.getDlqTopic(KafkaTopicRegistry.PAYMENT_WEBHOOKS)) + .partitions(3) + .replicas(1) + .config(RETENTION_MS, RETENTION_90_DAYS) + .build(); + } +} diff --git a/src/main/java/com/xtraction/api/extraction/ocr/events/OcrEventPublisher.java b/src/main/java/com/xtraction/api/extraction/ocr/events/OcrEventPublisher.java index e093bb7..cacb51b 100644 --- a/src/main/java/com/xtraction/api/extraction/ocr/events/OcrEventPublisher.java +++ b/src/main/java/com/xtraction/api/extraction/ocr/events/OcrEventPublisher.java @@ -1,7 +1,7 @@ package com.xtraction.api.extraction.ocr.events; import com.xtraction.api.integration.broker.core.Message; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.kafka.producer.KafkaMessageProducer; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -40,7 +40,7 @@ public CompletableFuture publishOcrRequest(OcrRequestedEvent event) { // Use collectionId as partition key to ensure ordering within a collection Message message = Message.of( event, - KafkaTopicConfig.TOPIC_DOCUMENTS, + KafkaTopicRegistry.DOCUMENTS, event.getCollectionId()); return kafkaMessageProducer.send(message) diff --git a/src/main/java/com/xtraction/api/extraction/ocr/events/OcrMessageListener.java b/src/main/java/com/xtraction/api/extraction/ocr/events/OcrMessageListener.java index c9835e8..32e3ebe 100644 --- a/src/main/java/com/xtraction/api/extraction/ocr/events/OcrMessageListener.java +++ b/src/main/java/com/xtraction/api/extraction/ocr/events/OcrMessageListener.java @@ -1,7 +1,7 @@ package com.xtraction.api.extraction.ocr.events; import com.xtraction.api.core.utils.logging.SanitizeLogging; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.extraction.ocr.interfaces.ProcessOcrService; import com.xtraction.api.extraction.ocr.service.ExtractionProgressService; import lombok.RequiredArgsConstructor; @@ -34,7 +34,7 @@ public class OcrMessageListener { private final ExtractionProgressService extractionProgressService; private final SanitizeLogging sanitizer; - @KafkaListener(topics = KafkaTopicConfig.TOPIC_DOCUMENTS, groupId = "unraveldocs-ocr-group", containerFactory = "kafkaListenerContainerFactory") + @KafkaListener(topics = KafkaTopicRegistry.DOCUMENTS, groupId = "unraveldocs-ocr-group", containerFactory = "kafkaListenerContainerFactory") public void receiveOcrRequestedEvent( ConsumerRecord record, Acknowledgment acknowledgment) { diff --git a/src/main/java/com/xtraction/api/extraction/search/consumer/ElasticsearchIndexConsumer.java b/src/main/java/com/xtraction/api/extraction/search/consumer/ElasticsearchIndexConsumer.java index 2679406..eeaea1d 100644 --- a/src/main/java/com/xtraction/api/extraction/search/consumer/ElasticsearchIndexConsumer.java +++ b/src/main/java/com/xtraction/api/extraction/search/consumer/ElasticsearchIndexConsumer.java @@ -1,7 +1,7 @@ package com.xtraction.api.extraction.search.consumer; import com.xtraction.api.core.utils.logging.SanitizeLogging; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.extraction.search.document.DocumentSearchIndex; import com.xtraction.api.extraction.search.document.PaymentSearchIndex; import com.xtraction.api.extraction.search.document.UserSearchIndex; @@ -40,7 +40,7 @@ public class ElasticsearchIndexConsumer { * @param event The indexing event to process * @param acknowledgment Kafka acknowledgment for manual commit */ - @KafkaListener(topics = KafkaTopicConfig.TOPIC_ELASTICSEARCH, groupId = "elasticsearch-consumer-group", containerFactory = "kafkaListenerContainerFactory") + @KafkaListener(topics = KafkaTopicRegistry.ELASTICSEARCH, groupId = "elasticsearch-consumer-group", containerFactory = "kafkaListenerContainerFactory") public void handleIndexEvent(ElasticsearchIndexEvent event, Acknowledgment acknowledgment) { if (event == null) { log.warn("Received null ElasticsearchIndexEvent, acknowledging and skipping"); diff --git a/src/main/java/com/xtraction/api/extraction/search/publisher/ElasticsearchEventPublisher.java b/src/main/java/com/xtraction/api/extraction/search/publisher/ElasticsearchEventPublisher.java index c93dc2b..ec0a8f2 100644 --- a/src/main/java/com/xtraction/api/extraction/search/publisher/ElasticsearchEventPublisher.java +++ b/src/main/java/com/xtraction/api/extraction/search/publisher/ElasticsearchEventPublisher.java @@ -3,7 +3,7 @@ import com.xtraction.api.integration.broker.core.Message; import com.xtraction.api.integration.broker.core.MessageBrokerFactory; import com.xtraction.api.integration.broker.core.MessageBrokerType; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.extraction.search.events.ElasticsearchIndexEvent; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -82,7 +82,7 @@ private void publishEvent(ElasticsearchIndexEvent event, String eventType) { Message message = Message.of( event, - KafkaTopicConfig.TOPIC_ELASTICSEARCH, + KafkaTopicRegistry.ELASTICSEARCH, event.getDocumentId(), // Use document ID as key for ordering Map.of("event-type", eventType)); diff --git a/src/main/java/com/xtraction/api/extraction/vision/events/VisionOcrEventPublisher.java b/src/main/java/com/xtraction/api/extraction/vision/events/VisionOcrEventPublisher.java index e694c85..2fe321d 100644 --- a/src/main/java/com/xtraction/api/extraction/vision/events/VisionOcrEventPublisher.java +++ b/src/main/java/com/xtraction/api/extraction/vision/events/VisionOcrEventPublisher.java @@ -2,7 +2,7 @@ import com.xtraction.api.integration.broker.core.Message; import com.xtraction.api.integration.broker.kafka.producer.KafkaMessageProducer; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -38,7 +38,7 @@ public CompletableFuture publishOcrRequest(VisionOcrRequestedEvent event) Message message = Message.of( event, - KafkaTopicConfig.TOPIC_DOCUMENTS, + KafkaTopicRegistry.DOCUMENTS, event.getDocumentId()); return kafkaMessageProducer.send(message) diff --git a/src/main/java/com/xtraction/api/identity/auth/impl/LoginUserImpl.java b/src/main/java/com/xtraction/api/identity/auth/impl/LoginUserImpl.java index d322f77..433d042 100644 --- a/src/main/java/com/xtraction/api/identity/auth/impl/LoginUserImpl.java +++ b/src/main/java/com/xtraction/api/identity/auth/impl/LoginUserImpl.java @@ -1,5 +1,6 @@ package com.xtraction.api.identity.auth.impl; +import com.xtraction.api.identity.auth.oauth2.datamodel.AuthProvider; import com.xtraction.api.core.utils.logging.SanitizeLogging; import com.xtraction.api.core.web.response.ApiResponse; @@ -52,6 +53,12 @@ public LoginResult loginUser(LoginRequestDto request) { ErrorCode.ACCOUNT_DEACTIVATED, "This account has been deactivated. Please contact support."); } + // Block password login for OAuth-only accounts + if (user.getAuthProvider() != AuthProvider.LOCAL && user.getPassword() == null) { + throw new BadRequestException( + ErrorCode.OAUTH_ACCOUNT, + "This account uses Google Sign-In. Please log in with Google."); + } }); userOpt.ifPresent(loginAttemptsService::checkIfUserBlocked); diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/config/OAuth2Properties.java b/src/main/java/com/xtraction/api/identity/auth/oauth2/config/OAuth2Properties.java new file mode 100644 index 0000000..c5e8bf5 --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/auth/oauth2/config/OAuth2Properties.java @@ -0,0 +1,29 @@ +package com.xtraction.api.identity.auth.oauth2.config; + +import lombok.Getter; +import lombok.Setter; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +import java.util.List; + +/** + * Type-safe configuration properties for OAuth2. + * Binds to properties under 'app.oauth2' prefix. + */ +@Getter +@Setter +@Configuration +@ConfigurationProperties(prefix = "app.oauth2") +public class OAuth2Properties { + /** + * The URI to redirect to after successful OAuth2 authentication. + * Typically, the frontend callback page. + */ + private String authorizedRedirectUri; + + /** + * List of allowed redirect URIs for security validation. + */ + private List allowedRedirectUris; +} diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/datamodel/AuthProvider.java b/src/main/java/com/xtraction/api/identity/auth/oauth2/datamodel/AuthProvider.java new file mode 100644 index 0000000..3133676 --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/auth/oauth2/datamodel/AuthProvider.java @@ -0,0 +1,10 @@ +package com.xtraction.api.identity.auth.oauth2.datamodel; + +/** + * Represents the authentication provider used to create a user account. + * Extensible — add new providers (e.g., GITHUB, MICROSOFT) as needed. + */ +public enum AuthProvider { + LOCAL, + GOOGLE +} diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/dto/GoogleOAuth2UserInfo.java b/src/main/java/com/xtraction/api/identity/auth/oauth2/dto/GoogleOAuth2UserInfo.java new file mode 100644 index 0000000..e095ada --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/auth/oauth2/dto/GoogleOAuth2UserInfo.java @@ -0,0 +1,16 @@ +package com.xtraction.api.identity.auth.oauth2.dto; + +import lombok.Builder; + +/** + * Immutable record representing user info extracted from Google's OAuth2 response. + */ +@Builder +public record GoogleOAuth2UserInfo( + String sub, + String email, + boolean emailVerified, + String givenName, + String familyName, + String picture +) {} diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationFailureHandler.java b/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationFailureHandler.java new file mode 100644 index 0000000..a4ee5c5 --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationFailureHandler.java @@ -0,0 +1,47 @@ +package com.xtraction.api.identity.auth.oauth2.handler; + +import com.xtraction.api.identity.auth.oauth2.config.OAuth2Properties; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.jspecify.annotations.NonNull; +import org.springframework.security.core.AuthenticationException; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler; +import org.springframework.stereotype.Component; +import org.springframework.web.util.UriComponentsBuilder; + +import java.io.IOException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; + +/** + * Handles OAuth2 authentication failures by redirecting to the frontend + * callback URL with an error parameter. + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class OAuth2AuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { + private final OAuth2Properties oAuth2Properties; + + @Override + public void onAuthenticationFailure( + @NonNull HttpServletRequest request, + @NonNull HttpServletResponse response, + AuthenticationException exception) throws IOException { + + log.error("OAuth2 authentication failed: {}", exception.getMessage()); + + String redirectUri = oAuth2Properties.getAuthorizedRedirectUri(); + String errorMessage = URLEncoder.encode( + exception.getLocalizedMessage(), StandardCharsets.UTF_8); + + String targetUrl = UriComponentsBuilder.fromUriString(redirectUri) + .queryParam("error", errorMessage) + .build() + .toUriString(); + + getRedirectStrategy().sendRedirect(request, response, targetUrl); + } +} diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationSuccessHandler.java b/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationSuccessHandler.java new file mode 100644 index 0000000..7c406f2 --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/auth/oauth2/handler/OAuth2AuthenticationSuccessHandler.java @@ -0,0 +1,99 @@ +package com.xtraction.api.identity.auth.oauth2.handler; + +import com.xtraction.api.core.security.JwtTokenProvider; +import com.xtraction.api.core.security.RefreshTokenService; +import com.xtraction.api.core.utils.CookieUtil; +import com.xtraction.api.identity.auth.oauth2.config.OAuth2Properties; +import com.xtraction.api.identity.user.model.User; +import com.xtraction.api.identity.user.repository.UserRepository; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.jspecify.annotations.NonNull; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.security.core.Authentication; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler; +import org.springframework.stereotype.Component; +import org.springframework.web.util.UriComponentsBuilder; + +import java.io.IOException; +import java.time.OffsetDateTime; + +/** + * Handles successful OAuth2 authentication by: + *
    + *
  1. Loading the provisioned user from the database
  2. + *
  3. Generating JWT access and refresh tokens
  4. + *
  5. Setting the refresh token as an HttpOnly cookie
  6. + *
  7. Redirecting to the frontend callback URL with the access token
  8. + *
+ */ +@Slf4j +@Component +@RequiredArgsConstructor +public class OAuth2AuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { + private final JwtTokenProvider jwtTokenProvider; + private final RefreshTokenService refreshTokenService; + private final UserRepository userRepository; + private final OAuth2Properties oAuth2Properties; + + @Value("${app.cookie-secure:true}") + private boolean cookieSecure; + + @Override + public void onAuthenticationSuccess( + @NonNull HttpServletRequest request, + HttpServletResponse response, + @NonNull Authentication authentication) throws IOException { + + if (response.isCommitted()) { + log.warn("Response has already been committed. Unable to redirect."); + return; + } + + OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal(); + assert oAuth2User != null; + String email = oAuth2User.getAttribute("email"); + + User user = userRepository.findByEmail(email) + .orElseThrow(() -> { + log.error("OAuth2 user not found in database after provisioning: {}", email); + return new RuntimeException("User not found after OAuth2 authentication"); + }); + + // Generate JWT tokens + String accessToken = jwtTokenProvider.generateAccessToken(user); + String refreshToken = jwtTokenProvider.generateRefreshToken(user); + + // Store refresh token JTI in Redis + String refreshTokenJti = jwtTokenProvider.getJtiFromToken(refreshToken); + if (refreshTokenJti != null) { + refreshTokenService.storeRefreshToken(refreshTokenJti, user.getId()); + } else { + log.error("Could not extract JTI from refresh token for OAuth user {}", user.getEmail()); + } + + // Update last login timestamp + user.setLastLogin(OffsetDateTime.now()); + userRepository.save(user); + + // Set refresh token as HttpOnly cookie + long maxAgeSeconds = jwtTokenProvider.getRefreshExpirationInMs() / 1000; + CookieUtil.addRefreshTokenCookie(response, refreshToken, maxAgeSeconds, cookieSecure); + + // Build redirect URL with access token and profile status + String redirectUri = oAuth2Properties.getAuthorizedRedirectUri(); + String targetUrl = UriComponentsBuilder.fromUriString(redirectUri) + .queryParam("token", accessToken) + .queryParam("profileComplete", user.isProfileComplete()) + .build() + .toUriString(); + + log.info("OAuth2 login successful for user {}. Redirecting to frontend.", user.getEmail()); + + clearAuthenticationAttributes(request); + getRedirectStrategy().sendRedirect(request, response, targetUrl); + } +} diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/impl/OAuth2UserProvisioningImpl.java b/src/main/java/com/xtraction/api/identity/auth/oauth2/impl/OAuth2UserProvisioningImpl.java new file mode 100644 index 0000000..5b68d6f --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/auth/oauth2/impl/OAuth2UserProvisioningImpl.java @@ -0,0 +1,167 @@ +package com.xtraction.api.identity.auth.oauth2.impl; + +import com.xtraction.api.billing.credit.service.CreditBalanceService; +import com.xtraction.api.billing.subscription.impl.AssignSubscriptionService; +import com.xtraction.api.billing.subscription.model.UserSubscription; +import com.xtraction.api.core.exceptions.custom.BadRequestException; +import com.xtraction.api.extraction.search.events.IndexAction; +import com.xtraction.api.extraction.search.service.ElasticsearchIndexingService; +import com.xtraction.api.identity.auth.datamodel.Role; +import com.xtraction.api.identity.auth.oauth2.datamodel.AuthProvider; +import com.xtraction.api.identity.auth.oauth2.dto.GoogleOAuth2UserInfo; +import com.xtraction.api.identity.auth.oauth2.interfaces.OAuth2UserProvisioningService; +import com.xtraction.api.identity.user.model.User; +import com.xtraction.api.identity.user.repository.UserRepository; +import com.xtraction.api.integration.notification.datamodel.NotificationType; +import com.xtraction.api.integration.notification.interfaces.NotificationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.time.OffsetDateTime; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + + +@Slf4j +@Service +@RequiredArgsConstructor +public class OAuth2UserProvisioningImpl implements OAuth2UserProvisioningService { + private final UserRepository userRepository; + private final AssignSubscriptionService assignSubscriptionService; + private final CreditBalanceService creditBalanceService; + private final NotificationService notificationService; + private final Optional elasticsearchIndexingService; + + @Override + @Transactional + public User provisionOAuth2User(GoogleOAuth2UserInfo userInfo) { + if (!userInfo.emailVerified()) { + throw new BadRequestException("Google email is not verified. Cannot proceed with OAuth login."); + } + + // Lookup by provider + provider ID (returning Google user) + Optional existingByProvider = userRepository.findByAuthProviderAndProviderId( + AuthProvider.GOOGLE, userInfo.sub()); + + if (existingByProvider.isPresent()) { + log.debug("Returning OAuth user found by provider ID: {}", userInfo.sub()); + return existingByProvider.get(); + } + + // Lookup by email (auto-link LOCAL account to Google) + Optional existingByEmail = userRepository.findByEmail(userInfo.email()); + + // Create a brand-new OAuth user + return existingByEmail.map(user -> linkExistingAccount(user, userInfo)).orElseGet(() -> createNewOAuthUser(userInfo)); + } + + /** + * Links an existing LOCAL account with Google OAuth. + * Only links if the user's email is verified (prevents account hijacking). + */ + private User linkExistingAccount(User existingUser, GoogleOAuth2UserInfo userInfo) { + if (existingUser.getDeletedAt() != null) { + throw new BadRequestException( + "This account has been deactivated. Please contact support."); + } + + log.info("Auto-linking existing account {} with Google OAuth", existingUser.getEmail()); + + existingUser.setAuthProvider(AuthProvider.GOOGLE); + existingUser.setProviderId(userInfo.sub()); + + // Sync profile picture only on first link (not on every login) + if (existingUser.getProfilePicture() == null && userInfo.picture() != null) { + existingUser.setProfilePicture(userInfo.picture()); + } + + // Ensure the account is active and verified (Google verified the email) + existingUser.setActive(true); + existingUser.setVerified(true); + + return userRepository.save(existingUser); + } + + /** + * Creates a brand-new user from Google OAuth info. + * Sets profileComplete=false so the frontend can prompt for missing fields. + */ + private User createNewOAuthUser(GoogleOAuth2UserInfo userInfo) { + log.info("Creating new OAuth user for email: {}", userInfo.email()); + + OffsetDateTime now = OffsetDateTime.now(); + + User user = new User(); + user.setFirstName(userInfo.givenName() != null ? userInfo.givenName() : "User"); + user.setLastName(userInfo.familyName() != null ? userInfo.familyName() : ""); + user.setEmail(userInfo.email().toLowerCase()); + user.setPassword(null); // OAuth users have no password + user.setAuthProvider(AuthProvider.GOOGLE); + user.setProviderId(userInfo.sub()); + user.setActive(true); + user.setVerified(true); // Google has already verified the email + user.setRole(Role.USER); + user.setTermsAccepted(false); + user.setMarketingOptIn(false); + user.setCountry(null); // Will be prompted by frontend + user.setProfileComplete(false); // Frontend will prompt for completion + user.setCreatedAt(now); + user.setUpdatedAt(now); + + // Sync profile picture on first registration + if (userInfo.picture() != null) { + user.setProfilePicture(userInfo.picture()); + } + + // Assign default subscription + UserSubscription subscription = assignSubscriptionService.assignDefaultSubscription(user); + user.setSubscription(subscription); + + User savedUser = userRepository.save(user); + + // Post-creation tasks (non-critical, don't fail the registration) + performPostCreationTasks(savedUser); + + return savedUser; + } + + private void performPostCreationTasks(User user) { + // Index in Elasticsearch + elasticsearchIndexingService.ifPresent(service -> { + try { + service.indexUser(user, IndexAction.CREATE); + } catch (Exception e) { + log.error("Failed to index OAuth user in Elasticsearch: {}", e.getMessage()); + } + }); + + // Send welcome notification + try { + Map data = new HashMap<>(); + data.put("userId", user.getId()); + data.put("email", user.getEmail()); + + notificationService.sendToUser( + user.getId(), + NotificationType.WELCOME, + "Welcome to Xtraction!", + String.format("Hi %s, welcome to Xtraction! Start uploading documents to get started.", + user.getFirstName()), + data); + } catch (Exception e) { + log.error("Failed to send welcome notification to OAuth user: {}", e.getMessage()); + } + + // Grant signup bonus credits + try { + creditBalanceService.grantSignupBonus(user); + log.info("Granted sign-up bonus credits to OAuth user {}", user.getId()); + } catch (Exception e) { + log.error("Failed to grant sign-up bonus credits to OAuth user {}: {}", + user.getId(), e.getMessage()); + } + } +} diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/interfaces/OAuth2UserProvisioningService.java b/src/main/java/com/xtraction/api/identity/auth/oauth2/interfaces/OAuth2UserProvisioningService.java new file mode 100644 index 0000000..cbd88eb --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/auth/oauth2/interfaces/OAuth2UserProvisioningService.java @@ -0,0 +1,24 @@ +package com.xtraction.api.identity.auth.oauth2.interfaces; + +import com.xtraction.api.identity.auth.oauth2.dto.GoogleOAuth2UserInfo; +import com.xtraction.api.identity.user.model.User; + +/** + * Service responsible for provisioning (creating or linking) users + * based on OAuth2 provider information. + */ +public interface OAuth2UserProvisioningService { + + /** + * Provisions a user based on Google OAuth2 user info. + *
    + *
  • If a user with matching provider + providerId exists, returns that user (returning user).
  • + *
  • If a user with matching email exists (LOCAL auth), auto-links the Google account.
  • + *
  • If no match, creates a new user with Google as the auth provider.
  • + *
+ * + * @param userInfo the user information from Google + * @return the provisioned or linked User entity + */ + User provisionOAuth2User(GoogleOAuth2UserInfo userInfo); +} diff --git a/src/main/java/com/xtraction/api/identity/auth/oauth2/service/CustomOAuth2UserService.java b/src/main/java/com/xtraction/api/identity/auth/oauth2/service/CustomOAuth2UserService.java new file mode 100644 index 0000000..708c489 --- /dev/null +++ b/src/main/java/com/xtraction/api/identity/auth/oauth2/service/CustomOAuth2UserService.java @@ -0,0 +1,79 @@ +package com.xtraction.api.identity.auth.oauth2.service; + +import com.xtraction.api.identity.auth.oauth2.dto.GoogleOAuth2UserInfo; +import com.xtraction.api.identity.auth.oauth2.interfaces.OAuth2UserProvisioningService; +import com.xtraction.api.identity.user.model.User; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.jspecify.annotations.NonNull; +import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest; +import org.springframework.security.oauth2.client.userinfo.OAuth2UserService; +import org.springframework.security.oauth2.core.OAuth2AuthenticationException; +import org.springframework.security.oauth2.core.OAuth2Error; +import org.springframework.security.oauth2.core.user.OAuth2User; +import org.springframework.stereotype.Service; + +import java.util.Map; + +/** + * Custom OAuth2 user service that integrates Spring Security's OAuth2 login + * with the application's user provisioning system. + * + *

This service is invoked by Spring Security after successfully exchanging + * the authorization code for tokens. It:

+ *
    + *
  1. Delegates to the default service to fetch user info from Google
  2. + *
  3. Extracts the user profile into a typed DTO
  4. + *
  5. Provisions (creates or links) the user in the local database
  6. + *
  7. Returns the OAuth2User for Spring Security's authentication context
  8. + *
+ */ +@Slf4j +@Service +@RequiredArgsConstructor +public class CustomOAuth2UserService implements OAuth2UserService { + private final OAuth2UserProvisioningService provisioningService; + private final DefaultOAuth2UserService defaultOAuth2UserService = new DefaultOAuth2UserService(); + + @Override + public OAuth2User loadUser( + @NonNull OAuth2UserRequest userRequest) throws OAuth2AuthenticationException { + // Delegate to Spring's default service to fetch user info from Google + OAuth2User oAuth2User = defaultOAuth2UserService.loadUser(userRequest); + + try { + return processOAuth2User(oAuth2User); + } catch (Exception ex) { + log.error("Error processing OAuth2 user: {}", ex.getMessage(), ex); + throw new OAuth2AuthenticationException( + new OAuth2Error("processing_error", ex.getMessage(), null), ex); + } + } + + private OAuth2User processOAuth2User(OAuth2User oAuth2User) { + Map attributes = oAuth2User.getAttributes(); + + // Extract Google user info into typed DTO + GoogleOAuth2UserInfo userInfo = GoogleOAuth2UserInfo.builder() + .sub((String) attributes.get("sub")) + .email((String) attributes.get("email")) + .emailVerified(Boolean.TRUE.equals(attributes.get("email_verified"))) + .givenName((String) attributes.get("given_name")) + .familyName((String) attributes.get("family_name")) + .picture((String) attributes.get("picture")) + .build(); + + log.debug("Processing Google OAuth2 user: {}", userInfo.email()); + + // Provision or link the user (handles all 3 strategies) + User user = provisioningService.provisionOAuth2User(userInfo); + + log.info("OAuth2 user provisioned successfully: userId={}, email={}", + user.getId(), user.getEmail()); + + // Return the original OAuth2User — the success handler will use the + // user's email to load the full User entity for JWT generation + return oAuth2User; + } +} diff --git a/src/main/java/com/xtraction/api/identity/user/eventlistener/UserEventListener.java b/src/main/java/com/xtraction/api/identity/user/eventlistener/UserEventListener.java index 20c6644..3e522fa 100644 --- a/src/main/java/com/xtraction/api/identity/user/eventlistener/UserEventListener.java +++ b/src/main/java/com/xtraction/api/identity/user/eventlistener/UserEventListener.java @@ -2,11 +2,10 @@ import com.xtraction.api.identity.auth.events.UserRegisteredEvent; import com.xtraction.api.identity.auth.events.WelcomeEvent; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.kafka.events.EventHandler; import com.xtraction.api.identity.user.events.*; import com.fasterxml.jackson.databind.ObjectMapper; -import com.xtraction.api.identity.user.events.*; import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -36,7 +35,11 @@ public void initializeHandlers() { log.info("Initialized event handlers for types: {}", eventHandlers.keySet()); } - @KafkaListener(topics = KafkaTopicConfig.TOPIC_USERS, groupId = "user-events-group", containerFactory = "kafkaListenerContainerFactory") + @KafkaListener( + topics = KafkaTopicRegistry.USERS, + groupId = "user-events-group", + containerFactory = "kafkaListenerContainerFactory" + ) public void handleUserEvent(ConsumerRecord record, Acknowledgment acknowledgment) { String eventType = extractEventType(record); Object payload = record.value(); diff --git a/src/main/java/com/xtraction/api/identity/user/model/User.java b/src/main/java/com/xtraction/api/identity/user/model/User.java index 8a1eec9..d185dde 100644 --- a/src/main/java/com/xtraction/api/identity/user/model/User.java +++ b/src/main/java/com/xtraction/api/identity/user/model/User.java @@ -4,12 +4,14 @@ import com.xtraction.api.identity.auth.model.UserVerification; import com.xtraction.api.extraction.documents.model.DocumentCollection; import com.xtraction.api.billing.subscription.model.UserSubscription; +import com.xtraction.api.identity.auth.oauth2.datamodel.AuthProvider; import jakarta.persistence.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; +import org.jspecify.annotations.NonNull; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; @@ -46,12 +48,19 @@ public class User implements UserDetails { @Column(nullable = false, unique = true) private String email; - @Column(nullable = false) + @Column private String password; @Column(name = "last_login", columnDefinition = "TIMESTAMP") private OffsetDateTime lastLogin; + @Enumerated(EnumType.STRING) + @Column(name = "auth_provider", nullable = false) + private AuthProvider authProvider = AuthProvider.LOCAL; + + @Column(name = "provider_id") + private String providerId; + @Column(nullable = false, name = "is_active") private boolean isActive = false; @@ -68,6 +77,9 @@ public class User implements UserDetails { @Column(nullable = false, columnDefinition = "VARCHAR(20) DEFAULT 'user'") private Role role = Role.USER; + @Column(name = "profile_complete", nullable = false) + private boolean profileComplete = true; + @Column(name = "deleted_at") private OffsetDateTime deletedAt; @@ -77,7 +89,7 @@ public class User implements UserDetails { @Column(name = "marketing_opt_in", nullable = false) private boolean marketingOptIn = false; - @Column(name = "country", nullable = false) + @Column(name = "country") private String country; @Column(name = "profession") @@ -104,7 +116,7 @@ public class User implements UserDetails { private OffsetDateTime updatedAt; @Override - public Collection getAuthorities() { + public @NonNull Collection getAuthorities() { return Collections.singletonList(new SimpleGrantedAuthority("ROLE_" + getRole().name())); } @@ -115,27 +127,14 @@ public String getPassword() { @Override - public String getUsername() { + public @NonNull String getUsername() { return email; } - @Override - public boolean isAccountNonExpired() { - return true; - } - - @Override - public boolean isAccountNonLocked() { - return true; - } - - @Override - public boolean isCredentialsNonExpired() { - return true; - } - @Override public boolean isEnabled() { - return this.isActive && this.isVerified; + return this.authProvider != AuthProvider.LOCAL + ? this.isActive + : (this.isActive && this.isVerified); } } diff --git a/src/main/java/com/xtraction/api/identity/user/repository/UserRepository.java b/src/main/java/com/xtraction/api/identity/user/repository/UserRepository.java index 57409ea..640a7d3 100644 --- a/src/main/java/com/xtraction/api/identity/user/repository/UserRepository.java +++ b/src/main/java/com/xtraction/api/identity/user/repository/UserRepository.java @@ -1,5 +1,6 @@ package com.xtraction.api.identity.user.repository; +import com.xtraction.api.identity.auth.oauth2.datamodel.AuthProvider; import com.xtraction.api.identity.user.model.User; import lombok.NonNull; import org.springframework.data.domain.Page; @@ -17,6 +18,8 @@ public interface UserRepository extends JpaRepository<@NonNull User, @NonNull String>, CustomUserRepository { Optional findByEmail(String email); + Optional findByAuthProviderAndProviderId(AuthProvider authProvider, String providerId); + Optional findUserById(String id); List findBySubscriptionIsNull(); @@ -29,8 +32,6 @@ public interface UserRepository extends JpaRepository<@NonNull User, @NonNull St @Query("SELECT u FROM User u WHERE u.deletedAt < :threshold") Page findAllByDeletedAtBefore(@Param("threshold") OffsetDateTime threshold, Pageable pageable); - // ========== PromoCode Notification Query Methods (Performance Optimized) - // ========== /** * Find users created after a specific date who are not deleted. diff --git a/src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaConsumerConfig.java b/src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaConsumerConfig.java deleted file mode 100644 index 99d38c7..0000000 --- a/src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaConsumerConfig.java +++ /dev/null @@ -1,155 +0,0 @@ -package com.xtraction.api.integration.broker.kafka.config; - -import com.xtraction.api.integration.broker.config.MessagingProperties; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.apache.kafka.clients.consumer.ConsumerConfig; -import org.apache.kafka.common.serialization.StringDeserializer; -import org.jspecify.annotations.NonNull; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory; -import org.springframework.kafka.core.ConsumerFactory; -import org.springframework.kafka.core.DefaultKafkaConsumerFactory; -import org.springframework.kafka.core.KafkaTemplate; -import org.springframework.kafka.listener.ContainerProperties; -import org.springframework.kafka.listener.DeadLetterPublishingRecoverer; -import org.springframework.kafka.listener.DefaultErrorHandler; -import org.springframework.kafka.support.serializer.ErrorHandlingDeserializer; -import org.springframework.kafka.support.serializer.JacksonJsonDeserializer; -import org.springframework.util.backoff.ExponentialBackOff; - -import java.util.HashMap; -import java.util.Map; - -/** - * Kafka consumer configuration. - * Only loaded when Kafka bootstrap servers are configured. - */ -@Slf4j -@Configuration -@RequiredArgsConstructor -@ConditionalOnProperty(name = "spring.kafka.bootstrap-servers") -public class KafkaConsumerConfig { - - private final MessagingProperties messagingProperties; - - @Value("${spring.kafka.bootstrap-servers}") - private String bootstrapServers; - - @Value("${spring.kafka.consumer.group-id:unraveldocs-group}") - private String groupId; - - @Value("${spring.kafka.consumer.auto-offset-reset:earliest}") - private String autoOffsetReset; - - @Value("${spring.kafka.consumer.enable-auto-commit:false}") - private boolean enableAutoCommit; - - @Bean - public ConsumerFactory consumerFactory() { - Map configProps = new HashMap<>(); - var consumerProps = messagingProperties.getKafka().getConsumer(); - - // Connection settings - configProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers); - configProps.put(ConsumerConfig.GROUP_ID_CONFIG, groupId); - - // Offset handling - configProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset); - configProps.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit); - - // Deserialization with error handling - configProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class); - configProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ErrorHandlingDeserializer.class); - configProps.put(ErrorHandlingDeserializer.KEY_DESERIALIZER_CLASS, StringDeserializer.class); - configProps.put(ErrorHandlingDeserializer.VALUE_DESERIALIZER_CLASS, JacksonJsonDeserializer.class); - - // JSON deserializer settings - configProps.put(JacksonJsonDeserializer.TRUSTED_PACKAGES, "com.xtraction.api.*"); - configProps.put(JacksonJsonDeserializer.USE_TYPE_INFO_HEADERS, true); - - // Performance tuning - use configurable values - configProps.put(ConsumerConfig.MAX_POLL_RECORDS_CONFIG, consumerProps.getMaxPollRecords()); - configProps.put(ConsumerConfig.FETCH_MIN_BYTES_CONFIG, 1); - configProps.put(ConsumerConfig.FETCH_MAX_WAIT_MS_CONFIG, 500); - - // Session and heartbeat settings - configProps.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, consumerProps.getSessionTimeoutMs()); - configProps.put(ConsumerConfig.HEARTBEAT_INTERVAL_MS_CONFIG, consumerProps.getHeartbeatIntervalMs()); - - return new DefaultKafkaConsumerFactory<>(configProps); - } - - @Bean - public ConcurrentKafkaListenerContainerFactory kafkaListenerContainerFactory( - ConsumerFactory consumerFactory, - DefaultErrorHandler errorHandler) { - ConcurrentKafkaListenerContainerFactory factory = new ConcurrentKafkaListenerContainerFactory<>(); - - factory.setConsumerFactory(consumerFactory); - factory.setCommonErrorHandler(errorHandler); - - // Manual acknowledgment for exactly-once semantics - factory.getContainerProperties().setAckMode(ContainerProperties.AckMode.MANUAL_IMMEDIATE); - - // Concurrency (number of consumer threads) - configurable - factory.setConcurrency(messagingProperties.getKafka().getConsumer().getConcurrency()); - - log.info("Kafka listener container configured with concurrency: {}", - messagingProperties.getKafka().getConsumer().getConcurrency()); - - return factory; - } - - @Bean - public DefaultErrorHandler errorHandler(KafkaTemplate kafkaTemplate) { - var retryProps = messagingProperties.getKafka().getRetry(); - - // Configure exponential backoff - ExponentialBackOff backOff = new ExponentialBackOff( - retryProps.getInitialIntervalMs(), - retryProps.getMultiplier()); - backOff.setMaxInterval(retryProps.getMaxIntervalMs()); - backOff.setMaxElapsedTime(retryProps.getMaxIntervalMs() * retryProps.getMaxAttempts()); - - // Dead Letter Publishing Recoverer - routes to DLQ after all retries exhausted - DefaultErrorHandler errorHandler = getErrorHandler(kafkaTemplate, backOff); - - // Don't retry for certain exceptions (non-recoverable) - errorHandler.addNotRetryableExceptions( - IllegalArgumentException.class, - NullPointerException.class, - ClassCastException.class); - - log.info("Kafka error handler configured with exponential backoff: initialInterval={}ms, multiplier={}, maxInterval={}ms", - retryProps.getInitialIntervalMs(), - retryProps.getMultiplier(), - retryProps.getMaxIntervalMs()); - - return errorHandler; - } - - private static @NonNull DefaultErrorHandler getErrorHandler(KafkaTemplate kafkaTemplate, - ExponentialBackOff backOff) { - DeadLetterPublishingRecoverer recoverer = new DeadLetterPublishingRecoverer( - kafkaTemplate, - (record, ex) -> { - String dlqTopic = record.topic() + "-dlq"; - log.error( - "Exhausted retries. Routing to DLQ: {}. Original topic: {}, Partition: {}, Offset: {}, Error: {}", - dlqTopic, - record.topic(), - record.partition(), - record.offset(), - ex.getMessage(), - ex // Add full stack trace - ); - return new org.apache.kafka.common.TopicPartition(dlqTopic, -1); - }); - - return new DefaultErrorHandler(recoverer, backOff); - } -} diff --git a/src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaTopicConfig.java b/src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaTopicConfig.java deleted file mode 100644 index c48a5ea..0000000 --- a/src/main/java/com/xtraction/api/integration/broker/kafka/config/KafkaTopicConfig.java +++ /dev/null @@ -1,318 +0,0 @@ -package com.xtraction.api.integration.broker.kafka.config; - -import org.apache.kafka.clients.admin.NewTopic; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.kafka.config.TopicBuilder; - -/** - * Kafka topic declarations. - * Topics are auto-created if they don't exist. - */ -@Configuration -@ConditionalOnProperty(name = "spring.kafka.bootstrap-servers") -public class KafkaTopicConfig { - - // Topic names as constants for reuse - public static final String TOPIC_EMAILS = "xtraction-emails"; - public static final String TOPIC_DOCUMENTS = "xtraction-documents"; - public static final String TOPIC_PAYMENTS = "xtraction-payments"; - public static final String TOPIC_USERS = "xtraction-users"; - public static final String TOPIC_NOTIFICATIONS = "xtraction-notifications"; - public static final String TOPIC_RECEIPTS = "xtraction-receipts"; - public static final String TOPIC_OCR = "xtraction-ocr"; - public static final String TOPIC_TEAM_EVENTS = "xtraction-team-events"; - public static final String TOPIC_ADMIN_EVENTS = "xtraction-admin-events"; - public static final String TOPIC_ELASTICSEARCH = "xtraction-elasticsearch"; - public static final String TOPIC_EXTRACTION_PROGRESS = "xtraction-extraction-progress"; - - // Retry topics (intermediate retry before DLQ) - public static final String TOPIC_EMAILS_RETRY = "xtraction-emails-retry"; - public static final String TOPIC_DOCUMENTS_RETRY = "xtraction-documents-retry"; - public static final String TOPIC_PAYMENTS_RETRY = "xtraction-payments-retry"; - public static final String TOPIC_USERS_RETRY = "xtraction-users-retry"; - public static final String TOPIC_RECEIPTS_RETRY = "xtraction-receipts-retry"; - public static final String TOPIC_OCR_RETRY = "xtraction-ocr-retry"; - public static final String TOPIC_TEAM_EVENTS_RETRY = "xtraction-team-events-retry"; - public static final String TOPIC_ADMIN_EVENTS_RETRY = "xtraction-admin-events-retry"; - public static final String TOPIC_ELASTICSEARCH_RETRY = "xtraction-elasticsearch-retry"; - - // Dead Letter Queue topics - public static final String TOPIC_EMAILS_DLQ = "xtraction-emails-dlq"; - public static final String TOPIC_DOCUMENTS_DLQ = "xtraction-documents-dlq"; - public static final String TOPIC_PAYMENTS_DLQ = "xtraction-payments-dlq"; - public static final String TOPIC_USERS_DLQ = "xtraction-users-dlq"; - public static final String TOPIC_RECEIPTS_DLQ = "xtraction-receipts-dlq"; - public static final String TOPIC_OCR_DLQ = "xtraction-ocr-dlq"; - public static final String TOPIC_TEAM_EVENTS_DLQ = "xtraction-team-events-dlq"; - public static final String TOPIC_ADMIN_EVENTS_DLQ = "xtraction-admin-events-dlq"; - public static final String TOPIC_ELASTICSEARCH_DLQ = "xtraction-elasticsearch-dlq"; - - @Bean - public NewTopic emailsTopic() { - return TopicBuilder.name(TOPIC_EMAILS) - .partitions(3) - .replicas(1) - .config("retention.ms", "604800000") // 7 days - .build(); - } - - @Bean - public NewTopic documentsTopic() { - return TopicBuilder.name(TOPIC_DOCUMENTS) - .partitions(6) // Higher partition count for document processing - .replicas(1) - .config("retention.ms", "604800000") - .build(); - } - - @Bean - public NewTopic paymentsTopic() { - return TopicBuilder.name(TOPIC_PAYMENTS) - .partitions(3) - .replicas(1) - .config("retention.ms", "2592000000") // 30 days for payments - .build(); - } - - @Bean - public NewTopic usersTopic() { - return TopicBuilder.name(TOPIC_USERS) - .partitions(3) - .replicas(1) - .config("retention.ms", "604800000") - .build(); - } - - @Bean - public NewTopic notificationsTopic() { - return TopicBuilder.name(TOPIC_NOTIFICATIONS) - .partitions(3) - .replicas(1) - .config("retention.ms", "259200000") // 3 days - .build(); - } - - @Bean - public NewTopic receiptsTopic() { - return TopicBuilder.name(TOPIC_RECEIPTS) - .partitions(3) - .replicas(1) - .config("retention.ms", "2592000000") // 30 days for receipts - .build(); - } - - // Dead Letter Queue topics - @Bean - public NewTopic emailsDlqTopic() { - return TopicBuilder.name(TOPIC_EMAILS_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") // 30 days - .build(); - } - - @Bean - public NewTopic documentsDlqTopic() { - return TopicBuilder.name(TOPIC_DOCUMENTS_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") - .build(); - } - - @Bean - public NewTopic paymentsDlqTopic() { - return TopicBuilder.name(TOPIC_PAYMENTS_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") - .build(); - } - - @Bean - public NewTopic usersDlqTopic() { - return TopicBuilder.name(TOPIC_USERS_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") - .build(); - } - - @Bean - public NewTopic receiptsDlqTopic() { - return TopicBuilder.name(TOPIC_RECEIPTS_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") - .build(); - } - - // Retry topics (short retention, for intermediate retry attempts) - @Bean - public NewTopic emailsRetryTopic() { - return TopicBuilder.name(TOPIC_EMAILS_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") // 1 day - .build(); - } - - @Bean - public NewTopic documentsRetryTopic() { - return TopicBuilder.name(TOPIC_DOCUMENTS_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") - .build(); - } - - @Bean - public NewTopic paymentsRetryTopic() { - return TopicBuilder.name(TOPIC_PAYMENTS_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") - .build(); - } - - @Bean - public NewTopic usersRetryTopic() { - return TopicBuilder.name(TOPIC_USERS_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") - .build(); - } - - @Bean - public NewTopic receiptsRetryTopic() { - return TopicBuilder.name(TOPIC_RECEIPTS_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") - .build(); - } - - // ==================== New Topics (Migrated from RabbitMQ) ==================== - - @Bean - public NewTopic ocrTopic() { - return TopicBuilder.name(TOPIC_OCR) - .partitions(3) - .replicas(1) - .config("retention.ms", "604800000") // 7 days - .build(); - } - - @Bean - public NewTopic teamEventsTopic() { - return TopicBuilder.name(TOPIC_TEAM_EVENTS) - .partitions(3) - .replicas(1) - .config("retention.ms", "604800000") - .build(); - } - - @Bean - public NewTopic adminEventsTopic() { - return TopicBuilder.name(TOPIC_ADMIN_EVENTS) - .partitions(3) - .replicas(1) - .config("retention.ms", "604800000") - .build(); - } - - @Bean - public NewTopic elasticsearchTopic() { - return TopicBuilder.name(TOPIC_ELASTICSEARCH) - .partitions(6) // Higher partition count for ES indexing - .replicas(1) - .config("retention.ms", "604800000") - .build(); - } - - @Bean - public NewTopic extractionProgressTopic() { - return TopicBuilder.name(TOPIC_EXTRACTION_PROGRESS) - .partitions(3) - .replicas(1) - .config("retention.ms", "259200000") // 3 days - .build(); - } - - // DLQ topics for new topics - @Bean - public NewTopic ocrDlqTopic() { - return TopicBuilder.name(TOPIC_OCR_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") - .build(); - } - - @Bean - public NewTopic teamEventsDlqTopic() { - return TopicBuilder.name(TOPIC_TEAM_EVENTS_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") - .build(); - } - - @Bean - public NewTopic adminEventsDlqTopic() { - return TopicBuilder.name(TOPIC_ADMIN_EVENTS_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") - .build(); - } - - @Bean - public NewTopic elasticsearchDlqTopic() { - return TopicBuilder.name(TOPIC_ELASTICSEARCH_DLQ) - .partitions(1) - .replicas(1) - .config("retention.ms", "2592000000") - .build(); - } - - // Retry topics for new topics - @Bean - public NewTopic ocrRetryTopic() { - return TopicBuilder.name(TOPIC_OCR_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") - .build(); - } - - @Bean - public NewTopic teamEventsRetryTopic() { - return TopicBuilder.name(TOPIC_TEAM_EVENTS_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") - .build(); - } - - @Bean - public NewTopic adminEventsRetryTopic() { - return TopicBuilder.name(TOPIC_ADMIN_EVENTS_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") - .build(); - } - - @Bean - public NewTopic elasticsearchRetryTopic() { - return TopicBuilder.name(TOPIC_ELASTICSEARCH_RETRY) - .partitions(1) - .replicas(1) - .config("retention.ms", "86400000") - .build(); - } -} diff --git a/src/main/java/com/xtraction/api/integration/broker/kafka/consumer/EmailKafkaConsumer.java b/src/main/java/com/xtraction/api/integration/broker/kafka/consumer/EmailKafkaConsumer.java index 9e701b7..571ff96 100644 --- a/src/main/java/com/xtraction/api/integration/broker/kafka/consumer/EmailKafkaConsumer.java +++ b/src/main/java/com/xtraction/api/integration/broker/kafka/consumer/EmailKafkaConsumer.java @@ -1,7 +1,7 @@ package com.xtraction.api.integration.broker.kafka.consumer; import com.xtraction.api.core.utils.logging.SanitizeLogging; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.messages.EmailNotificationMessage; import com.xtraction.api.integration.messaging.dto.EmailMessage; import com.xtraction.api.integration.messaging.emailservice.EmailOrchestratorService; @@ -25,7 +25,7 @@ public class EmailKafkaConsumer { private final EmailOrchestratorService emailOrchestratorService; private final SanitizeLogging sanitizer; - @KafkaListener(topics = KafkaTopicConfig.TOPIC_EMAILS, groupId = "email-consumer-group", containerFactory = "kafkaListenerContainerFactory") + @KafkaListener(topics = KafkaTopicRegistry.EMAILS, groupId = "email-consumer-group", containerFactory = "kafkaListenerContainerFactory") public void handleEmailRequest(EmailNotificationMessage emailNotificationMessage, Acknowledgment acknowledgment) { log.info("Received email request for: {}", sanitizer.sanitizeLogging(emailNotificationMessage.to())); try { diff --git a/src/main/java/com/xtraction/api/integration/broker/kafka/events/EventPublisherService.java b/src/main/java/com/xtraction/api/integration/broker/kafka/events/EventPublisherService.java index ba2f5d7..2f605bb 100644 --- a/src/main/java/com/xtraction/api/integration/broker/kafka/events/EventPublisherService.java +++ b/src/main/java/com/xtraction/api/integration/broker/kafka/events/EventPublisherService.java @@ -4,7 +4,7 @@ import com.xtraction.api.integration.broker.core.MessageBrokerFactory; import com.xtraction.api.integration.broker.core.MessageBrokerType; import com.xtraction.api.integration.broker.core.MessagingException; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -71,20 +71,20 @@ public void publishEvent(String topic, BaseEvent event) { * Publishes a user event to the users topic. */ public void publishUserEvent(BaseEvent event) { - publishEvent(KafkaTopicConfig.TOPIC_USERS, event); + publishEvent(KafkaTopicRegistry.USERS, event); } /** * Publishes a team event to the team events topic. */ public void publishTeamEvent(BaseEvent event) { - publishEvent(KafkaTopicConfig.TOPIC_TEAM_EVENTS, event); + publishEvent(KafkaTopicRegistry.TEAM_EVENTS, event); } /** * Publishes an admin event to the admin events topic. */ public void publishAdminEvent(BaseEvent event) { - publishEvent(KafkaTopicConfig.TOPIC_ADMIN_EVENTS, event); + publishEvent(KafkaTopicRegistry.ADMIN_EVENTS, event); } } diff --git a/src/main/java/com/xtraction/api/integration/broker/kafka/handler/KafkaErrorHandler.java b/src/main/java/com/xtraction/api/integration/broker/kafka/handler/KafkaErrorHandler.java index 4e407f0..787754a 100644 --- a/src/main/java/com/xtraction/api/integration/broker/kafka/handler/KafkaErrorHandler.java +++ b/src/main/java/com/xtraction/api/integration/broker/kafka/handler/KafkaErrorHandler.java @@ -1,6 +1,6 @@ package com.xtraction.api.integration.broker.kafka.handler; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.consumer.ConsumerRecord; @@ -131,14 +131,7 @@ private String getDlqTopic(String sourceTopic) { if (sourceTopic.endsWith("-retry")) { return sourceTopic.replace("-retry", "-dlq"); } - - return switch (sourceTopic) { - case KafkaTopicConfig.TOPIC_EMAILS -> KafkaTopicConfig.TOPIC_EMAILS_DLQ; - case KafkaTopicConfig.TOPIC_DOCUMENTS -> KafkaTopicConfig.TOPIC_DOCUMENTS_DLQ; - case KafkaTopicConfig.TOPIC_PAYMENTS -> KafkaTopicConfig.TOPIC_PAYMENTS_DLQ; - case KafkaTopicConfig.TOPIC_USERS -> KafkaTopicConfig.TOPIC_USERS_DLQ; - default -> sourceTopic + "-dlq"; - }; + return KafkaTopicRegistry.getDlqTopic(sourceTopic); } /** @@ -146,13 +139,7 @@ private String getDlqTopic(String sourceTopic) { * Returns null if retry topics are not applicable for this topic. */ public String getRetryTopic(String sourceTopic) { - return switch (sourceTopic) { - case KafkaTopicConfig.TOPIC_EMAILS -> KafkaTopicConfig.TOPIC_EMAILS_RETRY; - case KafkaTopicConfig.TOPIC_DOCUMENTS -> KafkaTopicConfig.TOPIC_DOCUMENTS_RETRY; - case KafkaTopicConfig.TOPIC_PAYMENTS -> KafkaTopicConfig.TOPIC_PAYMENTS_RETRY; - case KafkaTopicConfig.TOPIC_USERS -> KafkaTopicConfig.TOPIC_USERS_RETRY; - default -> null; - }; + return KafkaTopicRegistry.getRetryTopic(sourceTopic); } /** diff --git a/src/main/java/com/xtraction/api/integration/broker/service/DocumentProcessingProducerService.java b/src/main/java/com/xtraction/api/integration/broker/service/DocumentProcessingProducerService.java index 81084f6..889b327 100644 --- a/src/main/java/com/xtraction/api/integration/broker/service/DocumentProcessingProducerService.java +++ b/src/main/java/com/xtraction/api/integration/broker/service/DocumentProcessingProducerService.java @@ -3,7 +3,7 @@ import com.xtraction.api.integration.broker.core.Message; import com.xtraction.api.integration.broker.core.MessageBrokerFactory; import com.xtraction.api.integration.broker.core.MessageResult; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.messages.DocumentProcessingMessage; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -158,7 +158,7 @@ private CompletableFuture sendProcessingMessage(DocumentProcessin Message message = Message.of( docMessage, - KafkaTopicConfig.TOPIC_DOCUMENTS, + KafkaTopicRegistry.DOCUMENTS, docMessage.userId() // Use user ID as partition key for ordering per user ); diff --git a/src/main/java/com/xtraction/api/integration/broker/service/EmailMessageProducerService.java b/src/main/java/com/xtraction/api/integration/broker/service/EmailMessageProducerService.java index 15ad0f7..764741f 100644 --- a/src/main/java/com/xtraction/api/integration/broker/service/EmailMessageProducerService.java +++ b/src/main/java/com/xtraction/api/integration/broker/service/EmailMessageProducerService.java @@ -5,7 +5,7 @@ import com.xtraction.api.integration.broker.core.MessageBrokerFactory; import com.xtraction.api.integration.broker.core.MessageBrokerType; import com.xtraction.api.integration.broker.core.MessageResult; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.messages.EmailNotificationMessage; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -114,7 +114,7 @@ public CompletableFuture sendEmailMessage(EmailNotificationMessag Message message = Message.of( emailMessage, - KafkaTopicConfig.TOPIC_EMAILS, + KafkaTopicRegistry.EMAILS, emailMessage.to() // Use recipient as key for ordering ); diff --git a/src/main/java/com/xtraction/api/integration/broker/service/PaymentEventProducerService.java b/src/main/java/com/xtraction/api/integration/broker/service/PaymentEventProducerService.java index e120a94..7cabc59 100644 --- a/src/main/java/com/xtraction/api/integration/broker/service/PaymentEventProducerService.java +++ b/src/main/java/com/xtraction/api/integration/broker/service/PaymentEventProducerService.java @@ -3,7 +3,7 @@ import com.xtraction.api.integration.broker.core.Message; import com.xtraction.api.integration.broker.core.MessageBrokerFactory; import com.xtraction.api.integration.broker.core.MessageResult; -import com.xtraction.api.integration.broker.kafka.config.KafkaTopicConfig; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.broker.messages.PaymentEventMessage; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -156,7 +156,7 @@ private CompletableFuture sendPaymentEvent(PaymentEventMessage ev Message message = Message.of( event, - KafkaTopicConfig.TOPIC_PAYMENTS, + KafkaTopicRegistry.PAYMENTS, event.userId() // Use user ID as partition key ); diff --git a/src/main/java/com/xtraction/api/integration/notification/config/NotificationConfig.java b/src/main/java/com/xtraction/api/integration/notification/config/NotificationConfig.java index 2de067d..3397497 100644 --- a/src/main/java/com/xtraction/api/integration/notification/config/NotificationConfig.java +++ b/src/main/java/com/xtraction/api/integration/notification/config/NotificationConfig.java @@ -50,5 +50,5 @@ public class NotificationConfig { /** * Kafka topic for notification events. */ - private String kafkaTopic = "notification-events"; + private String kafkaTopic = "xtraction-notifications"; } diff --git a/src/main/java/com/xtraction/api/integration/notification/kafka/NotificationKafkaConsumer.java b/src/main/java/com/xtraction/api/integration/notification/kafka/NotificationKafkaConsumer.java index 510e692..97d7d64 100644 --- a/src/main/java/com/xtraction/api/integration/notification/kafka/NotificationKafkaConsumer.java +++ b/src/main/java/com/xtraction/api/integration/notification/kafka/NotificationKafkaConsumer.java @@ -1,5 +1,6 @@ package com.xtraction.api.integration.notification.kafka; +import com.xtraction.api.core.kafka.KafkaTopicRegistry; import com.xtraction.api.integration.notification.config.NotificationConfig; import com.xtraction.api.integration.notification.datamodel.NotificationProviderType; import com.xtraction.api.integration.notification.interfaces.DeviceTokenService; @@ -68,7 +69,7 @@ public NotificationKafkaConsumer( } } - @KafkaListener(topics = "${notification.kafka-topic:notification-events}", groupId = "notification-processor", containerFactory = "kafkaListenerContainerFactory") + @KafkaListener(topics = KafkaTopicRegistry.NOTIFICATIONS, groupId = "notification-processor", containerFactory = "kafkaListenerContainerFactory") public void handleNotificationEvent(NotificationEvent event) { log.debug("Received notification event for user {}: {}", event.getUserId(), event.getType()); diff --git a/src/main/resources/application-example.properties b/src/main/resources/application-example.properties index 0b55d88..44b791f 100644 --- a/src/main/resources/application-example.properties +++ b/src/main/resources/application-example.properties @@ -179,7 +179,7 @@ notification.persist-notifications=${NOTIFICATION_PERSIST_NOTIFICATIONS:true} notification.respect-quiet-hours=${NOTIFICATION_RESPECT_QUIET_HOURS:true} notification.max-devices-per-user=${NOTIFICATION_MAX_DEVICES_PER_USER:10} notification.notification-retention-days=${NOTIFICATION_RETENTION_DAYS:90} -notification.kafka-topic=${NOTIFICATION_KAFKA_TOPIC:notification-events} +notification.kafka-topic=${NOTIFICATION_KAFKA_TOPIC:xtraction-notifications} notification.active-provider=${NOTIFICATION_ACTIVE_PROVIDER:FCM} # Firebase Configuration diff --git a/src/main/resources/db/migration/V63__add_oauth_fields_to_users.sql b/src/main/resources/db/migration/V63__add_oauth_fields_to_users.sql new file mode 100644 index 0000000..b2f92f9 --- /dev/null +++ b/src/main/resources/db/migration/V63__add_oauth_fields_to_users.sql @@ -0,0 +1,21 @@ +-- ============================================= +-- V63: Add OAuth provider fields to users table +-- ============================================= + +-- Make password nullable for OAuth users (who authenticate via provider) +ALTER TABLE users ALTER COLUMN password DROP NOT NULL; + +-- Make country nullable for OAuth users (frontend prompts for completion) +ALTER TABLE users ALTER COLUMN country DROP NOT NULL; + +-- Add OAuth provider tracking fields +ALTER TABLE users ADD COLUMN auth_provider VARCHAR(20) NOT NULL DEFAULT 'LOCAL'; +ALTER TABLE users ADD COLUMN provider_id VARCHAR(255); + +-- Add a flag to indicate if the user's profile is complete +ALTER TABLE users ADD COLUMN profile_complete BOOLEAN NOT NULL DEFAULT TRUE; + +-- Indexes for OAuth lookups +CREATE INDEX idx_users_auth_provider ON users(auth_provider); +CREATE UNIQUE INDEX idx_users_provider_unique ON users(auth_provider, provider_id) + WHERE provider_id IS NOT NULL; diff --git a/src/test/resources/application-test.properties b/src/test/resources/application-test.properties index 876316c..c752795 100644 --- a/src/test/resources/application-test.properties +++ b/src/test/resources/application-test.properties @@ -141,3 +141,7 @@ spring.autoconfigure.exclude=com.google.cloud.spring.autoconfigure.firestore.Gcp # Disable Google Vision OCR for tests ocr.google-vision.enabled=false +# Google OAuth2 Configuration for tests +spring.security.oauth2.client.registration.google.client-id=test-google-client-id +spring.security.oauth2.client.registration.google.client-secret=test-google-client-secret +