From d8e2a13f50b39f01739339a340f0099e5ec418fa Mon Sep 17 00:00:00 2001 From: aniebietafia Date: Mon, 6 Jul 2026 13:01:55 +0100 Subject: [PATCH 1/3] feat: implement global response advice and refine repository workflows - Add GlobalResponseBodyAdvice to automatically wrap REST API success responses in the standard ApiResponse envelope. - Refactor CurrencyController to return raw DTOs directly, removing manual wrapping boilerplate. - Add @Order(Ordered.HIGHEST_PRECEDENCE) to global exception advisers to override Spring's default ProblemDetailsExceptionHandler. - Remove redundant @ResponseStatus annotations from exception handler methods returning ResponseEntity. - Add structured pull_request_template.md and configure domain boundaries in CODEOWNERS. - Refactor release.yml to use robust SemVer tag sorting. Signed-off-by: aniebietafia --- .github/CODEOWNERS | 31 ++++ .github/pull_request_template.md | 36 ++++ .github/workflows/release.yml | 18 +- .github/workflows/security.yml | 88 ---------- .../PayPalGlobalExceptionHandler.java | 3 +- .../PaystackGlobalExceptionHandler.java | 3 + .../controller/CurrencyController.java | 25 +-- .../global/GlobalExceptionHandler.java | 24 +-- .../web/response/BypassResponseWrapping.java | 14 ++ .../response/GlobalResponseBodyAdvice.java | 166 ++++++++++++++++++ .../GlobalResponseBodyAdviceTest.java | 99 +++++++++++ 11 files changed, 376 insertions(+), 131 deletions(-) create mode 100644 .github/CODEOWNERS create mode 100644 .github/pull_request_template.md delete mode 100644 .github/workflows/security.yml create mode 100644 src/main/java/com/xtraction/api/core/web/response/BypassResponseWrapping.java create mode 100644 src/main/java/com/xtraction/api/core/web/response/GlobalResponseBodyAdvice.java create mode 100644 src/test/java/com/xtraction/api/shared/response/GlobalResponseBodyAdviceTest.java diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS new file mode 100644 index 0000000..b395800 --- /dev/null +++ b/.github/CODEOWNERS @@ -0,0 +1,31 @@ +# ============================================================================== +# CODEOWNERS Configuration +# ============================================================================== +# This file automatically requests reviews from the code owners when files are +# modified. Patterns are evaluated in order; the last matching pattern takes +# precedence. +# ============================================================================== + +# Default owner for the entire repository +* @aniebietafia + +# CI/CD & GitHub Configurations +/.github/workflows/ @aniebietafia +/pom.xml @aniebietafia + +# Core Application Framework & Security Configuration +/src/main/java/com/xtraction/api/core/ @aniebietafia +/src/main/resources/*.properties @aniebietafia +/src/main/resources/*.json @aniebietafia + +# Identity, Authentication & User Management +/src/main/java/com/xtraction/api/identity/ @aniebietafia + +# Extraction, OCR Parsing & Document Core +/src/main/java/com/xtraction/api/extraction/ @aniebietafia + +# Billing, Credits & Payment Integrations (PayPal, Paystack) +/src/main/java/com/xtraction/api/billing/ @aniebietafia + +# Third-party Integrations (Messaging, Storage, WebSockets) +/src/main/java/com/xtraction/api/integration/ @aniebietafia \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md new file mode 100644 index 0000000..b7a5ee5 --- /dev/null +++ b/.github/pull_request_template.md @@ -0,0 +1,36 @@ +## Description + +Please include a summary of the changes and the related issue/feature request. List any dependencies that are required for this change. + +Fixes # (issue) + +## Type of Change + +Please mark options that apply: + +- [ ] Bug fix (non-breaking change which fixes an issue) +- [ ] New feature (non-breaking change which adds functionality) +- [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) +- [ ] Refactoring (code cleanup, formatting, or performance optimizations with no behavior changes) +- [ ] Documentation update +- [ ] Chore / Maintenance (dependencies update, CI config, etc.) + +## Verification Details + +### Automated Tests +Describe the tests that you ran to verify your changes (e.g. `mvn test`). +- [ ] Unit Tests +- [ ] Integration Tests + +### Manual Verification +Describe any manual testing performed (e.g. API requests tested via Postman/Bruno, console output logs, database verification). + +## Checklist + +- [ ] My code follows the style guidelines of this project +- [ ] I have performed a self-review of my own code +- [ ] I have commented my code, particularly in hard-to-understand areas +- [ ] My changes generate no new compiler warnings +- [ ] I have added tests that prove my fix is effective or that my feature works +- [ ] New and existing unit tests pass locally with my changes +- [ ] Any dependent changes have been merged and published in downstream modules diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 408b819..03ef098 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -45,12 +45,12 @@ jobs: - name: Determine version bump from commits id: version_info run: | - LAST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "") + LAST_TAG=$(git tag --sort=-v:refname | head -n 1 || echo "") if [ -z "$LAST_TAG" ]; then - COMMITS=$(git log --pretty=format:"%s" --no-merges) + COMMITS=$(git log --pretty=format:"%s" --no-merges || echo "") else - COMMITS=$(git log $LAST_TAG..HEAD --pretty=format:"%s" --no-merges) + COMMITS=$(git log "$LAST_TAG..HEAD" --pretty=format:"%s" --no-merges || echo "") fi echo "Commits to analyze:" @@ -130,9 +130,15 @@ jobs: run: | set -e git fetch --tags - LATEST_TAG=$(git describe --tags --abbrev=0 HEAD~1^) || LATEST_TAG=$(git rev-list --max-parents=0 HEAD) - echo "LATEST_TAG=$LATEST_TAG" >> $GITHUB_ENV - CHANGELOG=$(git log $LATEST_TAG..HEAD^ --pretty=format:"* %s") + PREV_TAG=$(git tag --sort=-v:refname | sed -n '2p' || echo "") + echo "PREV_TAG=$PREV_TAG" + if [ -z "$PREV_TAG" ]; then + CHANGELOG=$(git log HEAD~1 --pretty=format:"* %s" --no-merges || echo "First release") + else + CHANGELOG=$(git log "$PREV_TAG..HEAD~1" --pretty=format:"* %s" --no-merges || echo "No changes found") + fi + echo "Generated changelog:" + echo "$CHANGELOG" echo "$CHANGELOG" > changelog.txt - name: Create GitHub Release diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml deleted file mode 100644 index e238a94..0000000 --- a/.github/workflows/security.yml +++ /dev/null @@ -1,88 +0,0 @@ -name: CodeQL - -on: - push: - branches: [ dev, main, github-actions ] - pull_request: - branches: [ main ] - schedule: - - cron: '30 1 * * 0' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - timeout-minutes: 60 - permissions: - actions: read - contents: read - security-events: write - issues: write - pull-requests: write - - strategy: - fail-fast: false - matrix: - language: [ 'java' ] - - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Set up JDK - if: ${{ matrix.language == 'java' }} - uses: actions/setup-java@v4 - with: - java-version: '25' - distribution: 'temurin' - - - name: Cache Maven packages - if: ${{ matrix.language == 'java' }} - uses: actions/cache@v3 - with: - path: ~/.m2 - key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} - restore-keys: ${{ runner.os }}-m2 - - - name: Initialize CodeQL - uses: github/codeql-action/init@v3 - with: - languages: ${{ matrix.language }} - queries: security-extended,security-and-quality - - - name: Autobuild - if: ${{ matrix.language == 'java' }} - uses: github/codeql-action/autobuild@v3 - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v3 - with: - category: "/language:${{matrix.language}}" - - - name: Notify on failure - if: failure() && github.event.pull_request.head.repo.full_name == github.repository - uses: actions/github-script@v7 - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - script: | - const issue = context.payload.pull_request - ? context.payload.pull_request.number - : (context.payload.issue ? context.payload.issue.number : null); - - if (issue) { - github.rest.issues.createComment({ - issue_number: issue, - owner: context.repo.owner, - repo: context.repo.repo, - body: '⚠️ CodeQL security scan failed. Please check the workflow logs.' - }); - } else { - console.log('No issue or PR number found, skipping comment creation'); - } - - - name: Upload CodeQL results - if: success() || failure() # Continue even if previous steps fail - run: | - # Only attempt upload if Advanced Security is available - # The upload step will be skipped gracefully - echo "Attempting to upload CodeQL results..." \ No newline at end of file diff --git a/src/main/java/com/xtraction/api/billing/payment/paypal/exception/PayPalGlobalExceptionHandler.java b/src/main/java/com/xtraction/api/billing/payment/paypal/exception/PayPalGlobalExceptionHandler.java index 6042c27..bb46cb6 100644 --- a/src/main/java/com/xtraction/api/billing/payment/paypal/exception/PayPalGlobalExceptionHandler.java +++ b/src/main/java/com/xtraction/api/billing/payment/paypal/exception/PayPalGlobalExceptionHandler.java @@ -4,6 +4,7 @@ import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; +import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; @@ -21,7 +22,7 @@ * Global exception handler for PayPal payment operations. */ @Slf4j -@Order(1) +@Order(Ordered.HIGHEST_PRECEDENCE) @RestControllerAdvice(basePackages = "com.xtraction.api.billing.payment.paypal") public class PayPalGlobalExceptionHandler { diff --git a/src/main/java/com/xtraction/api/billing/payment/paystack/exception/PaystackGlobalExceptionHandler.java b/src/main/java/com/xtraction/api/billing/payment/paystack/exception/PaystackGlobalExceptionHandler.java index 0759c7a..1360cd9 100644 --- a/src/main/java/com/xtraction/api/billing/payment/paystack/exception/PaystackGlobalExceptionHandler.java +++ b/src/main/java/com/xtraction/api/billing/payment/paystack/exception/PaystackGlobalExceptionHandler.java @@ -4,6 +4,8 @@ import lombok.extern.slf4j.Slf4j; import org.slf4j.MDC; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ProblemDetail; @@ -23,6 +25,7 @@ * Global exception handler for Paystack-related operations */ @Slf4j +@Order(Ordered.HIGHEST_PRECEDENCE) @RestControllerAdvice(basePackages = "com.xtraction.api.billing.payment.paystack") public class PaystackGlobalExceptionHandler { diff --git a/src/main/java/com/xtraction/api/billing/subscription/controller/CurrencyController.java b/src/main/java/com/xtraction/api/billing/subscription/controller/CurrencyController.java index f5ac82d..8c8e707 100644 --- a/src/main/java/com/xtraction/api/billing/subscription/controller/CurrencyController.java +++ b/src/main/java/com/xtraction/api/billing/subscription/controller/CurrencyController.java @@ -1,16 +1,11 @@ package com.xtraction.api.billing.subscription.controller; -import com.xtraction.api.core.web.response.ApiResponse; - -import com.xtraction.api.core.web.response.ResponseBuilderService; import com.xtraction.api.billing.subscription.datamodel.SubscriptionCurrency; import com.xtraction.api.billing.subscription.dto.ConvertedPrice; import com.xtraction.api.billing.subscription.service.CurrencyConversionService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; -import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.math.BigDecimal; @@ -29,13 +24,12 @@ public class CurrencyController { private final CurrencyConversionService currencyConversionService; - private final ResponseBuilderService responseBuilderService; @Operation(summary = "Convert an amount between currencies", description = "Converts an amount from one currency to another using cached exchange rates. " + "Amount should be in the smallest unit (e.g., cents for USD, kobo for NGN).") @GetMapping("/convert") - public ResponseEntity> convert( + public ConvertedPrice convert( @RequestParam long amountInCents, @RequestParam(defaultValue = "USD") String from, @RequestParam String to) { @@ -43,7 +37,7 @@ public ResponseEntity> convert( SubscriptionCurrency fromCurrency = SubscriptionCurrency.fromIdentifier(from); SubscriptionCurrency toCurrency = SubscriptionCurrency.fromIdentifier(to); - // Convert cents to main unit (e.g., 500 cents → $5.00) + // Convert cents to main unit (e.g., 500 cents -> $5.00) BigDecimal amountInMainUnit = BigDecimal.valueOf(amountInCents) .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP); @@ -57,15 +51,12 @@ public ResponseEntity> convert( } // Convert from USD to target currency - ConvertedPrice result = currencyConversionService.convert(amountInUsd, toCurrency); - - return ResponseEntity.ok( - responseBuilderService.buildUserResponse(result, HttpStatus.OK, "Currency converted")); + return currencyConversionService.convert(amountInUsd, toCurrency); } @Operation(summary = "Get exchange rates", description = "Returns exchange rates for all supported currencies relative to USD") @GetMapping("/rates") - public ResponseEntity>> getRates() { + public Map getRates() { Map ratesData = new LinkedHashMap<>(); ratesData.put("baseCurrency", "USD"); @@ -75,13 +66,12 @@ public ResponseEntity>> getRates() { } ratesData.put("rates", rates); - return ResponseEntity.ok( - responseBuilderService.buildUserResponse(ratesData, HttpStatus.OK, "Exchange rates retrieved")); + return ratesData; } @Operation(summary = "List supported currencies", description = "Returns all supported currencies with their codes, symbols, and names") @GetMapping("/supported") - public ResponseEntity[]>> getSupportedCurrencies() { + public Map[] getSupportedCurrencies() { @SuppressWarnings("unchecked") Map[] currencies = new Map[SubscriptionCurrency.values().length]; int i = 0; @@ -93,7 +83,6 @@ public ResponseEntity[]>> getSupportedCurrencies currencies[i++] = entry; } - return ResponseEntity.ok( - responseBuilderService.buildUserResponse(currencies, HttpStatus.OK, "Supported currencies retrieved")); + return currencies; } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/global/GlobalExceptionHandler.java b/src/main/java/com/xtraction/api/core/exceptions/global/GlobalExceptionHandler.java index e727de9..8445547 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/global/GlobalExceptionHandler.java +++ b/src/main/java/com/xtraction/api/core/exceptions/global/GlobalExceptionHandler.java @@ -5,18 +5,17 @@ import com.xtraction.api.billing.promocode.exception.InvalidPromoCodeException; import com.xtraction.api.core.exceptions.custom.*; -import jakarta.servlet.http.HttpServletRequest; import org.slf4j.MDC; +import org.springframework.core.Ordered; +import org.springframework.core.annotation.Order; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ProblemDetail; import org.springframework.http.ResponseEntity; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.security.authorization.AuthorizationDeniedException; -import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @@ -26,6 +25,7 @@ import java.time.Instant; import java.util.List; +@Order(Ordered.HIGHEST_PRECEDENCE) @RestControllerAdvice public class GlobalExceptionHandler { @@ -121,7 +121,9 @@ public ResponseEntity handleValidationExceptions(MethodArgumentNotValidE .stream() .map(fieldError -> new ApiResponse.ValidationError( fieldError.getField(), - fieldError.getField().toLowerCase().contains("password") ? "[MASKED]" : fieldError.getRejectedValue(), + fieldError.getField().toLowerCase().contains("password") + ? "[MASKED]" + : fieldError.getRejectedValue(), fieldError.getDefaultMessage() )) .toList(); @@ -130,74 +132,62 @@ public ResponseEntity handleValidationExceptions(MethodArgumentNotValidE } @ExceptionHandler(NotFoundException.class) - @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseEntity handleNotFoundException(NotFoundException ex) { return buildErrorResponse(HttpStatus.NOT_FOUND, ex.getMessage(), null, null); } @ExceptionHandler(ConflictException.class) - @ResponseStatus(HttpStatus.CONFLICT) public ResponseEntity handleConflictException(ConflictException ex) { return buildErrorResponse(HttpStatus.CONFLICT, ex.getMessage(), null, null); } @ExceptionHandler(ForbiddenException.class) - @ResponseStatus(HttpStatus.FORBIDDEN) public ResponseEntity handleForbiddenException(ForbiddenException ex) { return buildErrorResponse(HttpStatus.FORBIDDEN, ex.getMessage(), ex.getErrorCode(), null); } @ExceptionHandler(BadRequestException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity handleBadRequestException(BadRequestException ex) { return buildErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage(), ex.getErrorCode(), null); } @ExceptionHandler(InvalidPromoCodeException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity handleInvalidPromoCodeException(InvalidPromoCodeException ex) { return buildErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage(), "INVALID_PROMO_CODE", null); } @ExceptionHandler(PromoCodeNotFoundException.class) - @ResponseStatus(HttpStatus.NOT_FOUND) public ResponseEntity handlePromoCodeNotFoundException(PromoCodeNotFoundException ex) { return buildErrorResponse(HttpStatus.NOT_FOUND, ex.getMessage(), "PROMO_CODE_NOT_FOUND", null); } @ExceptionHandler(UnauthorizedException.class) - @ResponseStatus(HttpStatus.UNAUTHORIZED) public ResponseEntity handleUnauthorizedException(UnauthorizedException ex) { return buildErrorResponse(HttpStatus.UNAUTHORIZED, ex.getMessage(), ex.getErrorCode(), null); } @ExceptionHandler(JwtAuthenticationException.class) - @ResponseStatus(HttpStatus.UNAUTHORIZED) public ResponseEntity handleJwtAuthenticationException(JwtAuthenticationException ex) { return buildErrorResponse(HttpStatus.UNAUTHORIZED, ex.getMessage(), "JWT_AUTHENTICATION_ERROR", null); } @ExceptionHandler(TokenProcessingException.class) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ResponseEntity handleTokenProcessingException(TokenProcessingException ex) { return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), "TOKEN_PROCESSING_ERROR", null); } @ExceptionHandler(MaxUploadSizeExceededException.class) - @ResponseStatus(HttpStatus.CONTENT_TOO_LARGE) public ResponseEntity handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) { String message = ex.getMessage() != null ? ex.getMessage() + " (Max size: 10MB)" : "Maximum upload size exceeded."; return buildErrorResponse(HttpStatus.CONTENT_TOO_LARGE, message, "MAX_UPLOAD_SIZE_EXCEEDED", null); } @ExceptionHandler(TooManyRequestsException.class) - @ResponseStatus(HttpStatus.TOO_MANY_REQUESTS) public ResponseEntity handleTooManyRequestsException(TooManyRequestsException ex) { return buildErrorResponse(HttpStatus.TOO_MANY_REQUESTS, ex.getMessage(), "TOO_MANY_REQUESTS", null); } @ExceptionHandler(HttpMessageNotReadableException.class) - @ResponseStatus(HttpStatus.BAD_REQUEST) public ResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) { String message = "Invalid request payload."; Throwable cause = ex.getCause(); @@ -208,13 +198,11 @@ public ResponseEntity handleHttpMessageNotReadableException(HttpMessageN } @ExceptionHandler(Exception.class) - @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) public ResponseEntity handleGenericException(Exception ex) { return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), "INTERNAL_SERVER_ERROR", null); } @ExceptionHandler(AuthorizationDeniedException.class) - @ResponseStatus(HttpStatus.FORBIDDEN) public ResponseEntity handleAuthorizationDeniedException(AuthorizationDeniedException ex) { return buildErrorResponse(HttpStatus.FORBIDDEN, ex.getMessage(), "AUTHORIZATION_DENIED", null); } diff --git a/src/main/java/com/xtraction/api/core/web/response/BypassResponseWrapping.java b/src/main/java/com/xtraction/api/core/web/response/BypassResponseWrapping.java new file mode 100644 index 0000000..5b6ce8a --- /dev/null +++ b/src/main/java/com/xtraction/api/core/web/response/BypassResponseWrapping.java @@ -0,0 +1,14 @@ +package com.xtraction.api.core.web.response; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Annotation to bypass the automatic response wrapping done by GlobalResponseBodyAdvice. + */ +@Target({ElementType.METHOD, ElementType.TYPE}) +@Retention(RetentionPolicy.RUNTIME) +public @interface BypassResponseWrapping { +} diff --git a/src/main/java/com/xtraction/api/core/web/response/GlobalResponseBodyAdvice.java b/src/main/java/com/xtraction/api/core/web/response/GlobalResponseBodyAdvice.java new file mode 100644 index 0000000..7f9ed11 --- /dev/null +++ b/src/main/java/com/xtraction/api/core/web/response/GlobalResponseBodyAdvice.java @@ -0,0 +1,166 @@ +package com.xtraction.api.core.web.response; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; + +import org.jspecify.annotations.NonNull; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.MethodParameter; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ProblemDetail; +import org.springframework.http.ResponseEntity; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.server.ServerHttpRequest; +import org.springframework.http.server.ServerHttpResponse; +import org.springframework.http.server.ServletServerHttpResponse; +import org.springframework.web.bind.annotation.RestControllerAdvice; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice; + +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.time.Instant; + +/** + * Global response body advice that automatically wraps all successful REST API payloads + * in the standardized ApiResponse envelope. + */ +@RestControllerAdvice(basePackages = "com.xtraction.api") +public class GlobalResponseBodyAdvice implements ResponseBodyAdvice { + + private final ObjectMapper objectMapper; + + public GlobalResponseBodyAdvice() { + this.objectMapper = new ObjectMapper().registerModule(new JavaTimeModule()); + } + + @Autowired + public GlobalResponseBodyAdvice(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + @Override + public boolean supports( + MethodParameter returnType, + @NonNull Class> converterType + ) { + Class type = returnType.getParameterType(); + if (type.equals(ApiResponse.class) || type.equals(Void.class) || type.equals(void.class)) { + return false; + } + + // Bypass if the controller class or method has @BypassResponseWrapping annotation + if (returnType.hasMethodAnnotation(BypassResponseWrapping.class) || + returnType.getDeclaringClass().isAnnotationPresent(BypassResponseWrapping.class)) { + return false; + } + + // Inspect ResponseEntity generic type to avoid wrapping if it is already ApiResponse + if (type.equals(ResponseEntity.class)) { + Type genericType = returnType.getGenericParameterType(); + if (genericType instanceof ParameterizedType paramType) { + Type[] actualTypeArguments = paramType.getActualTypeArguments(); + if (actualTypeArguments.length > 0) { + Type typeArg = actualTypeArguments[0]; + if (typeArg.equals(ApiResponse.class) || typeArg.toString().startsWith(ApiResponse.class.getName())) { + return false; + } + } + } + } + + // Ensure we only wrap API request paths + try { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes != null) { + String path = attributes.getRequest().getRequestURI(); + if (path == null || !path.contains("/api")) { + return false; + } + // Exclude specific file download API paths + if (path.contains("/download")) { + return false; + } + } + } catch (Exception e) { + // Ignore + } + + return true; + } + + @Override + public Object beforeBodyWrite( + Object body, + @NonNull MethodParameter returnType, + @NonNull MediaType selectedContentType, + @NonNull Class> selectedConverterType, + @NonNull ServerHttpRequest request, + @NonNull ServerHttpResponse response + ) { + if (body == null) { + return null; + } + + // Prevent double wrapping of ApiResponse or ProblemDetail at runtime + if (body instanceof ApiResponse || + body instanceof ProblemDetail || + body.getClass().getName().contains("ProblemDetail") + ) { + return body; + } + + // Prevent wrapping binary/stream resources + if (body instanceof org.springframework.core.io.Resource || + body instanceof byte[] || + body instanceof java.io.InputStream + ) { + return body; + } + + String path = request.getURI().getPath(); + + // Prevent wrapping actuator endpoints or Swagger/Docs endpoints + if (path != null && ( + path.startsWith("/docs") || + path.startsWith("/swagger-ui") || + path.startsWith("/v3/api-docs") || + path.startsWith("/actuator"))) { + return body; + } + + int status = HttpStatus.OK.value(); + if (response instanceof ServletServerHttpResponse servletResponse) { + status = servletResponse.getServletResponse().getStatus(); + } + + // Prevent casting exceptions for String bodies when converter is StringHttpMessageConverter + if (body instanceof String) { + try { + response.getHeaders().setContentType(MediaType.APPLICATION_JSON); + ApiResponse apiResponse = ApiResponse.builder() + .success(status >= 200 && status < 300) + .statusCode(status) + .message("Operation completed successfully") + .data(body) + .timestamp(Instant.now()) + .path(path) + .build(); + return objectMapper.writeValueAsString(apiResponse); + } catch (Exception e) { + return body; + } + } + + return ApiResponse.builder() + .success(status >= 200 && status < 300) + .statusCode(status) + .message("Operation completed successfully") + .data(body) + .timestamp(Instant.now()) + .path(path) + .build(); + } +} diff --git a/src/test/java/com/xtraction/api/shared/response/GlobalResponseBodyAdviceTest.java b/src/test/java/com/xtraction/api/shared/response/GlobalResponseBodyAdviceTest.java new file mode 100644 index 0000000..8f0decd --- /dev/null +++ b/src/test/java/com/xtraction/api/shared/response/GlobalResponseBodyAdviceTest.java @@ -0,0 +1,99 @@ +package com.xtraction.api.shared.response; + +import com.xtraction.api.core.web.response.ApiResponse; +import com.xtraction.api.core.web.response.BypassResponseWrapping; +import com.xtraction.api.core.web.response.GlobalResponseBodyAdvice; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Collections; +import java.util.Map; + +import static org.hamcrest.Matchers.is; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +class GlobalResponseBodyAdviceTest { + + private MockMvc mockMvc; + + @RestController + static class TestController { + @GetMapping("/api/test/raw-object") + public Map getRawObject() { + return Collections.singletonMap("key", "value"); + } + + @GetMapping("/api/test/already-wrapped") + public ApiResponse> getAlreadyWrapped() { + return ApiResponse.>builder() + .success(true) + .statusCode(200) + .message("Custom message") + .data(Collections.singletonMap("key", "value")) + .build(); + } + + @GetMapping("/api/test/bypass") + @BypassResponseWrapping + public Map getBypass() { + return Collections.singletonMap("key", "bypass-value"); + } + + @GetMapping("/api/test/raw-string") + public String getRawString() { + return "hello-world"; + } + } + + @BeforeEach + void setUp() { + mockMvc = MockMvcBuilders.standaloneSetup(new TestController()) + .setControllerAdvice(new GlobalResponseBodyAdvice()) + .build(); + } + + @Test + void whenRawObjectReturned_thenWrapInApiResponse() throws Exception { + mockMvc.perform(get("/api/test/raw-object")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success", is(true))) + .andExpect(jsonPath("$.statusCode", is(200))) + .andExpect(jsonPath("$.message", is("Operation completed successfully"))) + .andExpect(jsonPath("$.data.key", is("value"))) + .andExpect(jsonPath("$.path", is("/api/test/raw-object"))) + .andExpect(jsonPath("$.timestamp").exists()); + } + + @Test + void whenAlreadyWrappedReturned_thenDoNotWrapAgain() throws Exception { + mockMvc.perform(get("/api/test/already-wrapped")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success", is(true))) + .andExpect(jsonPath("$.statusCode", is(200))) + .andExpect(jsonPath("$.message", is("Custom message"))) + .andExpect(jsonPath("$.data.key", is("value"))) + .andExpect(jsonPath("$.path").doesNotExist()); + } + + @Test + void whenBypassAnnotationPresent_thenDoNotWrap() throws Exception { + mockMvc.perform(get("/api/test/bypass")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success").doesNotExist()) + .andExpect(jsonPath("$.key", is("bypass-value"))); + } + + @Test + void whenRawStringReturned_thenWrapAndSerializeAsString() throws Exception { + mockMvc.perform(get("/api/test/raw-string")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.success", is(true))) + .andExpect(jsonPath("$.statusCode", is(200))) + .andExpect(jsonPath("$.data", is("hello-world"))); + } +} From 2d1c5e78ed1f8579252585facd3b87e967041586 Mon Sep 17 00:00:00 2001 From: aniebietafia Date: Mon, 6 Jul 2026 14:00:51 +0100 Subject: [PATCH 2/3] refactor: centralize exception framework using ErrorCode enum - Update ErrorCode enum to define fallback system, authorization, and promo-code codes. - Refactor BusinessException to support getErrorCodeEnum() and getErrorCode() for backward compatibility. - Update custom exception classes to extend BusinessException. - Consolidate individual custom exception handlers in GlobalExceptionHandler into a single @ExceptionHandler(BusinessException.class). Signed-off-by: aniebietafia --- .../exception/InvalidPromoCodeException.java | 19 +++--- .../exception/PromoCodeNotFoundException.java | 9 ++- .../custom/BadRequestException.java | 14 ++--- .../exceptions/custom/BusinessException.java | 23 ++++++++ .../exceptions/custom/ConflictException.java | 4 +- .../api/core/exceptions/custom/ErrorCode.java | 46 +++++++++++++++ .../exceptions/custom/ForbiddenException.java | 14 ++--- .../custom/JwtAuthenticationException.java | 14 ++--- .../exceptions/custom/NotFoundException.java | 6 +- .../custom/TokenProcessingException.java | 4 +- .../custom/TooManyRequestsException.java | 4 +- .../custom/UnauthorizedException.java | 14 ++--- .../global/GlobalExceptionHandler.java | 59 +++---------------- .../auth/impl/EmailVerificationImpl.java | 15 ++--- .../api/identity/auth/impl/LoginUserImpl.java | 36 ++++++----- .../identity/auth/impl/RefreshTokenImpl.java | 22 ++++--- 16 files changed, 159 insertions(+), 144 deletions(-) create mode 100644 src/main/java/com/xtraction/api/core/exceptions/custom/BusinessException.java create mode 100644 src/main/java/com/xtraction/api/core/exceptions/custom/ErrorCode.java diff --git a/src/main/java/com/xtraction/api/billing/promocode/exception/InvalidPromoCodeException.java b/src/main/java/com/xtraction/api/billing/promocode/exception/InvalidPromoCodeException.java index 23c968c..bd7ee62 100644 --- a/src/main/java/com/xtraction/api/billing/promocode/exception/InvalidPromoCodeException.java +++ b/src/main/java/com/xtraction/api/billing/promocode/exception/InvalidPromoCodeException.java @@ -1,23 +1,18 @@ package com.xtraction.api.billing.promocode.exception; -import lombok.Getter; +import com.xtraction.api.core.exceptions.custom.BusinessException; +import com.xtraction.api.core.exceptions.custom.ErrorCode; /** * Exception thrown when a promo is invalid or cannot be used. */ -@Getter -public class InvalidPromoCodeException extends RuntimeException { - - private final String errorCode; - - public InvalidPromoCodeException(String message, String errorCode) { - super(message); - this.errorCode = errorCode; - } +public class InvalidPromoCodeException extends BusinessException { public InvalidPromoCodeException(String message) { - super(message); - this.errorCode = "INVALID_PROMO_CODE"; + super(ErrorCode.INVALID_PROMO_CODE, message); } + public InvalidPromoCodeException(ErrorCode errorCode, String message) { + super(errorCode, message); + } } diff --git a/src/main/java/com/xtraction/api/billing/promocode/exception/PromoCodeNotFoundException.java b/src/main/java/com/xtraction/api/billing/promocode/exception/PromoCodeNotFoundException.java index bd22b14..8fbc07d 100644 --- a/src/main/java/com/xtraction/api/billing/promocode/exception/PromoCodeNotFoundException.java +++ b/src/main/java/com/xtraction/api/billing/promocode/exception/PromoCodeNotFoundException.java @@ -1,16 +1,19 @@ package com.xtraction.api.billing.promocode.exception; +import com.xtraction.api.core.exceptions.custom.BusinessException; +import com.xtraction.api.core.exceptions.custom.ErrorCode; + /** * Exception thrown when a promo is not found. */ -public class PromoCodeNotFoundException extends RuntimeException { +public class PromoCodeNotFoundException extends BusinessException { public PromoCodeNotFoundException(String message) { - super(message); + super(ErrorCode.PROMO_CODE_NOT_FOUND, message); } public PromoCodeNotFoundException(String promoCode, boolean isCode) { - super(isCode ? "PromoCode with code '" + promoCode + "' not found" + super(ErrorCode.PROMO_CODE_NOT_FOUND, isCode ? "PromoCode with code '" + promoCode + "' not found" : "PromoCode with ID '" + promoCode + "' not found"); } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/BadRequestException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/BadRequestException.java index 5501db3..2435c35 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/BadRequestException.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/BadRequestException.java @@ -1,18 +1,12 @@ package com.xtraction.api.core.exceptions.custom; -import lombok.Getter; - -@Getter -public class BadRequestException extends RuntimeException { - private final String errorCode; +public class BadRequestException extends BusinessException { public BadRequestException(String message) { - super(message); - this.errorCode = null; + super(ErrorCode.BAD_REQUEST, message); } - public BadRequestException(String message, String errorCode) { - super(message); - this.errorCode = errorCode; + public BadRequestException(ErrorCode errorCode, String message) { + super(errorCode, message); } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/BusinessException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/BusinessException.java new file mode 100644 index 0000000..44a3a8f --- /dev/null +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/BusinessException.java @@ -0,0 +1,23 @@ +package com.xtraction.api.core.exceptions.custom; + +public abstract class BusinessException extends RuntimeException { + private final ErrorCode errorCode; + + protected BusinessException(ErrorCode errorCode) { + super(errorCode.getDefaultMessage()); + this.errorCode = errorCode; + } + + protected BusinessException(ErrorCode errorCode, String customMessage) { + super(customMessage); + this.errorCode = errorCode; + } + + public ErrorCode getErrorCodeEnum() { + return errorCode; + } + + public String getErrorCode() { + return errorCode.name(); + } +} diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/ConflictException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/ConflictException.java index bda2554..049b49d 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/ConflictException.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/ConflictException.java @@ -1,7 +1,7 @@ package com.xtraction.api.core.exceptions.custom; -public class ConflictException extends RuntimeException { +public class ConflictException extends BusinessException { public ConflictException(String message) { - super(message); + super(ErrorCode.RESOURCE_CONFLICT, message); } } 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 new file mode 100644 index 0000000..76327f3 --- /dev/null +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/ErrorCode.java @@ -0,0 +1,46 @@ +package com.xtraction.api.core.exceptions.custom; + +import lombok.Getter; +import org.springframework.http.HttpStatus; + +@Getter +public enum ErrorCode { + // Auth Errors + 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), + + // Resource Errors + RESOURCE_NOT_FOUND("RES_001", "Requested resource was not found", HttpStatus.NOT_FOUND), + RESOURCE_CONFLICT("RES_002", "Resource conflict occurred", HttpStatus.CONFLICT), + + // System Errors + 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), + INVALID_PROMO_CODE("PROMO_002", "Promo code is invalid", HttpStatus.BAD_REQUEST), + + // Verification & User Account Errors + VERIFICATION_FAILED("AUTH_006", "Email verification failed", HttpStatus.BAD_REQUEST), + EMAIL_ALREADY_VERIFIED("AUTH_007", "User is already verified", HttpStatus.BAD_REQUEST), + ACCOUNT_DEACTIVATED("AUTH_008", "Account has been deactivated", HttpStatus.BAD_REQUEST), + 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); + + private final String code; + private final String defaultMessage; + private final HttpStatus httpStatus; + + ErrorCode(String code, String defaultMessage, HttpStatus httpStatus) { + this.code = code; + this.defaultMessage = defaultMessage; + this.httpStatus = httpStatus; + } +} diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/ForbiddenException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/ForbiddenException.java index 3e2d479..eb1379a 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/ForbiddenException.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/ForbiddenException.java @@ -1,18 +1,12 @@ package com.xtraction.api.core.exceptions.custom; -import lombok.Getter; - -@Getter -public class ForbiddenException extends RuntimeException { - private final String errorCode; +public class ForbiddenException extends BusinessException { public ForbiddenException(String message) { - super(message); - this.errorCode = null; + super(ErrorCode.ACCESS_DENIED, message); } - public ForbiddenException(String message, String errorCode) { - super(message); - this.errorCode = errorCode; + public ForbiddenException(ErrorCode errorCode, String message) { + super(errorCode, message); } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/JwtAuthenticationException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/JwtAuthenticationException.java index 631f862..ee203d3 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/JwtAuthenticationException.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/JwtAuthenticationException.java @@ -1,14 +1,12 @@ package com.xtraction.api.core.exceptions.custom; -import lombok.Getter; +public class JwtAuthenticationException extends BusinessException { -@Getter -public class JwtAuthenticationException extends RuntimeException { - private final String errorCode; - - public JwtAuthenticationException(String message, String errorCode) { - super(message); - this.errorCode = errorCode; + public JwtAuthenticationException(String message) { + super(ErrorCode.UNAUTHORIZED, message); } + public JwtAuthenticationException(ErrorCode errorCode, String message) { + super(errorCode, message); + } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/NotFoundException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/NotFoundException.java index 8a2b043..3265227 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/NotFoundException.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/NotFoundException.java @@ -1,7 +1,7 @@ package com.xtraction.api.core.exceptions.custom; -public class NotFoundException extends RuntimeException{ - public NotFoundException(String message){ - super(message); +public class NotFoundException extends BusinessException { + public NotFoundException(String message) { + super(ErrorCode.RESOURCE_NOT_FOUND, message); } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/TokenProcessingException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/TokenProcessingException.java index 2a28b4f..e3a3c30 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/TokenProcessingException.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/TokenProcessingException.java @@ -1,7 +1,7 @@ package com.xtraction.api.core.exceptions.custom; -public class TokenProcessingException extends RuntimeException { +public class TokenProcessingException extends BusinessException { public TokenProcessingException(String message) { - super(message); + super(ErrorCode.INTERNAL_SERVER_ERROR, message); } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/TooManyRequestsException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/TooManyRequestsException.java index e1ff694..5f1e07a 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/TooManyRequestsException.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/TooManyRequestsException.java @@ -1,7 +1,7 @@ package com.xtraction.api.core.exceptions.custom; -public class TooManyRequestsException extends RuntimeException { +public class TooManyRequestsException extends BusinessException { public TooManyRequestsException(String message) { - super(message); + super(ErrorCode.RATE_LIMIT_EXCEEDED, message); } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/custom/UnauthorizedException.java b/src/main/java/com/xtraction/api/core/exceptions/custom/UnauthorizedException.java index f78a040..183b905 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/custom/UnauthorizedException.java +++ b/src/main/java/com/xtraction/api/core/exceptions/custom/UnauthorizedException.java @@ -1,18 +1,12 @@ package com.xtraction.api.core.exceptions.custom; -import lombok.Getter; - -@Getter -public class UnauthorizedException extends RuntimeException { - private final String errorCode; +public class UnauthorizedException extends BusinessException { public UnauthorizedException(String message) { - super(message); - this.errorCode = null; + super(ErrorCode.UNAUTHORIZED, message); } - public UnauthorizedException(String message, String errorCode) { - super(message); - this.errorCode = errorCode; + public UnauthorizedException(ErrorCode errorCode, String message) { + super(errorCode, message); } } diff --git a/src/main/java/com/xtraction/api/core/exceptions/global/GlobalExceptionHandler.java b/src/main/java/com/xtraction/api/core/exceptions/global/GlobalExceptionHandler.java index 8445547..2b45583 100644 --- a/src/main/java/com/xtraction/api/core/exceptions/global/GlobalExceptionHandler.java +++ b/src/main/java/com/xtraction/api/core/exceptions/global/GlobalExceptionHandler.java @@ -1,8 +1,6 @@ package com.xtraction.api.core.exceptions.global; import com.xtraction.api.core.web.response.ApiResponse; -import com.xtraction.api.billing.promocode.exception.PromoCodeNotFoundException; -import com.xtraction.api.billing.promocode.exception.InvalidPromoCodeException; import com.xtraction.api.core.exceptions.custom.*; import org.slf4j.MDC; @@ -131,49 +129,15 @@ public ResponseEntity handleValidationExceptions(MethodArgumentNotValidE return buildErrorResponse(HttpStatus.BAD_REQUEST, "Validation failed", "VALIDATION_ERROR", validationErrors); } - @ExceptionHandler(NotFoundException.class) - public ResponseEntity handleNotFoundException(NotFoundException ex) { - return buildErrorResponse(HttpStatus.NOT_FOUND, ex.getMessage(), null, null); - } - - @ExceptionHandler(ConflictException.class) - public ResponseEntity handleConflictException(ConflictException ex) { - return buildErrorResponse(HttpStatus.CONFLICT, ex.getMessage(), null, null); - } - - @ExceptionHandler(ForbiddenException.class) - public ResponseEntity handleForbiddenException(ForbiddenException ex) { - return buildErrorResponse(HttpStatus.FORBIDDEN, ex.getMessage(), ex.getErrorCode(), null); - } - - @ExceptionHandler(BadRequestException.class) - public ResponseEntity handleBadRequestException(BadRequestException ex) { - return buildErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage(), ex.getErrorCode(), null); - } - - @ExceptionHandler(InvalidPromoCodeException.class) - public ResponseEntity handleInvalidPromoCodeException(InvalidPromoCodeException ex) { - return buildErrorResponse(HttpStatus.BAD_REQUEST, ex.getMessage(), "INVALID_PROMO_CODE", null); - } - - @ExceptionHandler(PromoCodeNotFoundException.class) - public ResponseEntity handlePromoCodeNotFoundException(PromoCodeNotFoundException ex) { - return buildErrorResponse(HttpStatus.NOT_FOUND, ex.getMessage(), "PROMO_CODE_NOT_FOUND", null); - } - - @ExceptionHandler(UnauthorizedException.class) - public ResponseEntity handleUnauthorizedException(UnauthorizedException ex) { - return buildErrorResponse(HttpStatus.UNAUTHORIZED, ex.getMessage(), ex.getErrorCode(), null); - } - - @ExceptionHandler(JwtAuthenticationException.class) - public ResponseEntity handleJwtAuthenticationException(JwtAuthenticationException ex) { - return buildErrorResponse(HttpStatus.UNAUTHORIZED, ex.getMessage(), "JWT_AUTHENTICATION_ERROR", null); - } - - @ExceptionHandler(TokenProcessingException.class) - public ResponseEntity handleTokenProcessingException(TokenProcessingException ex) { - return buildErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), "TOKEN_PROCESSING_ERROR", null); + @ExceptionHandler(BusinessException.class) + public ResponseEntity handleBusinessException(BusinessException ex) { + ErrorCode errorCode = ex.getErrorCodeEnum(); + return buildErrorResponse( + errorCode.getHttpStatus(), + ex.getMessage(), + errorCode.getCode(), + null + ); } @ExceptionHandler(MaxUploadSizeExceededException.class) @@ -182,11 +146,6 @@ public ResponseEntity handleMaxUploadSizeExceededException(MaxUploadSize return buildErrorResponse(HttpStatus.CONTENT_TOO_LARGE, message, "MAX_UPLOAD_SIZE_EXCEEDED", null); } - @ExceptionHandler(TooManyRequestsException.class) - public ResponseEntity handleTooManyRequestsException(TooManyRequestsException ex) { - return buildErrorResponse(HttpStatus.TOO_MANY_REQUESTS, ex.getMessage(), "TOO_MANY_REQUESTS", null); - } - @ExceptionHandler(HttpMessageNotReadableException.class) public ResponseEntity handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) { String message = "Invalid request payload."; diff --git a/src/main/java/com/xtraction/api/identity/auth/impl/EmailVerificationImpl.java b/src/main/java/com/xtraction/api/identity/auth/impl/EmailVerificationImpl.java index 5336853..be362b8 100644 --- a/src/main/java/com/xtraction/api/identity/auth/impl/EmailVerificationImpl.java +++ b/src/main/java/com/xtraction/api/identity/auth/impl/EmailVerificationImpl.java @@ -13,6 +13,7 @@ import com.xtraction.api.integration.broker.kafka.events.EventPublisherService; import com.xtraction.api.integration.broker.kafka.events.EventTypes; import com.xtraction.api.core.exceptions.custom.BadRequestException; +import com.xtraction.api.core.exceptions.custom.ErrorCode; import com.xtraction.api.identity.user.model.User; import com.xtraction.api.identity.user.repository.UserRepository; import com.xtraction.api.core.web.response.ResponseBuilderService; @@ -45,25 +46,21 @@ public class EmailVerificationImpl implements EmailVerificationService { @Override @Transactional public ApiResponse resendEmailVerification(ResendEmailVerificationDto request) { - // Issue #3: Prevent user enumeration — always return generic 200 OK Optional userOpt = userRepository.findByEmail(request.email()); if (userOpt.isEmpty()) { - // User not found — return generic success to prevent enumeration return responseBuilder.buildUserResponse(null, HttpStatus.OK, RESEND_GENERIC_MESSAGE); } User user = userOpt.get(); if (user.isVerified()) { - // Already verified — return generic success to prevent enumeration return responseBuilder.buildUserResponse(null, HttpStatus.OK, RESEND_GENERIC_MESSAGE); } UserVerification userVerification = user.getUserVerification(); OffsetDateTime now = OffsetDateTime.now(); - // Issue #5: Do not leak token TTL — return generic message if (userVerification.getEmailVerificationToken() != null && userVerification.getEmailVerificationTokenExpiry().isAfter(now)) { return responseBuilder.buildUserResponse( @@ -113,29 +110,27 @@ private void publishVerificationEmailEvent(User user, String token, String expir @Override @Transactional public ApiResponse verifyEmail(String email, String token) { - // Issue #3: Use generic error for all failure cases — no 404 to prevent - // enumeration User user = userRepository.findByEmail(email) .orElseThrow(() -> new BadRequestException( - "Email verification failed.", "VERIFICATION_FAILED")); + ErrorCode.VERIFICATION_FAILED, "Email verification failed.")); if (user.isVerified()) { throw new BadRequestException( - "User is already verified. Please login.", "EMAIL_ALREADY_VERIFIED"); + ErrorCode.EMAIL_ALREADY_VERIFIED, "User is already verified. Please login."); } UserVerification userVerification = user.getUserVerification(); if (userVerification.getEmailVerificationToken() == null || !userVerification.getEmailVerificationToken().equals(token)) { throw new BadRequestException( - "Email verification failed.", "VERIFICATION_FAILED"); + ErrorCode.VERIFICATION_FAILED, "Email verification failed."); } if (userVerification.getEmailVerificationTokenExpiry().isBefore(OffsetDateTime.now())) { userVerification.setStatus(VerifiedStatus.EXPIRED); userRepository.save(user); throw new BadRequestException( - "Email verification token has expired.", "TOKEN_EXPIRED"); + ErrorCode.TOKEN_EXPIRED, "Email verification token has expired."); } userVerification.setEmailVerificationToken(null); 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 7a971df..d322f77 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.core.utils.logging.SanitizeLogging; import com.xtraction.api.core.web.response.ApiResponse; import com.xtraction.api.identity.auth.dto.LoginData; @@ -7,6 +8,7 @@ import com.xtraction.api.identity.auth.dto.request.LoginRequestDto; import com.xtraction.api.identity.auth.interfaces.LoginUserService; import com.xtraction.api.core.exceptions.custom.BadRequestException; +import com.xtraction.api.core.exceptions.custom.ErrorCode; import com.xtraction.api.core.exceptions.custom.ForbiddenException; import com.xtraction.api.core.exceptions.custom.TokenProcessingException; import com.xtraction.api.core.exceptions.custom.UnauthorizedException; @@ -37,17 +39,18 @@ public class LoginUserImpl implements LoginUserService { private final ResponseBuilderService responseBuilder; private final UserRepository userRepository; private final RefreshTokenService refreshTokenService; + private final SanitizeLogging sanitizer; @Override public LoginResult loginUser(LoginRequestDto request) { Optional userOpt = userRepository.findByEmail(request.email()); - // Block login for soft-deleted accounts (Issue #2) + // Block login for soft-deleted accounts userOpt.ifPresent(user -> { if (user.getDeletedAt() != null) { throw new BadRequestException( - "This account has been deactivated. Please contact support.", - "ACCOUNT_DEACTIVATED"); + ErrorCode.ACCOUNT_DEACTIVATED, + "This account has been deactivated. Please contact support."); } }); @@ -59,21 +62,25 @@ public LoginResult loginUser(LoginRequestDto request) { new UsernamePasswordAuthenticationToken(request.email(), request.password())); } catch (BadCredentialsException e) { userOpt.ifPresent(loginAttemptsService::recordFailedLoginAttempt); - throw new UnauthorizedException("Invalid email or password", "INVALID_CREDENTIALS"); + throw new UnauthorizedException(ErrorCode.INVALID_CREDENTIALS, "Invalid email or password"); } catch (DisabledException e) { throw new ForbiddenException( - "User account is disabled. Please verify your email or contact support.", - "ACCOUNT_NOT_VERIFIED"); + ErrorCode.ACCOUNT_NOT_VERIFIED, + "User account is disabled. Please verify your email or contact support."); } catch (LockedException e) { throw new ForbiddenException( - "User account is locked. Please contact support or try again later.", - "ACCOUNT_LOCKED"); + ErrorCode.ACCOUNT_LOCKED, + "User account is locked. Please contact support or try again later."); } catch (AuthenticationException e) { - log.error("Authentication failed for user {}: {}", request.email(), e.getMessage()); + log.error( + "Authentication failed for user {}: {}", + sanitizer.sanitizeLogging(request.email()), + e.getMessage() + ); userOpt.ifPresent(loginAttemptsService::recordFailedLoginAttempt); throw new UnauthorizedException( - "Authentication failed. Please check your credentials.", - "INVALID_CREDENTIALS"); + ErrorCode.INVALID_CREDENTIALS, + "Authentication failed. Please check your credentials."); } User authenticatedUser = (User) authentication.getPrincipal(); @@ -88,15 +95,16 @@ public LoginResult loginUser(LoginRequestDto request) { if (refreshTokenJti != null) { refreshTokenService.storeRefreshToken(refreshTokenJti, authenticatedUser.getId()); } else { - log.error("Could not generate JTI for refresh token for user {}", authenticatedUser.getEmail()); + log.error( + "Could not generate JTI for refresh token for user {}", + sanitizer.sanitizeLogging(authenticatedUser.getEmail()) + ); throw new TokenProcessingException("Error processing refresh token."); } authenticatedUser.setLastLogin(OffsetDateTime.now()); userRepository.save(authenticatedUser); - // Issue #8: Login response contains only token data — profile via GET - // /api/v1/user/me LoginData data = LoginData.builder() .userId(authenticatedUser.getId()) .accessToken(accessToken) diff --git a/src/main/java/com/xtraction/api/identity/auth/impl/RefreshTokenImpl.java b/src/main/java/com/xtraction/api/identity/auth/impl/RefreshTokenImpl.java index 861fbae..b349c93 100644 --- a/src/main/java/com/xtraction/api/identity/auth/impl/RefreshTokenImpl.java +++ b/src/main/java/com/xtraction/api/identity/auth/impl/RefreshTokenImpl.java @@ -6,6 +6,7 @@ import com.xtraction.api.identity.auth.dto.RefreshResult; import com.xtraction.api.identity.auth.interfaces.RefreshTokenService; import com.xtraction.api.identity.auth.service.CustomUserDetailsService; +import com.xtraction.api.core.exceptions.custom.ErrorCode; import com.xtraction.api.core.exceptions.custom.UnauthorizedException; import com.xtraction.api.core.web.response.ResponseBuilderService; import com.xtraction.api.core.security.JwtTokenProvider; @@ -35,7 +36,9 @@ public class RefreshTokenImpl implements RefreshTokenService { @Override public RefreshResult refreshToken(String requestRefreshToken) { if (requestRefreshToken == null || requestRefreshToken.isBlank()) { - throw new UnauthorizedException("Refresh token is required.", "TOKEN_MISSING"); + throw new UnauthorizedException( + ErrorCode.TOKEN_MISSING, "Refresh token is required." + ); } String refreshTokenJti = jwtTokenProvider.getJtiFromToken(requestRefreshToken); @@ -43,32 +46,35 @@ public RefreshResult refreshToken(String requestRefreshToken) { if (refreshTokenJti == null || !jwtTokenProvider.validateToken(requestRefreshToken) || !refreshTokenService.validateRefreshToken(refreshTokenJti)) { - throw new UnauthorizedException("Invalid or expired refresh token.", "TOKEN_INVALID"); + throw new UnauthorizedException( + ErrorCode.TOKEN_INVALID, "Invalid or expired refresh token." + ); } Claims claims = jwtTokenProvider.getAllClaimsFromToken(requestRefreshToken); String tokenType = claims.get("type", String.class); if (!"REFRESH".equals(tokenType)) { - throw new UnauthorizedException("Invalid token type for refresh.", "TOKEN_INVALID"); + throw new UnauthorizedException( + ErrorCode.TOKEN_INVALID, "Invalid token type for refresh." + ); } String userId = refreshTokenService.getUserIdByTokenJti(refreshTokenJti); User user = customUserDetailsService.loadUserEntityById(userId); if (!user.isVerified()) { - throw new UnauthorizedException("User account is not active or verified.", "ACCOUNT_NOT_VERIFIED"); + throw new UnauthorizedException( + ErrorCode.ACCOUNT_NOT_VERIFIED, "User account is not active or verified." + ); } String newAccessToken = jwtTokenProvider.generateAccessToken(user); - // Rolling refresh tokens — invalidate old, issue new refreshTokenService.deleteRefreshToken(refreshTokenJti); String newRefreshToken = jwtTokenProvider.generateRefreshToken(user); String newRefreshTokenJti = jwtTokenProvider.getJtiFromToken(newRefreshToken); refreshTokenService.storeRefreshToken(newRefreshTokenJti, String.valueOf(user.getId())); - // Issue #4/#8: Only access token data in JSON body; refresh token set as cookie - // by controller RefreshLoginData loginData = new RefreshLoginData( newAccessToken, "Bearer", @@ -101,7 +107,7 @@ public ApiResponse logout(HttpServletRequest request) { tokenBlacklistService.blacklistToken(jti, expiresInSeconds); } - // Issue #1: Invalidate all refresh tokens for this user + // Invalidate all refresh tokens for this user String userId = claims.get("userId", String.class); if (userId != null) { refreshTokenService.deleteAllRefreshTokensForUser(userId); From 0eacb2b01fa1a4ed26333dd6eaf81dfe0b2d5a72 Mon Sep 17 00:00:00 2001 From: aniebietafia Date: Mon, 6 Jul 2026 14:16:13 +0100 Subject: [PATCH 3/3] test: mock SanitizeLogging dependency in LoginUserImplTest Signed-off-by: aniebietafia --- .../api/identity/auth/service/impl/LoginUserImplTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/test/java/com/xtraction/api/identity/auth/service/impl/LoginUserImplTest.java b/src/test/java/com/xtraction/api/identity/auth/service/impl/LoginUserImplTest.java index b0f7c3f..2725edb 100644 --- a/src/test/java/com/xtraction/api/identity/auth/service/impl/LoginUserImplTest.java +++ b/src/test/java/com/xtraction/api/identity/auth/service/impl/LoginUserImplTest.java @@ -1,5 +1,6 @@ package com.xtraction.api.identity.auth.service.impl; +import com.xtraction.api.core.utils.logging.SanitizeLogging; import com.xtraction.api.core.web.response.ApiResponse; import com.xtraction.api.identity.auth.dto.LoginData; @@ -53,6 +54,9 @@ public class LoginUserImplTest { @Mock private RefreshTokenService refreshTokenService; + @Mock + private SanitizeLogging sanitizer; + @InjectMocks private LoginUserImpl loginUserImpl; @@ -63,6 +67,7 @@ public class LoginUserImplTest { @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); + when(sanitizer.sanitizeLogging(anyString())).thenAnswer(invocation -> invocation.getArgument(0)); loginRequest = new LoginRequestDto("test@example.com", "password"); user = new User();