From 20242c3561f73be731ed0173858d5e53f5ee8002 Mon Sep 17 00:00:00 2001 From: aniebietafia Date: Tue, 30 Jun 2026 14:29:08 +0100 Subject: [PATCH] refactor(auth): migrate login attempts persistence from database to Redis Refactors login attempts and account lockout tracking to leverage Redis instead of the PostgreSQL database. This improves performance and lightens the strain on the DB. - Adds Flyway migration V61 to drop the `login_attempts` table. - Removes JPA `@OneToOne` mapping from the `User` entity to `LoginAttempts`. - Converts `LoginAttempts` to a simple POJO and deletes `LoginAttemptsRepository`. - Rewrites `LoginAttemptsImpl` using `StringRedisTemplate` to store data: - User attempts: Hash key `login_attempts:user:{userId}`. - Active bans: ZSet key `login_attempts:blocked_users` (scored by epoch millisecond). - Failed logins: ZSet key `login_attempts:failed_logins_history` with 24h automatic pruning. - Integrates the non-deprecated `redisTemplate.expire(key, Duration)` signature. - Updates dependent statistics, KPI dashboards, and profile views. - Refactors user query filtering in `CustomUserRepositoryImpl` to query Redis blocked IDs and append JPQL `IN` / `NOT IN` clauses. - Updates all corresponding unit tests, verifying with a clean build. Signed-off-by: aniebietafia --- .../api/admin/api_docs/cli_admin_setup.md | 65 +++++ .../api/admin/config/AdminCliRunner.java | 100 ++++++++ .../admin/config/AdminUserInitializer.java | 5 - .../api/admin/controller/AdminController.java | 51 +--- .../api/admin/dto/ActiveOtpData.java | 19 -- .../dto/request/AdminSignupRequestDto.java | 62 ----- .../api/admin/dto/request/OtpRequestDto.java | 18 -- .../admin/dto/response/ActiveOtpListData.java | 19 -- .../api/admin/impl/CreateAdminUserImpl.java | 80 ++---- .../admin/impl/FetchActiveOtpCodesImpl.java | 57 ----- .../api/admin/impl/GenerateOtpImpl.java | 77 ------ .../api/admin/impl/GetUserProfileByAdmin.java | 4 +- .../api/admin/impl/OtpCleanupServiceImpl.java | 63 ----- .../admin/interfaces/CreateAdminService.java | 14 +- .../admin/interfaces/FetchActiveOtpCodes.java | 10 - .../admin/interfaces/GenerateOtpService.java | 10 - .../com/xtraction/api/admin/model/Otp.java | 49 ---- .../repository/CustomUserRepositoryImpl.java | 26 +- .../api/admin/repository/OtpRepository.java | 42 ---- .../api/admin/service/AdminService.java | 15 -- .../impl/AdminSecurityStatsServiceImpl.java | 8 +- .../impl/AdminUserActionServiceImpl.java | 8 +- .../impl/AdminUserStatsServiceImpl.java | 6 +- .../impl/DashboardMetricsCacheService.java | 6 +- .../identity/auth/impl/SignupUserImpl.java | 6 - .../interfaces/LoginAttemptsService.java | 9 + .../loginattempts/model/LoginAttempts.java | 29 +-- .../repository/LoginAttemptsRepository.java | 18 -- .../service/LoginAttemptsImpl.java | 154 +++++++++--- .../api/identity/user/model/User.java | 4 - .../migration/V60__drop_admin_otp_table.sql | 1 + .../V61__drop_login_attempts_table.sql | 2 + .../AdminSecurityStatsServiceImplTest.java | 8 +- .../impl/AdminUserActionServiceImplTest.java | 13 +- .../impl/AdminUserStatsServiceImplTest.java | 6 +- .../impl/GetUserProfileByAdminTest.java | 5 + .../impl/OtpCleanupServiceImplTest.java | 127 ---------- .../events/ReceiptEventPublisherTest.java | 6 +- .../impl/DashboardMetricsServiceImplTest.java | 8 +- .../auth/service/impl/SignupUserImplTest.java | 13 +- .../service/LoginAttemptsImplTest.java | 238 ++++++++---------- 41 files changed, 501 insertions(+), 960 deletions(-) create mode 100644 src/main/java/com/xtraction/api/admin/api_docs/cli_admin_setup.md create mode 100644 src/main/java/com/xtraction/api/admin/config/AdminCliRunner.java delete mode 100644 src/main/java/com/xtraction/api/admin/dto/ActiveOtpData.java delete mode 100644 src/main/java/com/xtraction/api/admin/dto/request/AdminSignupRequestDto.java delete mode 100644 src/main/java/com/xtraction/api/admin/dto/request/OtpRequestDto.java delete mode 100644 src/main/java/com/xtraction/api/admin/dto/response/ActiveOtpListData.java delete mode 100644 src/main/java/com/xtraction/api/admin/impl/FetchActiveOtpCodesImpl.java delete mode 100644 src/main/java/com/xtraction/api/admin/impl/GenerateOtpImpl.java delete mode 100644 src/main/java/com/xtraction/api/admin/impl/OtpCleanupServiceImpl.java delete mode 100644 src/main/java/com/xtraction/api/admin/interfaces/FetchActiveOtpCodes.java delete mode 100644 src/main/java/com/xtraction/api/admin/interfaces/GenerateOtpService.java delete mode 100644 src/main/java/com/xtraction/api/admin/model/Otp.java delete mode 100644 src/main/java/com/xtraction/api/admin/repository/OtpRepository.java delete mode 100644 src/main/java/com/xtraction/api/identity/loginattempts/repository/LoginAttemptsRepository.java create mode 100644 src/main/resources/db/migration/V60__drop_admin_otp_table.sql create mode 100644 src/main/resources/db/migration/V61__drop_login_attempts_table.sql delete mode 100644 src/test/java/com/xtraction/api/admin/service/impl/OtpCleanupServiceImplTest.java diff --git a/src/main/java/com/xtraction/api/admin/api_docs/cli_admin_setup.md b/src/main/java/com/xtraction/api/admin/api_docs/cli_admin_setup.md new file mode 100644 index 0000000..974b41c --- /dev/null +++ b/src/main/java/com/xtraction/api/admin/api_docs/cli_admin_setup.md @@ -0,0 +1,65 @@ +# CLI Administrative User Setup Guide + +This document describes the implementation and usage of the server-side CLI administration tool, which replaced the deprecated HTTP-based REST API signup/OTP flow. + +--- + +## 1. Overview & Security Rationale + +To reduce the public attack surface of the application, all public HTTP-facing endpoints for administrative signup (`/api/v1/admin/signup`), OTP generation (`/api/v1/admin/generate-otp`), and OTP listing (`/api/v1/admin/active-otps`) have been completely removed. + +Administrative user setup must now be done directly on the server host or container using the Spring Boot CLI runner. This ensures that: +* **Zero Network Exposure**: No public endpoints exist for brute-forcing admin privileges. +* **DevOps Isolation**: Only users with console or shell access (`SSH`, `kubectl exec`, or secure deployment pipelines) can provision admin accounts. + +--- + +## 2. Command Usage + +The CLI command is triggered by passing the `--create-admin` parameter alongside the admin user details. + +If any required parameter is missing or invalid, the command displays the correct usage instructions and exits with status code `1`. Upon successful creation, it prints the user details and exits with status code `0`. + +### Development (Maven) +Run the following command in your terminal from the project root: + +```powershell +mvn spring-boot:run "-Dspring-boot.run.arguments=--create-admin --email=admin@xtraction.xyz --password=SecurePassword123! --first-name=Jane --last-name=Doe --country=US --role=SUPER_ADMIN" +``` + +### Production (JAR) +Run the compiled executable archive directly: + +```bash +java -jar xtraction-api.jar --create-admin \ + --email="admin@xtraction.xyz" \ + --password="SecurePassword123!" \ + --first-name="Jane" \ + --last-name="Doe" \ + --country="US" \ + --role="super_admin" +``` + +--- + +## 3. Parameter Reference + +| Parameter | Required? | Default | Description | +|:-------------------------------|:----------|:--------|:-------------------------------------------------------------| +| `--create-admin` | **Yes** | *None* | Trigger flag that activates the admin CLI creation sequence. | +| `--email` | **Yes** | *None* | Unique email address for the new administrative user. | +| `--password` | **Yes** | *None* | Secure password for the admin account. | +| `--first-name` / `--firstName` | **Yes** | *None* | First name of the administrator. | +| `--last-name` / `--lastName` | **Yes** | *None* | Last name of the administrator. | +| `--country` | No | `US` | Two-letter country code (e.g., `NG`, `US`, `GB`). | +| `--role` | No | `admin` | Target role. Must be either `admin` or `super_admin`. | + +--- + +## 4. Under-the-Hood Sequence +1. The `AdminCliRunner` bean implements `ApplicationRunner` and executes on startup. +2. It detects the `--create-admin` argument and hijacks the regular application boot loop. +3. It performs validations on required fields and checks that the requested email is not already registered. +4. It calls `CreateAdminService` to hash the password, save the new `User` to the database, assign the default unlimited credit plan and default subscription, and register the transaction commit synchronization. +5. Once the transaction successfully commits, a Kafka `AdminCreatedEvent` is dispatched. +6. The CLI prints a success confirmation table and exits the JVM with code `0`, preventing Tomcat/Netty from binding to network ports. diff --git a/src/main/java/com/xtraction/api/admin/config/AdminCliRunner.java b/src/main/java/com/xtraction/api/admin/config/AdminCliRunner.java new file mode 100644 index 0000000..4aa6d6d --- /dev/null +++ b/src/main/java/com/xtraction/api/admin/config/AdminCliRunner.java @@ -0,0 +1,100 @@ +package com.xtraction.api.admin.config; + +import com.xtraction.api.admin.interfaces.CreateAdminService; +import com.xtraction.api.identity.auth.datamodel.Role; +import com.xtraction.api.identity.user.model.User; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +@RequiredArgsConstructor +public class AdminCliRunner implements ApplicationRunner { + + private final CreateAdminService createAdminService; + + @Override + public void run(ApplicationArguments args) throws Exception { + if (args.containsOption("create-admin")) { + System.out.println("================================================="); + System.out.println(" XTRACTION CLI ADMIN CREATION "); + System.out.println("================================================="); + + String email = getOptionValue(args, "email"); + String password = getOptionValue(args, "password"); + String firstName = getOptionValue(args, "first-name"); + if (firstName == null) { + firstName = getOptionValue(args, "firstName"); + } + String lastName = getOptionValue(args, "last-name"); + if (lastName == null) { + lastName = getOptionValue(args, "lastName"); + } + String country = getOptionValue(args, "country"); + if (country == null || country.isBlank()) { + country = "US"; + } + String roleStr = getOptionValue(args, "role"); + Role role = Role.ADMIN; + + if (roleStr != null && !roleStr.isBlank()) { + try { + role = Role.fromString(roleStr); + if (role != Role.ADMIN && role != Role.SUPER_ADMIN) { + System.err.println("Error: Role must be either admin or super_admin."); + printUsageAndExit(); + } + } catch (Exception e) { + System.err.println("Error: Invalid role value. Allowed values: admin, super_admin"); + printUsageAndExit(); + } + } + + if (email == null || email.isBlank() || + password == null || password.isBlank() || + firstName == null || firstName.isBlank() || + lastName == null || lastName.isBlank()) { + System.err.println("Error: Missing required parameters."); + printUsageAndExit(); + } + + try { + User admin = createAdminService.createAdminUser(firstName, lastName, email, password, country, role); + System.out.println("SUCCESS: Admin user successfully created!"); + System.out.println("ID: " + admin.getId()); + System.out.println("Name: " + admin.getFirstName() + " " + admin.getLastName()); + System.out.println("Email: " + admin.getEmail()); + System.out.println("Role: " + admin.getRole().name()); + System.out.println("Country: " + admin.getCountry()); + System.out.println("================================================="); + System.exit(0); + } catch (Exception e) { + System.err.println("FAILED: Error creating admin user: " + e.getMessage()); + System.err.println("================================================="); + System.exit(1); + } + } + } + + private String getOptionValue(ApplicationArguments args, String optionName) { + if (args.containsOption(optionName)) { + List values = args.getOptionValues(optionName); + if (values != null && !values.isEmpty()) { + return values.get(0); + } + } + return null; + } + + private void printUsageAndExit() { + System.out.println("Usage:"); + System.out.println(" --create-admin --email= --password= --first-name= --last-name= [--country=] [--role=admin|super_admin]"); + System.out.println("================================================="); + System.exit(1); + } +} diff --git a/src/main/java/com/xtraction/api/admin/config/AdminUserInitializer.java b/src/main/java/com/xtraction/api/admin/config/AdminUserInitializer.java index ef05817..2518a8f 100644 --- a/src/main/java/com/xtraction/api/admin/config/AdminUserInitializer.java +++ b/src/main/java/com/xtraction/api/admin/config/AdminUserInitializer.java @@ -9,7 +9,6 @@ import com.xtraction.api.billing.credit.repository.UserCreditBalanceRepository; import com.xtraction.api.billing.credit.service.CreditBalanceService; import com.xtraction.api.extraction.documents.utils.SanitizeLogging; -import com.xtraction.api.identity.loginattempts.model.LoginAttempts; import com.xtraction.api.billing.subscription.datamodel.BillingIntervalUnit; import com.xtraction.api.billing.subscription.datamodel.SubscriptionCurrency; import com.xtraction.api.billing.subscription.datamodel.SubscriptionPlans; @@ -145,10 +144,6 @@ private User createAdminUser() { var verification = getVerification(adminUser, now); adminUser.setUserVerification(verification); - var loginAttempts = new LoginAttempts(); - loginAttempts.setUser(adminUser); - adminUser.setLoginAttempts(loginAttempts); - return adminUser; } diff --git a/src/main/java/com/xtraction/api/admin/controller/AdminController.java b/src/main/java/com/xtraction/api/admin/controller/AdminController.java index 8a781ac..c28b6d3 100644 --- a/src/main/java/com/xtraction/api/admin/controller/AdminController.java +++ b/src/main/java/com/xtraction/api/admin/controller/AdminController.java @@ -32,22 +32,7 @@ public class AdminController { private final AdminService adminService; - /** - * Create an admin user if none exists. - * - * @param request The sign-up request containing user details. - * @return ResponseEntity containing the created admin user data. - */ - @Operation( - summary = "Create Admin User", - description = "Allows users to register as an admin to manage the application.") - @PostMapping("/signup") - public ResponseEntity> createAdmin( - @Valid @RequestBody AdminSignupRequestDto request - ) { - XtractionResponse response = adminService.createAdmin(request); - return ResponseEntity.ok(response); - } + /** * Change the role of a user to ADMIN or MODERATOR. @@ -245,41 +230,7 @@ public ResponseEntity> getPlanSubscribers( return ResponseEntity.ok(adminService.getPlanSubscribers(planId, page, size)); } - /** - * Generate a One-Time Password (OTP) of specified length. - * - * @param request The request containing OTP generation parameters. - * @return ResponseEntity containing the generated OTP. - */ - @Operation( - summary = "Generate OTP", - description = "Generates a One-Time Password (OTP) of specified length.") - @PreAuthorize("hasRole('SUPER_ADMIN')") - @PostMapping("/generate-otp") - public ResponseEntity>> generateOtp( - @Valid @RequestBody OtpRequestDto request - ) { - XtractionResponse> response = adminService.generateOtp(request); - return ResponseEntity.ok(response); - } - /** - * Fetch all active OTPs. - * - * @return ResponseEntity containing the list of active OTPs. - */ - @Operation( - summary = "Fetch Active OTPs", - description = "Fetches all active One-Time Passwords (OTPs).") - @PreAuthorize("hasRole('SUPER_ADMIN') or hasRole('ADMIN')") - @GetMapping("/active-otps") - public ResponseEntity> fetchActiveOtps( - @RequestParam(defaultValue = "0") int page, - @RequestParam(defaultValue = "5") int size - ) { - XtractionResponse response = adminService.fetchActiveOtpCodes(page, size); - return ResponseEntity.ok(response); - } // ========================================== // PROMO_CODE STATISTICS diff --git a/src/main/java/com/xtraction/api/admin/dto/ActiveOtpData.java b/src/main/java/com/xtraction/api/admin/dto/ActiveOtpData.java deleted file mode 100644 index acbbc6e..0000000 --- a/src/main/java/com/xtraction/api/admin/dto/ActiveOtpData.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xtraction.api.admin.dto; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class ActiveOtpData { - private String id; - private String otpCode; - private String createdBy; - private boolean isUsed; - private String usedAt; - private boolean isExpired; - private String expiresAt; - private String createdAt; -} diff --git a/src/main/java/com/xtraction/api/admin/dto/request/AdminSignupRequestDto.java b/src/main/java/com/xtraction/api/admin/dto/request/AdminSignupRequestDto.java deleted file mode 100644 index eec7d26..0000000 --- a/src/main/java/com/xtraction/api/admin/dto/request/AdminSignupRequestDto.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.xtraction.api.admin.dto.request; - -import com.xtraction.api.identity.auth.dto.PasswordMatches; -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.*; -import lombok.Data; - -@Data -@Schema(description = "Create Admin Request DTO") -@PasswordMatches -public class AdminSignupRequestDto { - @Schema(description = "First name of the admin user", example = "John") - @NotNull(message = "First name is required") - @Size(min = 3, max = 80, message = "First name must be between 3 and 80 characters") - private String firstName; - - @Schema(description = "Last name of the admin user", example = "Doe") - @NotNull(message = "Last name is required") - @Size(min = 3, max = 80, message = "Last name must be between 3 and 80 characters") - private String lastName; - - @Schema(description = "Email address of the admin user", example = "johndoe@example.com") - @NotNull(message = "Email is required") - @Email(message = "Please enter a valid email address") - @Pattern( - regexp = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$", - message = "Email must be a valid email address format" - ) - @Size(max = 100, message = "Email must be less than 100 characters") - private String email; - - @Schema(description = "Password of the admin user", example = "P@ssw0rd123") - @NotNull(message = "Password is required") - @Size(min = 8, message = "Password must be at least 8 characters") - @Pattern.List({ - @Pattern(regexp = ".*[a-z].*", message = "Password must contain at least one lowercase letter"), - @Pattern(regexp = ".*[A-Z].*", message = "Password must contain at least one uppercase letter"), - @Pattern(regexp = ".*[0-9].*", message = "Password must contain at least one digit"), - @Pattern(regexp = ".*[@$!%*?&].*", message = "Password must contain at least one special character") - }) - private String password; - - @Schema(description = "Confirm password of the admin user", example = "P@ssw0rd123") - @NotNull(message = "Confirm password is required") - private String confirmPassword; - - @Schema(description = "Admin creation code", example = "ADMIN-CREATE-2024") - @NotNull(message = "Admin creation code is required") - private String code; - - @Schema(description = "Country of the user", example = "USA") - @NotNull(message = "Country is required") - String country; - - @Schema(description = "Terms and Conditions acceptance", example = "true") - @NotNull(message = "You must accept the terms and conditions") - @AssertTrue(message = "You must accept the terms and conditions") - Boolean acceptTerms; - - @Schema(description = "Marketing emails subscription", example = "false") - Boolean subscribeToMarketing; -} diff --git a/src/main/java/com/xtraction/api/admin/dto/request/OtpRequestDto.java b/src/main/java/com/xtraction/api/admin/dto/request/OtpRequestDto.java deleted file mode 100644 index bd74227..0000000 --- a/src/main/java/com/xtraction/api/admin/dto/request/OtpRequestDto.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.xtraction.api.admin.dto.request; - -import io.swagger.v3.oas.annotations.media.Schema; -import jakarta.validation.constraints.Max; -import jakarta.validation.constraints.Min; -import lombok.Data; - -@Data -public class OtpRequestDto { - @Schema(description = "Length of the OTP to be generated", example = "6") - @Min(value = 6, message = "Length must be at least 6") - @Max(value = 10, message = "Length must be at most 10") - private int length; - - @Schema(description = "Number of OTPs to generate", example = "1") - @Min(value = 1, message = "Count must be at least 1") - private int count; -} diff --git a/src/main/java/com/xtraction/api/admin/dto/response/ActiveOtpListData.java b/src/main/java/com/xtraction/api/admin/dto/response/ActiveOtpListData.java deleted file mode 100644 index 779f2be..0000000 --- a/src/main/java/com/xtraction/api/admin/dto/response/ActiveOtpListData.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.xtraction.api.admin.dto.response; - -import com.xtraction.api.admin.dto.ActiveOtpData; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; - -import java.util.List; - -@Data -@AllArgsConstructor -@NoArgsConstructor -public class ActiveOtpListData { - private List otps; - private long totalOtps; - private int totalPages; - private int currentPage; - private int pageSize; -} diff --git a/src/main/java/com/xtraction/api/admin/impl/CreateAdminUserImpl.java b/src/main/java/com/xtraction/api/admin/impl/CreateAdminUserImpl.java index 6a252d0..8d667d1 100644 --- a/src/main/java/com/xtraction/api/admin/impl/CreateAdminUserImpl.java +++ b/src/main/java/com/xtraction/api/admin/impl/CreateAdminUserImpl.java @@ -1,21 +1,14 @@ package com.xtraction.api.admin.impl; -import com.xtraction.api.admin.dto.AdminData; -import com.xtraction.api.admin.dto.request.AdminSignupRequestDto; import com.xtraction.api.admin.events.AdminCreatedEvent; import com.xtraction.api.admin.interfaces.CreateAdminService; -import com.xtraction.api.admin.repository.OtpRepository; import com.xtraction.api.identity.auth.datamodel.Role; import com.xtraction.api.identity.auth.model.UserVerification; import com.xtraction.api.integration.broker.kafka.events.BaseEvent; import com.xtraction.api.integration.broker.kafka.events.EventMetadata; 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.ConflictException; -import com.xtraction.api.identity.loginattempts.model.LoginAttempts; -import com.xtraction.api.core.shared.response.ResponseBuilderService; -import com.xtraction.api.core.shared.response.XtractionResponse; import com.xtraction.api.billing.subscription.impl.AssignSubscriptionService; import com.xtraction.api.billing.subscription.model.UserSubscription; import com.xtraction.api.identity.user.model.User; @@ -24,7 +17,6 @@ import com.xtraction.api.core.utils.userlib.DateHelper; import com.xtraction.api.core.utils.userlib.UserLibrary; import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -41,54 +33,42 @@ public class CreateAdminUserImpl implements CreateAdminService { private final DateHelper dateHelper; private final EventPublisherService eventPublisher; private final GenerateVerificationToken generateVerificationToken; - private final ResponseBuilderService responseBuilder; private final UserRepository userRepository; private final UserLibrary library; - private final OtpRepository otpRepository; private final PasswordEncoder passwordEncoder; @Override @Transactional - public XtractionResponse createAdminUser(AdminSignupRequestDto request) { - // Check if code is a valid code - var code = request.getCode(); - if (code == null || code.isBlank()) { - throw new ConflictException("Admin signup code is required."); + public User createAdminUser( + String firstName, + String lastName, + String email, + String password, + String country, + Role role + ) { + if (userRepository.existsByEmail(email)) { + throw new ConflictException("Admin user already exists with email: " + email); } - // check if code exists and is valid - var otpRecord = otpRepository.findByOtpCodeAndIsExpiredFalseAndIsUsedFalse(code) - .orElseThrow(() -> new ConflictException("Invalid or expired admin signup code.")); - - OffsetDateTime now = OffsetDateTime.now(); - - // check if otp is expired - if (otpRecord.getExpiresAt().isBefore(now)) { - otpRecord.setExpired(true); - otpRepository.save(otpRecord); - throw new BadRequestException("Admin signup code has expired."); - } - - if (userRepository.existsByEmail(request.getEmail())) { - throw new ConflictException("Admin user already exists with email: " + request.getEmail()); - } - - if (request.getPassword().equalsIgnoreCase(request.getEmail())) { + if (password.equalsIgnoreCase(email)) { throw new ConflictException("Password cannot be same as email."); } + OffsetDateTime now = OffsetDateTime.now(); + User newAdmin = new User(); - newAdmin.setFirstName(library.capitalizeFirstLetterOfName(request.getFirstName())); - newAdmin.setLastName(library.capitalizeFirstLetterOfName(request.getLastName())); - newAdmin.setEmail(request.getEmail()); - newAdmin.setPassword(passwordEncoder.encode(request.getPassword())); + newAdmin.setFirstName(library.capitalizeFirstLetterOfName(firstName)); + newAdmin.setLastName(library.capitalizeFirstLetterOfName(lastName)); + newAdmin.setEmail(email); + newAdmin.setPassword(passwordEncoder.encode(password)); newAdmin.setActive(true); newAdmin.setVerified(true); - newAdmin.setRole(Role.ADMIN); + newAdmin.setRole(role); newAdmin.setPlatformAdmin(true); - newAdmin.setCountry(request.getCountry()); - newAdmin.setTermsAccepted(request.getAcceptTerms()); - newAdmin.setMarketingOptIn(request.getSubscribeToMarketing()); + newAdmin.setCountry(country == null || country.isBlank() ? "US" : country); + newAdmin.setTermsAccepted(true); + newAdmin.setMarketingOptIn(false); newAdmin.setCreatedAt(now); newAdmin.setUpdatedAt(now); @@ -101,22 +81,12 @@ public XtractionResponse createAdminUser(AdminSignupRequestDto reques userVerification.setEmailVerificationTokenExpiry(tokenExpiry); newAdmin.setUserVerification(userVerification); - // Initialize login attempts for the new admin user - LoginAttempts loginAttempts = new LoginAttempts(); - loginAttempts.setUser(newAdmin); - newAdmin.setLoginAttempts(loginAttempts); - // Assign default subscription based on user role UserSubscription adminSubscription = subscription.assignDefaultSubscription(newAdmin); newAdmin.setSubscription(adminSubscription); User savedAdmin = userRepository.save(newAdmin); - // Mark the OTP as used - otpRecord.setUsed(true); - otpRecord.setUsedAt(OffsetDateTime.now()); - otpRepository.save(otpRecord); - // Publish admin created event TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @Override @@ -144,12 +114,6 @@ public void afterCommit() { } }); - AdminData adminData = new AdminData(); - adminData.setEmail(newAdmin.getEmail()); - adminData.setFirstName(newAdmin.getFirstName()); - adminData.setLastName(newAdmin.getLastName()); - adminData.setRole(Role.ADMIN); - - return responseBuilder.buildUserResponse(adminData, HttpStatus.CREATED, "Admin user created successfully"); + return savedAdmin; } } diff --git a/src/main/java/com/xtraction/api/admin/impl/FetchActiveOtpCodesImpl.java b/src/main/java/com/xtraction/api/admin/impl/FetchActiveOtpCodesImpl.java deleted file mode 100644 index 010db7b..0000000 --- a/src/main/java/com/xtraction/api/admin/impl/FetchActiveOtpCodesImpl.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.xtraction.api.admin.impl; - -import com.xtraction.api.admin.dto.ActiveOtpData; -import com.xtraction.api.admin.dto.response.ActiveOtpListData; -import com.xtraction.api.admin.interfaces.FetchActiveOtpCodes; -import com.xtraction.api.admin.model.Otp; -import com.xtraction.api.admin.repository.OtpRepository; -import com.xtraction.api.core.shared.response.ResponseBuilderService; -import com.xtraction.api.core.shared.response.XtractionResponse; -import lombok.RequiredArgsConstructor; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.PageRequest; -import org.springframework.data.domain.Pageable; -import org.springframework.http.HttpStatus; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.util.List; - -@Service -@RequiredArgsConstructor -public class FetchActiveOtpCodesImpl implements FetchActiveOtpCodes { - private final OtpRepository otpRepository; - private final ResponseBuilderService responseBuilderService; - - @Override - @Transactional(readOnly = true) - public XtractionResponse fetchActiveOtpCodes(int page, int size) { - Pageable pageable = PageRequest.of(page, size); - Page otpPage = otpRepository.findActiveOtps(pageable); - - List activeOtps = otpPage.getContent().stream().map(otp -> new ActiveOtpData( - otp.getId(), - otp.getOtpCode(), - otp.getUser().getFirstName() + " " + otp.getUser().getLastName(), - otp.isUsed(), - otp.getUsedAt() != null ? otp.getUsedAt().toString() : null, - otp.isExpired(), - otp.getExpiresAt().toString(), - otp.getCreatedAt().toString() - )).toList(); - - ActiveOtpListData data = new ActiveOtpListData( - activeOtps, - otpPage.getTotalElements(), - otpPage.getTotalPages(), - otpPage.getNumber(), - otpPage.getSize() - ); - - return responseBuilderService.buildUserResponse( - data, - HttpStatus.OK, - "Active OTP codes fetched successfully" - ); - } -} diff --git a/src/main/java/com/xtraction/api/admin/impl/GenerateOtpImpl.java b/src/main/java/com/xtraction/api/admin/impl/GenerateOtpImpl.java deleted file mode 100644 index 62c4ae3..0000000 --- a/src/main/java/com/xtraction/api/admin/impl/GenerateOtpImpl.java +++ /dev/null @@ -1,77 +0,0 @@ -package com.xtraction.api.admin.impl; - -import com.xtraction.api.admin.dto.request.OtpRequestDto; -import com.xtraction.api.admin.interfaces.GenerateOtpService; -import com.xtraction.api.admin.model.Otp; -import com.xtraction.api.admin.repository.OtpRepository; -import com.xtraction.api.core.exceptions.custom.NotFoundException; -import com.xtraction.api.core.shared.response.ResponseBuilderService; -import com.xtraction.api.core.shared.response.XtractionResponse; -import com.xtraction.api.identity.user.model.User; -import com.xtraction.api.identity.user.repository.UserRepository; -import com.xtraction.api.core.utils.generatetoken.GenerateVerificationToken; -import com.xtraction.api.core.utils.userlib.DateHelper; -import lombok.RequiredArgsConstructor; -import org.springframework.http.HttpStatus; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.OffsetDateTime; -import java.util.ArrayList; -import java.util.List; - -@Service -@RequiredArgsConstructor -public class GenerateOtpImpl implements GenerateOtpService { - private final GenerateVerificationToken generateVerificationToken; - private final OtpRepository otpRepository; - private final DateHelper dateHelper; - private final ResponseBuilderService responseBuilder; - private final UserRepository userRepository; - - @Override - @Transactional - public XtractionResponse> generateOtp(OtpRequestDto request) { - var len = request.getLength() > 6 ? request.getLength() : 6; - var count = request.getCount() > 1 ? request.getCount() : 1; - - Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - assert authentication != null; - String userEmail = authentication.getName(); - - User superAdminUser = userRepository.findByEmail(userEmail) - .orElseThrow(() -> new NotFoundException("Super admin user not found")); - - OffsetDateTime now = OffsetDateTime.now(); - var expiry = dateHelper.setExpiryDate(now, "minute", 10); - - List otpCodes = new ArrayList<>(); - - for (int i = 0; i < count; i++) { - String otp = generateVerificationToken.generateOtp(len); - - var otpEntity = new Otp(); - otpEntity.setOtpCode(otp); - otpEntity.setExpiresAt(expiry); - otpEntity.setUser(superAdminUser); - otpEntity.setExpired(false); - otpEntity.setUsed(false); - otpEntity.setExpired(false); - otpRepository.save(otpEntity); - - otpCodes.add(otp); - } - - String message = count > 1 - ? count + " OTPs generated successfully" - : "OTP generated successfully"; - - return responseBuilder.buildUserResponse( - otpCodes, - HttpStatus.OK, - message - ); - } -} diff --git a/src/main/java/com/xtraction/api/admin/impl/GetUserProfileByAdmin.java b/src/main/java/com/xtraction/api/admin/impl/GetUserProfileByAdmin.java index 58bf9c5..10a3ecd 100644 --- a/src/main/java/com/xtraction/api/admin/impl/GetUserProfileByAdmin.java +++ b/src/main/java/com/xtraction/api/admin/impl/GetUserProfileByAdmin.java @@ -6,6 +6,7 @@ import com.xtraction.api.billing.credit.repository.UserCreditBalanceRepository; import com.xtraction.api.core.exceptions.custom.NotFoundException; import com.xtraction.api.identity.loginattempts.model.LoginAttempts; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.core.shared.response.ResponseBuilderService; import com.xtraction.api.core.shared.response.XtractionResponse; import com.xtraction.api.billing.subscription.model.UserSubscription; @@ -24,6 +25,7 @@ public class GetUserProfileByAdmin implements GetUserProfileByAdminService { private final ResponseBuilderService responseBuilder; private final UserRepository userRepository; private final UserCreditBalanceRepository creditBalanceRepository; + private final LoginAttemptsService loginAttemptsService; @Override public XtractionResponse getUserProfileByAdmin(String userId) { @@ -71,7 +73,7 @@ private AdminUserDetailDto mapToDetailDto(User user, UserCreditBalance credit) { .build(); // Map Login Security - LoginAttempts la = user.getLoginAttempts(); + LoginAttempts la = loginAttemptsService.getLoginAttempts(user); AdminUserDetailDto.LoginSecurity security = AdminUserDetailDto.LoginSecurity.builder() .attempts(la != null ? la.getLoginAttempts() : 0) .isBlocked(la != null && la.isBlocked()) diff --git a/src/main/java/com/xtraction/api/admin/impl/OtpCleanupServiceImpl.java b/src/main/java/com/xtraction/api/admin/impl/OtpCleanupServiceImpl.java deleted file mode 100644 index 3c13550..0000000 --- a/src/main/java/com/xtraction/api/admin/impl/OtpCleanupServiceImpl.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.xtraction.api.admin.impl; - -import com.xtraction.api.admin.repository.OtpRepository; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.scheduling.annotation.Scheduled; -import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; - -import java.time.OffsetDateTime; - -/** - * Service responsible for OTP cleanup operations: - * 1. Marks expired OTPs (runs every 5 minutes) - * 2. Deletes OTPs expired for more than 24 hours (runs daily at 2 AM) - */ -@Slf4j -@Service -@RequiredArgsConstructor -public class OtpCleanupServiceImpl { - private final OtpRepository otpRepository; - - /** - * Scheduled task to mark expired OTPs as expired. - * Runs every 5 minutes for timely expiration status updates. - * Uses bulk update for efficiency. - */ - @Scheduled(cron = "0 */5 * * * ?") - @Transactional - public void markExpiredOtps() { - try { - OffsetDateTime now = OffsetDateTime.now(); - int updatedCount = otpRepository.markExpiredOtps(now); - - if (updatedCount > 0) { - log.info("Marked {} OTP(s) as expired", updatedCount); - } - } catch (Exception e) { - log.error("Error marking expired OTPs: {}", e.getMessage(), e); - } - } - - /** - * Scheduled task to delete OTPs that have been expired for more than 24 hours. - * Runs daily at 1:00 AM to clean up old OTP records. - * Uses bulk delete for efficiency. - */ - @Scheduled(cron = "0 0 1 * * ?") - @Transactional - public void deleteOldExpiredOtps() { - try { - OffsetDateTime threshold = OffsetDateTime.now().minusHours(24); - int deletedCount = otpRepository.deleteExpiredOtpsOlderThan(threshold); - - if (deletedCount > 0) { - log.info("Deleted {} expired OTP(s) older than 24 hours", deletedCount); - } - } catch (Exception e) { - log.error("Error deleting old expired OTPs: {}", e.getMessage(), e); - } - } -} - diff --git a/src/main/java/com/xtraction/api/admin/interfaces/CreateAdminService.java b/src/main/java/com/xtraction/api/admin/interfaces/CreateAdminService.java index 7bc42bc..473ca34 100644 --- a/src/main/java/com/xtraction/api/admin/interfaces/CreateAdminService.java +++ b/src/main/java/com/xtraction/api/admin/interfaces/CreateAdminService.java @@ -1,9 +1,15 @@ package com.xtraction.api.admin.interfaces; -import com.xtraction.api.admin.dto.AdminData; -import com.xtraction.api.admin.dto.request.AdminSignupRequestDto; -import com.xtraction.api.core.shared.response.XtractionResponse; +import com.xtraction.api.identity.auth.datamodel.Role; +import com.xtraction.api.identity.user.model.User; public interface CreateAdminService { - XtractionResponse createAdminUser(AdminSignupRequestDto request); + User createAdminUser( + String firstName, + String lastName, + String email, + String password, + String country, + Role role + ); } diff --git a/src/main/java/com/xtraction/api/admin/interfaces/FetchActiveOtpCodes.java b/src/main/java/com/xtraction/api/admin/interfaces/FetchActiveOtpCodes.java deleted file mode 100644 index 1d29b27..0000000 --- a/src/main/java/com/xtraction/api/admin/interfaces/FetchActiveOtpCodes.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.xtraction.api.admin.interfaces; - -import com.xtraction.api.admin.dto.response.ActiveOtpListData; -import com.xtraction.api.core.shared.response.XtractionResponse; - - - -public interface FetchActiveOtpCodes { - XtractionResponse fetchActiveOtpCodes(int page, int size); -} diff --git a/src/main/java/com/xtraction/api/admin/interfaces/GenerateOtpService.java b/src/main/java/com/xtraction/api/admin/interfaces/GenerateOtpService.java deleted file mode 100644 index b73def3..0000000 --- a/src/main/java/com/xtraction/api/admin/interfaces/GenerateOtpService.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.xtraction.api.admin.interfaces; - -import com.xtraction.api.admin.dto.request.OtpRequestDto; -import com.xtraction.api.core.shared.response.XtractionResponse; - -import java.util.List; - -public interface GenerateOtpService { - XtractionResponse> generateOtp(OtpRequestDto request); -} diff --git a/src/main/java/com/xtraction/api/admin/model/Otp.java b/src/main/java/com/xtraction/api/admin/model/Otp.java deleted file mode 100644 index e3bc13c..0000000 --- a/src/main/java/com/xtraction/api/admin/model/Otp.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.xtraction.api.admin.model; - -import com.xtraction.api.identity.user.model.User; -import jakarta.persistence.*; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.hibernate.annotations.CreationTimestamp; -import org.hibernate.annotations.UpdateTimestamp; - -import java.time.OffsetDateTime; - -@Data -@Entity -@Table(name = "admin_otp") -@NoArgsConstructor -@AllArgsConstructor -public class Otp { - @Id - @GeneratedValue(strategy = GenerationType.UUID) - private String id; - - @ManyToOne(fetch = FetchType.LAZY) - @JoinColumn(name = "created_by", referencedColumnName = "id", nullable = false) - private User user; - - @Column(nullable = false, name = "otp_code", unique = true) - private String otpCode; - - @Column(nullable = false, columnDefinition = "TIMESTAMP", name = "expires_at") - private OffsetDateTime expiresAt; - - @Column(nullable = false, name = "is_used") - private boolean isUsed = false; - - @Column(name = "is_expired", nullable = false) - private boolean isExpired = false; - - @CreationTimestamp - @Column(nullable = false, updatable = false, name = "created_at") - private OffsetDateTime createdAt; - - @UpdateTimestamp - @Column(nullable = false, name = "updated_at") - private OffsetDateTime updatedAt; - - @Column(name = "used_at", columnDefinition = "TIMESTAMP") - private OffsetDateTime usedAt; -} diff --git a/src/main/java/com/xtraction/api/admin/repository/CustomUserRepositoryImpl.java b/src/main/java/com/xtraction/api/admin/repository/CustomUserRepositoryImpl.java index d23684a..7dbe3cb 100644 --- a/src/main/java/com/xtraction/api/admin/repository/CustomUserRepositoryImpl.java +++ b/src/main/java/com/xtraction/api/admin/repository/CustomUserRepositoryImpl.java @@ -9,8 +9,11 @@ import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Repository; +import org.springframework.beans.factory.annotation.Autowired; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import java.util.List; +import java.util.Set; @Repository public class CustomUserRepositoryImpl implements CustomUserRepository { @@ -18,6 +21,9 @@ public class CustomUserRepositoryImpl implements CustomUserRepository { @PersistenceContext private EntityManager entityManager; + @Autowired + private LoginAttemptsService loginAttemptsService; + @Override public Page findAllUsers(UserFilterDto filter, Pageable pageable) { StringBuilder selectStr = new StringBuilder("SELECT DISTINCT u FROM User u "); @@ -31,9 +37,19 @@ public Page findAllUsers(UserFilterDto filter, Pageable pageable) { joins.append(" LEFT JOIN u.subscription sub LEFT JOIN sub.plan p "); where.append(" AND p.name = :subscriptionPlan"); } + Set blockedUserIds = null; if (filter.getIsBlocked() != null) { - joins.append(" LEFT JOIN u.loginAttempts la "); - where.append(" AND la.isBlocked = :isBlocked"); + blockedUserIds = loginAttemptsService.getBlockedUserIds(); + if (filter.getIsBlocked()) { + if (blockedUserIds.isEmpty()) { + return new PageImpl<>(java.util.Collections.emptyList(), pageable, 0); + } + where.append(" AND u.id IN :blockedUserIds"); + } else { + if (!blockedUserIds.isEmpty()) { + where.append(" AND u.id NOT IN :blockedUserIds"); + } + } } if (filter.getHasTeam() != null) { if (filter.getHasTeam()) { @@ -87,9 +103,9 @@ public Page findAllUsers(UserFilterDto filter, Pageable pageable) { query.setParameter("subscriptionPlan", filter.getSubscriptionPlan().name()); countQuery.setParameter("subscriptionPlan", filter.getSubscriptionPlan().name()); } - if (filter.getIsBlocked() != null) { - query.setParameter("isBlocked", filter.getIsBlocked()); - countQuery.setParameter("isBlocked", filter.getIsBlocked()); + if (filter.getIsBlocked() != null && blockedUserIds != null && !blockedUserIds.isEmpty()) { + query.setParameter("blockedUserIds", blockedUserIds); + countQuery.setParameter("blockedUserIds", blockedUserIds); } if (filter.getSearch() != null && !filter.getSearch().trim().isEmpty()) { diff --git a/src/main/java/com/xtraction/api/admin/repository/OtpRepository.java b/src/main/java/com/xtraction/api/admin/repository/OtpRepository.java deleted file mode 100644 index 2f33ba3..0000000 --- a/src/main/java/com/xtraction/api/admin/repository/OtpRepository.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.xtraction.api.admin.repository; - -import com.xtraction.api.admin.model.Otp; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.data.jpa.repository.Modifying; -import org.springframework.data.jpa.repository.Query; -import org.springframework.data.repository.query.Param; -import org.springframework.stereotype.Repository; - -import java.time.OffsetDateTime; -import java.util.List; -import java.util.Optional; - -@Repository -public interface OtpRepository extends JpaRepository { - Optional findByOtpCodeAndIsExpiredFalseAndIsUsedFalse(String otpCode); - - // find active OTPs - @Query("SELECT o FROM Otp o WHERE o.isExpired = false AND o.isUsed = false ORDER BY o.createdAt DESC") - List findActiveOtps(); - - @Query("SELECT o FROM Otp o WHERE o.isExpired = false AND o.isUsed = false ORDER BY o.createdAt DESC") - org.springframework.data.domain.Page findActiveOtps(org.springframework.data.domain.Pageable pageable); - - /** - * Bulk update to mark OTPs as expired when their expiry time has passed - * @param now Current timestamp - * @return Number of OTPs marked as expired - */ - @Modifying - @Query("UPDATE Otp o SET o.isExpired = true, o.updatedAt = :now WHERE o.expiresAt < :now AND o.isExpired = false") - int markExpiredOtps(@Param("now") OffsetDateTime now); - - /** - * Bulk delete OTPs that have been expired for more than the specified threshold - * @param threshold Timestamp threshold (e.g., 24 hours ago) - * @return Number of OTPs deleted - */ - @Modifying - @Query("DELETE FROM Otp o WHERE o.isExpired = true AND o.updatedAt < :threshold") - int deleteExpiredOtpsOlderThan(@Param("threshold") OffsetDateTime threshold); -} diff --git a/src/main/java/com/xtraction/api/admin/service/AdminService.java b/src/main/java/com/xtraction/api/admin/service/AdminService.java index 11aafbc..f3ece0e 100644 --- a/src/main/java/com/xtraction/api/admin/service/AdminService.java +++ b/src/main/java/com/xtraction/api/admin/service/AdminService.java @@ -19,11 +19,8 @@ @RequiredArgsConstructor public class AdminService { private final ChangeUserRoleService changeRoleService; - private final FetchActiveOtpCodes fetchActiveOtpCodes; private final GetAllUsersService getAllUsersService; private final GetUserProfileByAdminService getProfileByAdmin; - private final CreateAdminService createAdminService; - private final GenerateOtpService generateOtpService; private final AdminUserActionService adminUserActionService; private final AdminSubscriptionActionService adminSubscriptionActionService; private final AdminUserStatsService adminUserStatsService; @@ -131,18 +128,6 @@ public XtractionResponse resetUserQuotas(String userId) { return adminSubscriptionActionService.resetUserQuotas(userId); } - public XtractionResponse createAdmin(AdminSignupRequestDto request) { - return createAdminService.createAdminUser(request); - } - - public XtractionResponse> generateOtp(OtpRequestDto request) { - return generateOtpService.generateOtp(request); - } - - public XtractionResponse fetchActiveOtpCodes(int page, int size) { - return fetchActiveOtpCodes.fetchActiveOtpCodes(page, size); - } - public XtractionResponse> getReceipts(ReceiptFilterDto filter, int page, int size) { return adminReceiptListService.getReceipts(filter, page, size); } diff --git a/src/main/java/com/xtraction/api/admin/service/impl/AdminSecurityStatsServiceImpl.java b/src/main/java/com/xtraction/api/admin/service/impl/AdminSecurityStatsServiceImpl.java index bd4d000..3c53832 100644 --- a/src/main/java/com/xtraction/api/admin/service/impl/AdminSecurityStatsServiceImpl.java +++ b/src/main/java/com/xtraction/api/admin/service/impl/AdminSecurityStatsServiceImpl.java @@ -3,7 +3,7 @@ import com.xtraction.api.admin.dto.response.SecurityStatsDto; import com.xtraction.api.admin.interfaces.AdminSecurityStatsService; import com.xtraction.api.identity.auth.datamodel.Role; -import com.xtraction.api.identity.loginattempts.repository.LoginAttemptsRepository; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.core.shared.response.ResponseBuilderService; import com.xtraction.api.core.shared.response.XtractionResponse; import com.xtraction.api.identity.user.repository.UserRepository; @@ -24,7 +24,7 @@ public class AdminSecurityStatsServiceImpl implements AdminSecurityStatsService { private final UserRepository userRepository; - private final LoginAttemptsRepository loginAttemptsRepository; + private final LoginAttemptsService loginAttemptsService; private final ResponseBuilderService responseBuilderService; @Override @@ -32,11 +32,11 @@ public class AdminSecurityStatsServiceImpl implements AdminSecurityStatsService public XtractionResponse getSecurityStats() { log.info("Fetching admin security statistics"); - long activeBans = loginAttemptsRepository.countByIsBlockedTrue(); + long activeBans = loginAttemptsService.getBlockedUsersCount(); long twoFactorEnabledUsers = 0; // Not yet implemented in the user model LocalDateTime twentyFourHoursAgo = LocalDateTime.now().minusHours(24); - long recentFailedLogins = loginAttemptsRepository.sumFailedLoginsSince(twentyFourHoursAgo); + long recentFailedLogins = loginAttemptsService.getRecentFailedLoginsCount(twentyFourHoursAgo); List rolesRaw = userRepository.countByRoleGrouped(); Map userRoles = new LinkedHashMap<>(); diff --git a/src/main/java/com/xtraction/api/admin/service/impl/AdminUserActionServiceImpl.java b/src/main/java/com/xtraction/api/admin/service/impl/AdminUserActionServiceImpl.java index 639b7a1..06480b5 100644 --- a/src/main/java/com/xtraction/api/admin/service/impl/AdminUserActionServiceImpl.java +++ b/src/main/java/com/xtraction/api/admin/service/impl/AdminUserActionServiceImpl.java @@ -10,6 +10,7 @@ import com.xtraction.api.identity.user.interfaces.userimpl.PasswordResetService; import com.xtraction.api.identity.user.model.User; import com.xtraction.api.identity.user.repository.UserRepository; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -25,6 +26,7 @@ public class AdminUserActionServiceImpl implements AdminUserActionService { private final UserRepository userRepository; private final PasswordResetService passwordResetService; private final JwtTokenProvider jwtTokenProvider; + private final LoginAttemptsService loginAttemptsService; @Override @Transactional @@ -56,11 +58,7 @@ public XtractionResponse forceVerifyEmail(String userId) { @Transactional public XtractionResponse unlockUser(String userId) { User user = getUser(userId); - if (user.getLoginAttempts() != null) { - user.getLoginAttempts().setLoginAttempts(0); - user.getLoginAttempts().setBlockedUntil(null); - } - userRepository.save(user); + loginAttemptsService.resetLoginAttempts(user); log.info("Admin unlocked user {}", userId); return new XtractionResponse<>(200, "success", "User account unlocked", null); diff --git a/src/main/java/com/xtraction/api/admin/service/impl/AdminUserStatsServiceImpl.java b/src/main/java/com/xtraction/api/admin/service/impl/AdminUserStatsServiceImpl.java index d4c7e18..88e59af 100644 --- a/src/main/java/com/xtraction/api/admin/service/impl/AdminUserStatsServiceImpl.java +++ b/src/main/java/com/xtraction/api/admin/service/impl/AdminUserStatsServiceImpl.java @@ -2,7 +2,7 @@ import com.xtraction.api.admin.dto.response.UserStatsDto; import com.xtraction.api.admin.interfaces.AdminUserStatsService; -import com.xtraction.api.identity.loginattempts.repository.LoginAttemptsRepository; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.identity.user.repository.UserRepository; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -22,7 +22,7 @@ public class AdminUserStatsServiceImpl implements AdminUserStatsService { private final UserRepository userRepository; - private final LoginAttemptsRepository loginAttemptsRepository; + private final LoginAttemptsService loginAttemptsService; @Override @Transactional(readOnly = true) @@ -40,7 +40,7 @@ public UserStatsDto getUserStatistics() { long inactiveUsers = userRepository.countByIsActiveFalseAndDeletedAtIsNull(); long verifiedUsers = userRepository.countByIsVerifiedTrueAndDeletedAtIsNull(); long unverifiedUsers = userRepository.countByIsVerifiedFalseAndDeletedAtIsNull(); - long blockedUsers = loginAttemptsRepository.countByIsBlockedTrue(); + long blockedUsers = loginAttemptsService.getBlockedUsersCount(); long softDeletedUsers = userRepository.countByDeletedAtIsNotNull(); // --- Activity windows --- diff --git a/src/main/java/com/xtraction/api/core/metrics/dashboard/service/impl/DashboardMetricsCacheService.java b/src/main/java/com/xtraction/api/core/metrics/dashboard/service/impl/DashboardMetricsCacheService.java index 8ae56a9..2481822 100644 --- a/src/main/java/com/xtraction/api/core/metrics/dashboard/service/impl/DashboardMetricsCacheService.java +++ b/src/main/java/com/xtraction/api/core/metrics/dashboard/service/impl/DashboardMetricsCacheService.java @@ -1,6 +1,6 @@ package com.xtraction.api.core.metrics.dashboard.service.impl; -import com.xtraction.api.identity.loginattempts.repository.LoginAttemptsRepository; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.core.metrics.dashboard.dto.DashboardKpiStatsDto; import com.xtraction.api.billing.subscription.datamodel.SubscriptionPlans; import com.xtraction.api.billing.subscription.repository.UserSubscriptionRepository; @@ -23,7 +23,7 @@ public class DashboardMetricsCacheService { private final UserRepository userRepository; - private final LoginAttemptsRepository loginAttemptsRepository; + private final LoginAttemptsService loginAttemptsService; private final UserSubscriptionRepository userSubscriptionRepository; @Transactional(readOnly = true) @@ -41,7 +41,7 @@ public DashboardKpiStatsDto getDashboardKpiStatsData() { long activeUsers = userRepository.countByIsActiveTrueAndIsVerifiedTrueAndDeletedAtIsNull(); long verifiedUsers = userRepository.countByIsVerifiedTrueAndDeletedAtIsNull(); long unverifiedUsers = userRepository.countByIsVerifiedFalseAndDeletedAtIsNull(); - long blockedUsers = loginAttemptsRepository.countByIsBlockedTrue(); + long blockedUsers = loginAttemptsService.getBlockedUsersCount(); long newUsersToday = userRepository.countByCreatedAtAfterAndDeletedAtIsNull(startOfToday); long newUsersThisWeek = userRepository.countByCreatedAtAfterAndDeletedAtIsNull(startOfWeek); diff --git a/src/main/java/com/xtraction/api/identity/auth/impl/SignupUserImpl.java b/src/main/java/com/xtraction/api/identity/auth/impl/SignupUserImpl.java index 4bc1cbc..a6fb170 100644 --- a/src/main/java/com/xtraction/api/identity/auth/impl/SignupUserImpl.java +++ b/src/main/java/com/xtraction/api/identity/auth/impl/SignupUserImpl.java @@ -20,7 +20,6 @@ import com.xtraction.api.integration.notification.interfaces.NotificationService; import com.xtraction.api.core.shared.response.ResponseBuilderService; import com.xtraction.api.core.shared.response.XtractionResponse; -import com.xtraction.api.identity.loginattempts.model.LoginAttempts; import com.xtraction.api.billing.subscription.impl.AssignSubscriptionService; import com.xtraction.api.billing.subscription.model.UserSubscription; import com.xtraction.api.identity.user.model.User; @@ -101,11 +100,6 @@ public XtractionResponse registerUser(SignupRequestDto request) { userVerification.setEmailVerified(false); user.setUserVerification(userVerification); - // Initialize LoginAttempts for the User - LoginAttempts loginAttempts = new LoginAttempts(); - loginAttempts.setUser(user); - user.setLoginAttempts(loginAttempts); - // Assign default subscription based on user role UserSubscription subscription = assignSubscriptionService.assignDefaultSubscription(user); user.setSubscription(subscription); diff --git a/src/main/java/com/xtraction/api/identity/loginattempts/interfaces/LoginAttemptsService.java b/src/main/java/com/xtraction/api/identity/loginattempts/interfaces/LoginAttemptsService.java index 190c94b..aa9180d 100644 --- a/src/main/java/com/xtraction/api/identity/loginattempts/interfaces/LoginAttemptsService.java +++ b/src/main/java/com/xtraction/api/identity/loginattempts/interfaces/LoginAttemptsService.java @@ -1,9 +1,18 @@ package com.xtraction.api.identity.loginattempts.interfaces; +import com.xtraction.api.identity.loginattempts.model.LoginAttempts; import com.xtraction.api.identity.user.model.User; +import java.time.LocalDateTime; +import java.util.Set; + public interface LoginAttemptsService { void checkIfUserBlocked(User user); void recordFailedLoginAttempt(User user); void resetLoginAttempts(User user); + + LoginAttempts getLoginAttempts(User user); + long getBlockedUsersCount(); + long getRecentFailedLoginsCount(LocalDateTime since); + Set getBlockedUserIds(); } diff --git a/src/main/java/com/xtraction/api/identity/loginattempts/model/LoginAttempts.java b/src/main/java/com/xtraction/api/identity/loginattempts/model/LoginAttempts.java index a6488d8..73fbf94 100644 --- a/src/main/java/com/xtraction/api/identity/loginattempts/model/LoginAttempts.java +++ b/src/main/java/com/xtraction/api/identity/loginattempts/model/LoginAttempts.java @@ -1,43 +1,18 @@ package com.xtraction.api.identity.loginattempts.model; -import com.xtraction.api.identity.user.model.User; -import jakarta.persistence.*; import lombok.AllArgsConstructor; +import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; -import org.hibernate.annotations.CreationTimestamp; -import org.hibernate.annotations.UpdateTimestamp; import java.time.LocalDateTime; @Data -@Entity -@Table(name = "login_attempts") +@Builder @NoArgsConstructor @AllArgsConstructor public class LoginAttempts { - @Id - @GeneratedValue(strategy = GenerationType.UUID) - private String id; - - @OneToOne - @JoinColumn(name = "user_id", referencedColumnName = "id", nullable = false) - private User user; - - @Column(nullable = false, name = "login_attempts") private int loginAttempts = 0; - - @Column(nullable = false, name = "is_blocked") private boolean isBlocked = false; - - @Column(name = "blocked_until") private LocalDateTime blockedUntil; - - @CreationTimestamp - @Column(nullable = false, updatable = false, name = "created_at") - private LocalDateTime createdAt; - - @UpdateTimestamp - @Column(nullable = false, name = "updated_at") - private LocalDateTime updatedAt; } diff --git a/src/main/java/com/xtraction/api/identity/loginattempts/repository/LoginAttemptsRepository.java b/src/main/java/com/xtraction/api/identity/loginattempts/repository/LoginAttemptsRepository.java deleted file mode 100644 index 335b599..0000000 --- a/src/main/java/com/xtraction/api/identity/loginattempts/repository/LoginAttemptsRepository.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.xtraction.api.identity.loginattempts.repository; - -import com.xtraction.api.identity.loginattempts.model.LoginAttempts; -import com.xtraction.api.identity.user.model.User; -import org.springframework.data.jpa.repository.JpaRepository; -import org.springframework.stereotype.Repository; - -import java.util.Optional; - -@Repository -public interface LoginAttemptsRepository extends JpaRepository { - Optional findByUser(User user); - - long countByIsBlockedTrue(); - - @org.springframework.data.jpa.repository.Query("SELECT COALESCE(SUM(l.loginAttempts), 0) FROM LoginAttempts l WHERE l.updatedAt >= :since") - long sumFailedLoginsSince(@org.springframework.data.repository.query.Param("since") java.time.LocalDateTime since); -} diff --git a/src/main/java/com/xtraction/api/identity/loginattempts/service/LoginAttemptsImpl.java b/src/main/java/com/xtraction/api/identity/loginattempts/service/LoginAttemptsImpl.java index 672472a..b8f3e32 100644 --- a/src/main/java/com/xtraction/api/identity/loginattempts/service/LoginAttemptsImpl.java +++ b/src/main/java/com/xtraction/api/identity/loginattempts/service/LoginAttemptsImpl.java @@ -3,39 +3,46 @@ import com.xtraction.api.core.exceptions.custom.ForbiddenException; import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.identity.loginattempts.model.LoginAttempts; -import com.xtraction.api.identity.loginattempts.repository.LoginAttemptsRepository; import com.xtraction.api.identity.user.model.User; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import java.time.Duration; import java.time.LocalDateTime; -import java.util.Optional; +import java.time.ZoneId; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; +import java.util.UUID; @Service @RequiredArgsConstructor +@Slf4j public class LoginAttemptsImpl implements LoginAttemptsService { + private static final int MAX_LOGIN_ATTEMPTS = 4; private static final int LOCKOUT_DURATION_DAYS = 5; - private final LoginAttemptsRepository loginAttemptsRepository; + private static final String USER_KEY_PREFIX = "login_attempts:user:"; + private static final String BLOCKED_USERS_KEY = "login_attempts:blocked_users"; + private static final String FAILED_LOGINS_HISTORY_KEY = "login_attempts:failed_logins_history"; + + private final StringRedisTemplate redisTemplate; @Override public void checkIfUserBlocked(User user) { - Optional attemptsOpt = loginAttemptsRepository.findByUser(user); - if (attemptsOpt.isPresent()) { - LoginAttempts attempts = attemptsOpt.get(); - if ( - attempts.isBlocked() && - attempts.getBlockedUntil() != null && - attempts.getBlockedUntil().isAfter(LocalDateTime.now())) { - - LocalDateTime now = LocalDateTime.now(); - LocalDateTime blockedUntilTime = attempts.getBlockedUntil(); - - Duration remainingDuration = Duration.between(now, blockedUntilTime); - String displayMessage = getDisplayMessage(remainingDuration); - throw new ForbiddenException(displayMessage); - } + LoginAttempts attempts = getLoginAttempts(user); + if (attempts.isBlocked() && + attempts.getBlockedUntil() != null && + attempts.getBlockedUntil().isAfter(LocalDateTime.now())) { + + LocalDateTime now = LocalDateTime.now(); + LocalDateTime blockedUntilTime = attempts.getBlockedUntil(); + + Duration remainingDuration = Duration.between(now, blockedUntilTime); + String displayMessage = getDisplayMessage(remainingDuration); + throw new ForbiddenException(displayMessage); } } @@ -68,12 +75,8 @@ private static String getDisplayMessage(Duration remainingDuration) { @Override public void recordFailedLoginAttempt(User user) { - LoginAttempts attempts = loginAttemptsRepository.findByUser(user) - .orElseGet(() -> { - LoginAttempts newAttempts = new LoginAttempts(); - newAttempts.setUser(user); - return newAttempts; - }); + String key = USER_KEY_PREFIX + user.getId(); + LoginAttempts attempts = getLoginAttempts(user); // Check if block period has expired and reset if needed if (attempts.isBlocked() && @@ -82,18 +85,43 @@ public void recordFailedLoginAttempt(User user) { attempts.setLoginAttempts(0); attempts.setBlocked(false); attempts.setBlockedUntil(null); + redisTemplate.opsForZSet().remove(BLOCKED_USERS_KEY, user.getId()); } - // Now increment the attempt count + // Increment the attempt count attempts.setLoginAttempts(attempts.getLoginAttempts() + 1); + // Record the failed login event in the history ZSET + long nowMillis = System.currentTimeMillis(); + redisTemplate.opsForZSet().add(FAILED_LOGINS_HISTORY_KEY, user.getId() + ":" + UUID.randomUUID(), nowMillis); + pruneFailedLoginsHistory(); + + Map hash = new HashMap<>(); if (attempts.getLoginAttempts() >= MAX_LOGIN_ATTEMPTS) { attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().plusDays(LOCKOUT_DURATION_DAYS)); - loginAttemptsRepository.save(attempts); - throw new ForbiddenException("Your account has been locked. " + "Try again in " + LOCKOUT_DURATION_DAYS + " days."); + LocalDateTime blockedUntil = LocalDateTime.now().plusDays(LOCKOUT_DURATION_DAYS); + attempts.setBlockedUntil(blockedUntil); + + hash.put("attempts", String.valueOf(attempts.getLoginAttempts())); + hash.put("isBlocked", "true"); + hash.put("blockedUntil", blockedUntil.toString()); + + redisTemplate.opsForHash().putAll(key, hash); + redisTemplate.expire(key, Duration.ofDays(LOCKOUT_DURATION_DAYS + 1)); + + // Add to blocked users ZSET with score = epoch millis of blockedUntil + long blockedUntilEpoch = blockedUntil.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + redisTemplate.opsForZSet().add(BLOCKED_USERS_KEY, user.getId(), blockedUntilEpoch); + + throw new ForbiddenException("Your account has been locked. Try again in " + LOCKOUT_DURATION_DAYS + " days."); } else { - loginAttemptsRepository.save(attempts); + hash.put("attempts", String.valueOf(attempts.getLoginAttempts())); + hash.put("isBlocked", "false"); + hash.put("blockedUntil", ""); + + redisTemplate.opsForHash().putAll(key, hash); + redisTemplate.expire(key, Duration.ofHours(24)); + int attemptsRemaining = MAX_LOGIN_ATTEMPTS - attempts.getLoginAttempts(); String attemptWord = attemptsRemaining == 1 ? "attempt" : "attempts"; throw new ForbiddenException("Invalid credentials. You have " + attemptsRemaining + " " + attemptWord + " left."); @@ -102,15 +130,65 @@ public void recordFailedLoginAttempt(User user) { @Override public void resetLoginAttempts(User user) { - Optional attemptsOpt = loginAttemptsRepository.findByUser(user); - if (attemptsOpt.isPresent()) { - LoginAttempts attempts = attemptsOpt.get(); - if (attempts.getLoginAttempts() != 0 || attempts.isBlocked() || attempts.getBlockedUntil() != null) { - attempts.setLoginAttempts(0); - attempts.setBlocked(false); - attempts.setBlockedUntil(null); - loginAttemptsRepository.save(attempts); - } + String key = USER_KEY_PREFIX + user.getId(); + redisTemplate.delete(key); + redisTemplate.opsForZSet().remove(BLOCKED_USERS_KEY, user.getId()); + } + + @Override + public LoginAttempts getLoginAttempts(User user) { + String key = USER_KEY_PREFIX + user.getId(); + Map entries = redisTemplate.opsForHash().entries(key); + if (entries.isEmpty()) { + return LoginAttempts.builder() + .loginAttempts(0) + .isBlocked(false) + .blockedUntil(null) + .build(); } + + int loginAttempts = Integer.parseInt((String) entries.get("attempts")); + boolean isBlocked = Boolean.parseBoolean((String) entries.get("isBlocked")); + String blockedUntilStr = (String) entries.get("blockedUntil"); + LocalDateTime blockedUntil = (blockedUntilStr != null && !blockedUntilStr.isEmpty()) + ? LocalDateTime.parse(blockedUntilStr) + : null; + + return LoginAttempts.builder() + .loginAttempts(loginAttempts) + .isBlocked(isBlocked) + .blockedUntil(blockedUntil) + .build(); + } + + @Override + public long getBlockedUsersCount() { + pruneBlockedUsers(); + Long count = redisTemplate.opsForZSet().zCard(BLOCKED_USERS_KEY); + return count != null ? count : 0L; + } + + @Override + public long getRecentFailedLoginsCount(LocalDateTime since) { + pruneFailedLoginsHistory(); + long sinceEpoch = since.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli(); + Long count = redisTemplate.opsForZSet().count(FAILED_LOGINS_HISTORY_KEY, sinceEpoch, Double.MAX_VALUE); + return count != null ? count : 0L; + } + + @Override + public Set getBlockedUserIds() { + pruneBlockedUsers(); + return redisTemplate.opsForZSet().range(BLOCKED_USERS_KEY, 0, -1); + } + + private void pruneBlockedUsers() { + long now = System.currentTimeMillis(); + redisTemplate.opsForZSet().removeRangeByScore(BLOCKED_USERS_KEY, 0, now); + } + + private void pruneFailedLoginsHistory() { + long twentyFourHoursAgo = System.currentTimeMillis() - Duration.ofDays(1).toMillis(); + redisTemplate.opsForZSet().removeRangeByScore(FAILED_LOGINS_HISTORY_KEY, 0, twentyFourHoursAgo); } } 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 be58069..8a1eec9 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 @@ -3,7 +3,6 @@ import com.xtraction.api.identity.auth.datamodel.Role; import com.xtraction.api.identity.auth.model.UserVerification; import com.xtraction.api.extraction.documents.model.DocumentCollection; -import com.xtraction.api.identity.loginattempts.model.LoginAttempts; import com.xtraction.api.billing.subscription.model.UserSubscription; import jakarta.persistence.*; import lombok.AllArgsConstructor; @@ -87,9 +86,6 @@ public class User implements UserDetails { @Column(name = "organization") private String organization; - @OneToOne(mappedBy = "user", cascade = CascadeType.ALL) - private LoginAttempts loginAttempts; - @OneToOne(mappedBy = "user", cascade = CascadeType.ALL) private UserVerification userVerification; diff --git a/src/main/resources/db/migration/V60__drop_admin_otp_table.sql b/src/main/resources/db/migration/V60__drop_admin_otp_table.sql new file mode 100644 index 0000000..960aa70 --- /dev/null +++ b/src/main/resources/db/migration/V60__drop_admin_otp_table.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS admin_otp CASCADE; diff --git a/src/main/resources/db/migration/V61__drop_login_attempts_table.sql b/src/main/resources/db/migration/V61__drop_login_attempts_table.sql new file mode 100644 index 0000000..ccd7741 --- /dev/null +++ b/src/main/resources/db/migration/V61__drop_login_attempts_table.sql @@ -0,0 +1,2 @@ +-- Drop login_attempts table as tracking is moved to Redis +DROP TABLE IF EXISTS login_attempts CASCADE; diff --git a/src/test/java/com/xtraction/api/admin/service/impl/AdminSecurityStatsServiceImplTest.java b/src/test/java/com/xtraction/api/admin/service/impl/AdminSecurityStatsServiceImplTest.java index d99eb4b..5115780 100644 --- a/src/test/java/com/xtraction/api/admin/service/impl/AdminSecurityStatsServiceImplTest.java +++ b/src/test/java/com/xtraction/api/admin/service/impl/AdminSecurityStatsServiceImplTest.java @@ -2,7 +2,7 @@ import com.xtraction.api.admin.dto.response.SecurityStatsDto; import com.xtraction.api.identity.auth.datamodel.Role; -import com.xtraction.api.identity.loginattempts.repository.LoginAttemptsRepository; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.core.shared.response.ResponseBuilderService; import com.xtraction.api.core.shared.response.XtractionResponse; import com.xtraction.api.identity.user.repository.UserRepository; @@ -32,7 +32,7 @@ class AdminSecurityStatsServiceImplTest { private UserRepository userRepository; @Mock - private LoginAttemptsRepository loginAttemptsRepository; + private LoginAttemptsService loginAttemptsService; @Mock private ResponseBuilderService responseBuilderService; @@ -47,8 +47,8 @@ void setUp() { @Test void getSecurityStats_Success() { // Arrange - when(loginAttemptsRepository.countByIsBlockedTrue()).thenReturn(15L); - when(loginAttemptsRepository.sumFailedLoginsSince(any(LocalDateTime.class))).thenReturn(45L); + when(loginAttemptsService.getBlockedUsersCount()).thenReturn(15L); + when(loginAttemptsService.getRecentFailedLoginsCount(any(LocalDateTime.class))).thenReturn(45L); List rolesRaw = new ArrayList<>(); rolesRaw.add(new Object[]{Role.USER, 1000L}); diff --git a/src/test/java/com/xtraction/api/admin/service/impl/AdminUserActionServiceImplTest.java b/src/test/java/com/xtraction/api/admin/service/impl/AdminUserActionServiceImplTest.java index e7b3c98..b8581ad 100644 --- a/src/test/java/com/xtraction/api/admin/service/impl/AdminUserActionServiceImplTest.java +++ b/src/test/java/com/xtraction/api/admin/service/impl/AdminUserActionServiceImplTest.java @@ -3,7 +3,7 @@ import com.xtraction.api.admin.dto.request.ActionReasonDto; import com.xtraction.api.identity.auth.dto.LoginData; import com.xtraction.api.core.exceptions.custom.NotFoundException; -import com.xtraction.api.identity.loginattempts.model.LoginAttempts; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.core.security.JwtTokenProvider; import com.xtraction.api.core.shared.response.XtractionResponse; import com.xtraction.api.identity.user.dto.request.ForgotPasswordDto; @@ -36,6 +36,9 @@ public class AdminUserActionServiceImplTest { @Mock private JwtTokenProvider jwtTokenProvider; + @Mock + private LoginAttemptsService loginAttemptsService; + @InjectMocks private AdminUserActionServiceImpl testClass; @@ -87,16 +90,12 @@ void forceVerifyEmail_NotVerified() { @Test void unlockUser() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setLoginAttempts(5); - sampleUser.setLoginAttempts(attempts); when(userRepository.findById(userId)).thenReturn(Optional.of(sampleUser)); XtractionResponse response = testClass.unlockUser(userId); - assertEquals(0, sampleUser.getLoginAttempts().getLoginAttempts()); - assertNull(sampleUser.getLoginAttempts().getBlockedUntil()); - verify(userRepository).save(sampleUser); + verify(loginAttemptsService).resetLoginAttempts(sampleUser); + verify(userRepository, never()).save(any(User.class)); } @Test diff --git a/src/test/java/com/xtraction/api/admin/service/impl/AdminUserStatsServiceImplTest.java b/src/test/java/com/xtraction/api/admin/service/impl/AdminUserStatsServiceImplTest.java index 46bb799..d4fe36a 100644 --- a/src/test/java/com/xtraction/api/admin/service/impl/AdminUserStatsServiceImplTest.java +++ b/src/test/java/com/xtraction/api/admin/service/impl/AdminUserStatsServiceImplTest.java @@ -2,7 +2,7 @@ import com.xtraction.api.admin.dto.response.UserStatsDto; import com.xtraction.api.identity.auth.datamodel.Role; -import com.xtraction.api.identity.loginattempts.repository.LoginAttemptsRepository; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.identity.user.repository.UserRepository; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -27,7 +27,7 @@ class AdminUserStatsServiceImplTest { private UserRepository userRepository; @Mock - private LoginAttemptsRepository loginAttemptsRepository; + private LoginAttemptsService loginAttemptsService; @InjectMocks private AdminUserStatsServiceImpl testClass; @@ -47,7 +47,7 @@ void setUp() { when(userRepository.countByIsActiveFalseAndDeletedAtIsNull()).thenReturn(20L); when(userRepository.countByIsVerifiedTrueAndDeletedAtIsNull()).thenReturn(75L); when(userRepository.countByIsVerifiedFalseAndDeletedAtIsNull()).thenReturn(25L); - when(loginAttemptsRepository.countByIsBlockedTrue()).thenReturn(3L); + when(loginAttemptsService.getBlockedUsersCount()).thenReturn(3L); when(userRepository.countByDeletedAtIsNotNull()).thenReturn(5L); when(userRepository.countByMarketingOptInTrueAndDeletedAtIsNull()).thenReturn(40L); diff --git a/src/test/java/com/xtraction/api/admin/service/impl/GetUserProfileByAdminTest.java b/src/test/java/com/xtraction/api/admin/service/impl/GetUserProfileByAdminTest.java index f6b835d..309968a 100644 --- a/src/test/java/com/xtraction/api/admin/service/impl/GetUserProfileByAdminTest.java +++ b/src/test/java/com/xtraction/api/admin/service/impl/GetUserProfileByAdminTest.java @@ -8,6 +8,7 @@ import com.xtraction.api.core.shared.response.XtractionResponse; import com.xtraction.api.identity.user.model.User; import com.xtraction.api.identity.user.repository.UserRepository; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -37,6 +38,9 @@ public class GetUserProfileByAdminTest { @Mock private UserCreditBalanceRepository creditBalanceRepository; + @Mock + private LoginAttemptsService loginAttemptsService; + @InjectMocks private GetUserProfileByAdmin getUserProfileByAdmin; @@ -66,6 +70,7 @@ void shouldReturnUserProfileWhenUserExists() { // Arrange when(userRepository.findById(USER_ID)).thenReturn(Optional.of(mockUser)); when(creditBalanceRepository.findByUserId(USER_ID)).thenReturn(Optional.empty()); + when(loginAttemptsService.getLoginAttempts(mockUser)).thenReturn(null); when(responseBuilder.buildUserResponse( any(AdminUserDetailDto.class), eq(HttpStatus.OK), diff --git a/src/test/java/com/xtraction/api/admin/service/impl/OtpCleanupServiceImplTest.java b/src/test/java/com/xtraction/api/admin/service/impl/OtpCleanupServiceImplTest.java deleted file mode 100644 index 65fe577..0000000 --- a/src/test/java/com/xtraction/api/admin/service/impl/OtpCleanupServiceImplTest.java +++ /dev/null @@ -1,127 +0,0 @@ -package com.xtraction.api.admin.service.impl; - -import com.xtraction.api.admin.impl.OtpCleanupServiceImpl; -import com.xtraction.api.admin.repository.OtpRepository; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.jupiter.MockitoExtension; - -import java.time.OffsetDateTime; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.*; - -@ExtendWith(MockitoExtension.class) -class OtpCleanupServiceImplTest { - - @Mock - private OtpRepository otpRepository; - - @InjectMocks - private OtpCleanupServiceImpl otpCleanupService; - - @BeforeEach - void setUp() { - // Reset mocks before each test - reset(otpRepository); - } - - @Test - void markExpiredOtps_ShouldMarkExpiredOtps_WhenExpiredOtpsExist() { - // Arrange - int expectedUpdatedCount = 5; - when(otpRepository.markExpiredOtps(any(OffsetDateTime.class))) - .thenReturn(expectedUpdatedCount); - - // Act - otpCleanupService.markExpiredOtps(); - - // Assert - verify(otpRepository, times(1)).markExpiredOtps(any(OffsetDateTime.class)); - } - - @Test - void markExpiredOtps_ShouldNotThrowException_WhenNoExpiredOtpsExist() { - // Arrange - when(otpRepository.markExpiredOtps(any(OffsetDateTime.class))) - .thenReturn(0); - - // Act & Assert - should not throw exception - otpCleanupService.markExpiredOtps(); - - verify(otpRepository, times(1)).markExpiredOtps(any(OffsetDateTime.class)); - } - - @Test - void markExpiredOtps_ShouldHandleExceptionGracefully() { - // Arrange - when(otpRepository.markExpiredOtps(any(OffsetDateTime.class))) - .thenThrow(new RuntimeException("Database error")); - - // Act & Assert - should not propagate exception - otpCleanupService.markExpiredOtps(); - - verify(otpRepository, times(1)).markExpiredOtps(any(OffsetDateTime.class)); - } - - @Test - void deleteOldExpiredOtps_ShouldDeleteOldOtps_WhenOldExpiredOtpsExist() { - // Arrange - int expectedDeletedCount = 3; - when(otpRepository.deleteExpiredOtpsOlderThan(any(OffsetDateTime.class))) - .thenReturn(expectedDeletedCount); - - // Act - otpCleanupService.deleteOldExpiredOtps(); - - // Assert - verify(otpRepository, times(1)).deleteExpiredOtpsOlderThan(any(OffsetDateTime.class)); - } - - @Test - void deleteOldExpiredOtps_ShouldNotThrowException_WhenNoOldExpiredOtpsExist() { - // Arrange - when(otpRepository.deleteExpiredOtpsOlderThan(any(OffsetDateTime.class))) - .thenReturn(0); - - // Act & Assert - should not throw exception - otpCleanupService.deleteOldExpiredOtps(); - - verify(otpRepository, times(1)).deleteExpiredOtpsOlderThan(any(OffsetDateTime.class)); - } - - @Test - void deleteOldExpiredOtps_ShouldHandleExceptionGracefully() { - // Arrange - when(otpRepository.deleteExpiredOtpsOlderThan(any(OffsetDateTime.class))) - .thenThrow(new RuntimeException("Database error")); - - // Act & Assert - should not propagate exception - otpCleanupService.deleteOldExpiredOtps(); - - verify(otpRepository, times(1)).deleteExpiredOtpsOlderThan(any(OffsetDateTime.class)); - } - - @Test - void deleteOldExpiredOtps_ShouldUse24HourThreshold() { - // Arrange - when(otpRepository.deleteExpiredOtpsOlderThan(any(OffsetDateTime.class))) - .thenReturn(2); - - // Act - otpCleanupService.deleteOldExpiredOtps(); - - // Assert - verify that the threshold is approximately 24 hours ago - verify(otpRepository, times(1)).deleteExpiredOtpsOlderThan( - argThat(threshold -> { - OffsetDateTime expectedThreshold = OffsetDateTime.now().minusHours(24); - // Allow 1 minute tolerance for test execution time - return Math.abs(threshold.toEpochSecond() - expectedThreshold.toEpochSecond()) < 60; - }) - ); - } -} - diff --git a/src/test/java/com/xtraction/api/billing/payment/receipt/events/ReceiptEventPublisherTest.java b/src/test/java/com/xtraction/api/billing/payment/receipt/events/ReceiptEventPublisherTest.java index c8a1c44..ff2c311 100644 --- a/src/test/java/com/xtraction/api/billing/payment/receipt/events/ReceiptEventPublisherTest.java +++ b/src/test/java/com/xtraction/api/billing/payment/receipt/events/ReceiptEventPublisherTest.java @@ -53,7 +53,7 @@ void shouldPublishReceiptRequestToKafka() { when(receiptEventMapper.toReceiptRequestedEvent(any(ReceiptData.class))).thenReturn(event); when(kafkaMessageProducer.send(any())).thenReturn( - CompletableFuture.completedFuture(MessageResult.success("msg-id", "unraveldocs-receipts", 0, 0L))); + CompletableFuture.completedFuture(MessageResult.success("msg-id", "xtraction-receipts", 0, 0L))); // When receiptEventPublisher.publishReceiptRequest(receiptData); @@ -67,7 +67,7 @@ void shouldPublishReceiptRequestToKafka() { verify(kafkaMessageProducer).send(messageCaptor.capture()); Message> capturedMessage = messageCaptor.getValue(); - assertThat(capturedMessage.topic()).isEqualTo("unraveldocs-receipts"); + assertThat(capturedMessage.topic()).isEqualTo("xtraction-receipts"); assertThat(capturedMessage.key()).isEqualTo("pi_test123"); assertThat(capturedMessage.payload().getPayload()).isEqualTo(event); assertThat(capturedMessage.payload().getMetadata().getEventType()).isEqualTo("ReceiptRequested"); @@ -82,7 +82,7 @@ void shouldUseExternalPaymentIdAsPartitionKey() { when(receiptEventMapper.toReceiptRequestedEvent(any(ReceiptData.class))).thenReturn(event); when(kafkaMessageProducer.send(any())).thenReturn( - CompletableFuture.completedFuture(MessageResult.success("msg-id", "unraveldocs-receipts", 0, 0L))); + CompletableFuture.completedFuture(MessageResult.success("msg-id", "xtraction-receipts", 0, 0L))); // When receiptEventPublisher.publishReceiptRequest(receiptData); diff --git a/src/test/java/com/xtraction/api/core/metrics/dashboard/service/impl/DashboardMetricsServiceImplTest.java b/src/test/java/com/xtraction/api/core/metrics/dashboard/service/impl/DashboardMetricsServiceImplTest.java index 267d809..eba7ce5 100644 --- a/src/test/java/com/xtraction/api/core/metrics/dashboard/service/impl/DashboardMetricsServiceImplTest.java +++ b/src/test/java/com/xtraction/api/core/metrics/dashboard/service/impl/DashboardMetricsServiceImplTest.java @@ -1,6 +1,6 @@ package com.xtraction.api.core.metrics.dashboard.service.impl; -import com.xtraction.api.identity.loginattempts.repository.LoginAttemptsRepository; +import com.xtraction.api.identity.loginattempts.interfaces.LoginAttemptsService; import com.xtraction.api.core.metrics.dashboard.dto.DashboardKpiStatsDto; import com.xtraction.api.billing.subscription.datamodel.SubscriptionPlans; import com.xtraction.api.billing.subscription.repository.UserSubscriptionRepository; @@ -26,7 +26,7 @@ class DashboardMetricsServiceImplTest { private UserRepository userRepository; @Mock - private LoginAttemptsRepository loginAttemptsRepository; + private LoginAttemptsService loginAttemptsService; @Mock private UserSubscriptionRepository userSubscriptionRepository; @@ -41,7 +41,7 @@ void getDashboardKpiStatsData_returnsCorrectMetrics_whenDataExists() { when(userRepository.countByIsActiveTrueAndIsVerifiedTrueAndDeletedAtIsNull()).thenReturn(80L); when(userRepository.countByIsVerifiedTrueAndDeletedAtIsNull()).thenReturn(90L); when(userRepository.countByIsVerifiedFalseAndDeletedAtIsNull()).thenReturn(10L); - when(loginAttemptsRepository.countByIsBlockedTrue()).thenReturn(5L); + when(loginAttemptsService.getBlockedUsersCount()).thenReturn(5L); when(userRepository.countByCreatedAtAfterAndDeletedAtIsNull(any())).thenReturn(5L, 15L, 30L); when(userRepository.countByLastLoginAfterAndDeletedAtIsNull(any())).thenReturn(20L, 50L, 85L); @@ -103,7 +103,7 @@ void getDashboardKpiStatsData_handlesNullAndEmptyData_correctly() { when(userRepository.countByIsActiveTrueAndIsVerifiedTrueAndDeletedAtIsNull()).thenReturn(0L); when(userRepository.countByIsVerifiedTrueAndDeletedAtIsNull()).thenReturn(0L); when(userRepository.countByIsVerifiedFalseAndDeletedAtIsNull()).thenReturn(0L); - when(loginAttemptsRepository.countByIsBlockedTrue()).thenReturn(0L); + when(loginAttemptsService.getBlockedUsersCount()).thenReturn(0L); when(userRepository.countByCreatedAtAfterAndDeletedAtIsNull(any())).thenReturn(0L); when(userRepository.countByLastLoginAfterAndDeletedAtIsNull(any())).thenReturn(0L); diff --git a/src/test/java/com/xtraction/api/identity/auth/service/impl/SignupUserImplTest.java b/src/test/java/com/xtraction/api/identity/auth/service/impl/SignupUserImplTest.java index 45dccbe..7f41a31 100644 --- a/src/test/java/com/xtraction/api/identity/auth/service/impl/SignupUserImplTest.java +++ b/src/test/java/com/xtraction/api/identity/auth/service/impl/SignupUserImplTest.java @@ -13,7 +13,6 @@ import com.xtraction.api.billing.credit.service.CreditBalanceService; import com.xtraction.api.core.shared.response.ResponseBuilderService; import com.xtraction.api.core.shared.response.XtractionResponse; -import com.xtraction.api.identity.loginattempts.model.LoginAttempts; import com.xtraction.api.billing.subscription.impl.AssignSubscriptionService; import com.xtraction.api.billing.subscription.model.UserSubscription; import com.xtraction.api.identity.user.model.User; @@ -204,7 +203,7 @@ void registerUser_PasswordSameAsEmail_ThrowsBadRequestException() { } @Test - void registerUser_VerificationDetailsAndLoginAttemptsSetCorrectly() { + void registerUser_VerificationDetailsSetCorrectly() { // Arrange setupCommonMocks(); @@ -214,18 +213,10 @@ void registerUser_VerificationDetailsAndLoginAttemptsSetCorrectly() { // Assert verify(userRepository).save(argThat(u -> { UserVerification verification = u.getUserVerification(); - boolean verificationCorrect = verification != null && + return verification != null && verification.getUser() == u && verification.getEmailVerificationToken().equals("verificationToken") && verification.getEmailVerificationTokenExpiry().equals(expiryDate); - - LoginAttempts loginAttempts = u.getLoginAttempts(); - boolean loginAttemptsCorrect = loginAttempts != null && - loginAttempts.getUser() == u && - loginAttempts.getLoginAttempts() == 0 && - !loginAttempts.isBlocked(); - - return verificationCorrect && loginAttemptsCorrect; })); } } diff --git a/src/test/java/com/xtraction/api/identity/loginattempts/service/LoginAttemptsImplTest.java b/src/test/java/com/xtraction/api/identity/loginattempts/service/LoginAttemptsImplTest.java index bd083ed..47d5a73 100644 --- a/src/test/java/com/xtraction/api/identity/loginattempts/service/LoginAttemptsImplTest.java +++ b/src/test/java/com/xtraction/api/identity/loginattempts/service/LoginAttemptsImplTest.java @@ -2,29 +2,42 @@ import com.xtraction.api.core.exceptions.custom.ForbiddenException; import com.xtraction.api.identity.loginattempts.model.LoginAttempts; -import com.xtraction.api.identity.loginattempts.repository.LoginAttemptsRepository; import com.xtraction.api.identity.user.model.User; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; -import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.data.redis.core.ZSetOperations; +import java.time.Duration; import java.time.LocalDateTime; import java.time.temporal.ChronoUnit; -import java.util.Optional; +import java.util.Collections; +import java.util.Map; +import java.util.Set; import static org.junit.jupiter.api.Assertions.*; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyDouble; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.*; @ExtendWith(MockitoExtension.class) class LoginAttemptsImplTest { @Mock - private LoginAttemptsRepository loginAttemptsRepository; + private StringRedisTemplate redisTemplate; + + @Mock + private HashOperations hashOperations; + + @Mock + private ZSetOperations zSetOperations; @InjectMocks private LoginAttemptsImpl loginAttemptsService; @@ -33,6 +46,9 @@ class LoginAttemptsImplTest { @BeforeEach void setUp() { + lenient().when(redisTemplate.opsForHash()).thenReturn(hashOperations); + lenient().when(redisTemplate.opsForZSet()).thenReturn(zSetOperations); + user = new User(); user.setId("1"); user.setEmail("test@example.com"); @@ -40,36 +56,40 @@ void setUp() { @Test void checkIfUserBlocked_whenUserNotFound_shouldNotThrowException() { - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.empty()); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(Collections.emptyMap()); assertDoesNotThrow(() -> loginAttemptsService.checkIfUserBlocked(user)); } @Test void checkIfUserBlocked_whenUserNotBlocked_shouldNotThrowException() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setBlocked(false); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); + Map entries = Map.of( + "attempts", "0", + "isBlocked", "false", + "blockedUntil", "" + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); assertDoesNotThrow(() -> loginAttemptsService.checkIfUserBlocked(user)); } @Test void checkIfUserBlocked_whenUserBlockedAndBlockExpired_shouldNotThrowException() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().minusDays(1)); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); + Map entries = Map.of( + "attempts", "4", + "isBlocked", "true", + "blockedUntil", LocalDateTime.now().minusDays(1).toString() + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); assertDoesNotThrow(() -> loginAttemptsService.checkIfUserBlocked(user)); } @Test void checkIfUserBlocked_whenUserBlocked_DaysRemaining_shouldThrowForbiddenException() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().plusDays(2).plusHours(1)); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); + Map entries = Map.of( + "attempts", "4", + "isBlocked", "true", + "blockedUntil", LocalDateTime.now().plusDays(2).plusHours(1).toString() + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.checkIfUserBlocked(user)); @@ -80,11 +100,12 @@ void checkIfUserBlocked_whenUserBlocked_DaysRemaining_shouldThrowForbiddenExcept @Test void checkIfUserBlocked_whenUserBlocked_HoursRemaining_shouldThrowForbiddenException() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().plusHours(3).plusMinutes(10)); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); + Map entries = Map.of( + "attempts", "4", + "isBlocked", "true", + "blockedUntil", LocalDateTime.now().plusHours(3).plusMinutes(10).toString() + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.checkIfUserBlocked(user)); @@ -95,11 +116,12 @@ void checkIfUserBlocked_whenUserBlocked_HoursRemaining_shouldThrowForbiddenExcep @Test void checkIfUserBlocked_whenUserBlocked_MinutesRemaining_shouldThrowForbiddenException() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().plusMinutes(30).plusSeconds(10)); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); + Map entries = Map.of( + "attempts", "4", + "isBlocked", "true", + "blockedUntil", LocalDateTime.now().plusMinutes(30).plusSeconds(10).toString() + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.checkIfUserBlocked(user)); @@ -110,11 +132,12 @@ void checkIfUserBlocked_whenUserBlocked_MinutesRemaining_shouldThrowForbiddenExc @Test void checkIfUserBlocked_whenUserBlocked_LessThanOneMinuteRemaining_shouldThrowForbiddenExceptionWithOneMinute() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().plusSeconds(30)); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); + Map entries = Map.of( + "attempts", "4", + "isBlocked", "true", + "blockedUntil", LocalDateTime.now().plusSeconds(30).toString() + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.checkIfUserBlocked(user)); @@ -125,12 +148,12 @@ void checkIfUserBlocked_whenUserBlocked_LessThanOneMinuteRemaining_shouldThrowFo @Test void checkIfUserBlocked_whenUserBlocked_ZeroOrNegativeSecondsRemaining_shouldThrowForbiddenExceptionWithOneMinute() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setBlocked(true); - LocalDateTime testStartTime = LocalDateTime.now(); - attempts.setBlockedUntil(testStartTime.plus(500, ChronoUnit.MILLIS)); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); + Map entries = Map.of( + "attempts", "4", + "isBlocked", "true", + "blockedUntil", LocalDateTime.now().plus(500, ChronoUnit.MILLIS).toString() + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.checkIfUserBlocked(user)); @@ -139,141 +162,98 @@ void checkIfUserBlocked_whenUserBlocked_ZeroOrNegativeSecondsRemaining_shouldThr "Exception message was: " + exception.getMessage() + ", expected to contain: " + expectedMessagePart); } - @Test void recordFailedLoginAttempt_newUser_shouldCreateRecordAndThrowException() { - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.empty()); - ArgumentCaptor attemptsCaptor = ArgumentCaptor.forClass(LoginAttempts.class); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(Collections.emptyMap()); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.recordFailedLoginAttempt(user)); - verify(loginAttemptsRepository).save(attemptsCaptor.capture()); - LoginAttempts savedAttempts = attemptsCaptor.getValue(); - assertEquals(1, savedAttempts.getLoginAttempts()); - assertFalse(savedAttempts.isBlocked()); - assertNull(savedAttempts.getBlockedUntil()); - assertEquals(user, savedAttempts.getUser()); + verify(hashOperations).putAll(eq("login_attempts:user:1"), anyMap()); + verify(redisTemplate).expire("login_attempts:user:1", Duration.ofHours(24)); + verify(zSetOperations).add(eq("login_attempts:failed_logins_history"), anyString(), anyDouble()); assertTrue(exception.getMessage().contains("Invalid credentials. You have 3 attempts left.")); } @Test void recordFailedLoginAttempt_existingUser_belowMaxAttempts_shouldIncrementAndThrowException() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setLoginAttempts(1); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); - ArgumentCaptor attemptsCaptor = ArgumentCaptor.forClass(LoginAttempts.class); + Map entries = Map.of( + "attempts", "1", + "isBlocked", "false", + "blockedUntil", "" + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.recordFailedLoginAttempt(user)); - verify(loginAttemptsRepository).save(attemptsCaptor.capture()); - LoginAttempts savedAttempts = attemptsCaptor.getValue(); - assertEquals(2, savedAttempts.getLoginAttempts()); - assertFalse(savedAttempts.isBlocked()); + verify(hashOperations).putAll(eq("login_attempts:user:1"), anyMap()); + verify(redisTemplate).expire("login_attempts:user:1", Duration.ofHours(24)); assertTrue(exception.getMessage().contains("Invalid credentials. You have 2 attempts left.")); } @Test void recordFailedLoginAttempt_existingUser_reachesMaxAttempts_shouldBlockAndThrowException() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setLoginAttempts(3); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); - ArgumentCaptor attemptsCaptor = ArgumentCaptor.forClass(LoginAttempts.class); + Map entries = Map.of( + "attempts", "3", + "isBlocked", "false", + "blockedUntil", "" + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.recordFailedLoginAttempt(user)); - verify(loginAttemptsRepository).save(attemptsCaptor.capture()); - LoginAttempts savedAttempts = attemptsCaptor.getValue(); - assertEquals(4, savedAttempts.getLoginAttempts()); - assertTrue(savedAttempts.isBlocked()); - assertNotNull(savedAttempts.getBlockedUntil()); + verify(hashOperations).putAll(eq("login_attempts:user:1"), anyMap()); + verify(redisTemplate).expire("login_attempts:user:1", Duration.ofDays(6)); + verify(zSetOperations).add(eq("login_attempts:blocked_users"), eq("1"), anyDouble()); assertTrue(exception.getMessage().contains("Your account has been locked. Try again in 5 days.")); } @Test void recordFailedLoginAttempt_blockedUserWithExpiredBlock_shouldResetBlockAndRecordAttempt() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setLoginAttempts(0); - attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().minusDays(1)); - - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); - ArgumentCaptor attemptsCaptor = ArgumentCaptor.forClass(LoginAttempts.class); + Map entries = Map.of( + "attempts", "4", + "isBlocked", "true", + "blockedUntil", LocalDateTime.now().minusDays(1).toString() + ); + when(hashOperations.entries("login_attempts:user:1")).thenReturn(entries); ForbiddenException exception = assertThrows(ForbiddenException.class, () -> loginAttemptsService.recordFailedLoginAttempt(user)); - verify(loginAttemptsRepository).save(attemptsCaptor.capture()); - LoginAttempts savedAttempts = attemptsCaptor.getValue(); - - assertEquals(1, savedAttempts.getLoginAttempts()); - assertFalse(savedAttempts.isBlocked(), "Block should be reset as it was expired"); - assertNull(savedAttempts.getBlockedUntil(), "BlockedUntil should be null after reset"); + verify(zSetOperations).remove("login_attempts:blocked_users", "1"); + verify(hashOperations).putAll(eq("login_attempts:user:1"), anyMap()); assertTrue(exception.getMessage().contains("Invalid credentials. You have 3 attempts left.")); } - @Test - void resetLoginAttempts_userNotFound_shouldDoNothing() { - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.empty()); + void resetLoginAttempts_shouldResetAndSave() { loginAttemptsService.resetLoginAttempts(user); - verify(loginAttemptsRepository, never()).save(any(LoginAttempts.class)); + verify(redisTemplate).delete("login_attempts:user:1"); + verify(zSetOperations).remove("login_attempts:blocked_users", "1"); } @Test - void resetLoginAttempts_userFoundWithAttempts_shouldResetAndSave() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setLoginAttempts(2); - attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().plusDays(1)); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); - ArgumentCaptor attemptsCaptor = ArgumentCaptor.forClass(LoginAttempts.class); - - loginAttemptsService.resetLoginAttempts(user); - - verify(loginAttemptsRepository).save(attemptsCaptor.capture()); - LoginAttempts savedAttempts = attemptsCaptor.getValue(); - assertEquals(0, savedAttempts.getLoginAttempts()); - assertFalse(savedAttempts.isBlocked()); - assertNull(savedAttempts.getBlockedUntil()); + void getBlockedUsersCount_shouldReturnCount() { + when(zSetOperations.zCard("login_attempts:blocked_users")).thenReturn(5L); + assertEquals(5L, loginAttemptsService.getBlockedUsersCount()); + verify(zSetOperations).removeRangeByScore(eq("login_attempts:blocked_users"), eq(0.0), anyDouble()); } @Test - void resetLoginAttempts_userFoundWithNoAttemptsAndNotBlocked_shouldNotSave() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setLoginAttempts(0); - attempts.setBlocked(false); - attempts.setBlockedUntil(null); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); - - loginAttemptsService.resetLoginAttempts(user); - - verify(loginAttemptsRepository, never()).save(any(LoginAttempts.class)); + void getRecentFailedLoginsCount_shouldReturnCount() { + when(zSetOperations.count(eq("login_attempts:failed_logins_history"), anyDouble(), eq(Double.MAX_VALUE))).thenReturn(10L); + assertEquals(10L, loginAttemptsService.getRecentFailedLoginsCount(LocalDateTime.now().minusHours(24))); + verify(zSetOperations).removeRangeByScore(eq("login_attempts:failed_logins_history"), eq(0.0), anyDouble()); } @Test - void resetLoginAttempts_userFoundOnlyBlocked_shouldResetAndSave() { - LoginAttempts attempts = new LoginAttempts(); - attempts.setUser(user); - attempts.setLoginAttempts(0); - attempts.setBlocked(true); - attempts.setBlockedUntil(LocalDateTime.now().plusDays(1)); - when(loginAttemptsRepository.findByUser(user)).thenReturn(Optional.of(attempts)); - ArgumentCaptor attemptsCaptor = ArgumentCaptor.forClass(LoginAttempts.class); - - loginAttemptsService.resetLoginAttempts(user); - - verify(loginAttemptsRepository).save(attemptsCaptor.capture()); - LoginAttempts savedAttempts = attemptsCaptor.getValue(); - assertEquals(0, savedAttempts.getLoginAttempts()); - assertFalse(savedAttempts.isBlocked()); - assertNull(savedAttempts.getBlockedUntil()); + void getBlockedUserIds_shouldReturnIds() { + when(zSetOperations.range("login_attempts:blocked_users", 0, -1)).thenReturn(Set.of("1", "2")); + Set ids = loginAttemptsService.getBlockedUserIds(); + assertEquals(2, ids.size()); + assertTrue(ids.contains("1")); + assertTrue(ids.contains("2")); } }