From dd1dca15b45da68e0ef588d176cd9e8b0fabad91 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:27:15 +0400 Subject: [PATCH 01/51] refactor(config): replace static CORS origins with dynamic local-network check CorsConfig now exposes a CorsConfigurationSource bean instead of a WebMvcConfigurer, so Spring Security's .cors() can intercept pre-flight OPTIONS requests before they hit the security filter chain (the WebMvcConfigurer path does not intercept pre-flight requests at the filter level, which caused 401 responses on cross-origin preflight). The allowed-origin check is dynamic: any request whose Origin header starts with http://localhost: (web frontend dev server), http://10.0.2.2: (Android emulator), http://192.168. or http://10. (physical device on the local network) is accepted. This avoids hardcoding a port or IP that changes with every network switch, following the same pattern used in postify-microservices api-gateway/CustomCorsConfig. --- .../springboottutorial/config/CorsConfig.java | 47 +++++++++++++------ 1 file changed, 32 insertions(+), 15 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/config/CorsConfig.java b/src/main/java/com/edgareldy/springboottutorial/config/CorsConfig.java index 59b1404..0ef06d6 100644 --- a/src/main/java/com/edgareldy/springboottutorial/config/CorsConfig.java +++ b/src/main/java/com/edgareldy/springboottutorial/config/CorsConfig.java @@ -1,17 +1,24 @@ package com.edgareldy.springboottutorial.config; +import java.util.List; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; -import org.springframework.web.servlet.config.annotation.CorsRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; /** - * Allows local frontend dev servers to call the API from the browser - * during development, where the API and the frontend run on different - * origins (different ports). Active only under the "dev" profile: prod - * is expected to define its own, stricter CORS policy when a real - * frontend origin exists. + * CORS configuration active only under the "dev" profile. Dynamically + * allows any origin that is a local address: any frontend dev server on + * localhost ({@code http://localhost:*}), the Android emulator host alias + * ({@code http://10.0.2.2:*}), and physical mobile devices on the same + * LAN ({@code http://192.168.*} and private {@code http://10.*} range). + *

+ * Uses a {@link CorsConfigurationSource} bean so Spring Security's + * {@code .cors()} picks it up directly instead of relying on the Spring MVC + * {@code WebMvcConfigurer} path, which does not intercept pre-flight OPTIONS + * requests before the security filter chain. In prod no bean of this type is + * registered so the reverse proxy is responsible for CORS headers. *

* Created edgar.muhamyangabo on 7/4/26 * Author : edgar.muhamyangabo @@ -23,15 +30,25 @@ public class CorsConfig { @Bean - public WebMvcConfigurer corsConfigurer() { - return new WebMvcConfigurer() { - @Override - public void addCorsMappings(CorsRegistry registry) { - registry.addMapping("/api/**") - .allowedOrigins("http://localhost:3000", "http://localhost:5173") - .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS") - .allowedHeaders("*"); + public CorsConfigurationSource corsConfigurationSource() { + return request -> { + String origin = request.getHeader("Origin"); + if (origin == null || !isLocalOrigin(origin)) { + return null; } + CorsConfiguration config = new CorsConfiguration(); + config.setAllowedOrigins(List.of(origin)); + config.setAllowedMethods(List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); + config.setAllowedHeaders(List.of("*")); + config.setAllowCredentials(true); + return config; }; } + + private boolean isLocalOrigin(String origin) { + return origin.startsWith("http://localhost:") + || origin.startsWith("http://10.0.2.2:") + || origin.startsWith("http://192.168.") + || (origin.startsWith("http://10.") && !origin.startsWith("http://10.0.2.2:")); + } } From 81159ff7c8a974989364547018b71c4c9571d4f1 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:27:57 +0400 Subject: [PATCH 02/51] feat(token): add PasswordResetTokenType enum (LINK/OTP) Discriminates the two password-reset flows: LINK for the web flow (UUID token in a clickable email link, 1-hour TTL) and OTP for the mobile flow (6-digit numeric code entered manually in the app, 5-minute TTL). Storing the type as an enum rather than a bare String makes the distinction explicit in the Java type system and allows the Flyway CHECK constraint (V19) to enforce it at the database level. --- .../entity/token/PasswordResetTokenType.java | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 src/main/java/com/edgareldy/springboottutorial/entity/token/PasswordResetTokenType.java diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/token/PasswordResetTokenType.java b/src/main/java/com/edgareldy/springboottutorial/entity/token/PasswordResetTokenType.java new file mode 100644 index 0000000..656a210 --- /dev/null +++ b/src/main/java/com/edgareldy/springboottutorial/entity/token/PasswordResetTokenType.java @@ -0,0 +1,18 @@ +package com.edgareldy.springboottutorial.entity.token; + +/** + * Discriminates the two password-reset flows. {@code LINK} is used for the + * web flow: a UUID token is embedded in a clickable reset link emailed to the + * user (1-hour TTL). {@code OTP} is used for the mobile flow: a 6-digit + * numeric code is emailed and must be entered manually in the app before + * the user can set a new password (5-minute TTL). + *

+ * Created edgar.muhamyangabo on 11/21/26 + * Author : edgar.muhamyangabo + * Date : 11/21/26 + * Project : spring-boot-tutorial + */ +public enum PasswordResetTokenType { + LINK, + OTP +} From 106c637f20b8127456c9fe8d1688d1e4a9614e87 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:27:57 +0400 Subject: [PATCH 03/51] feat(flyway): V19 migrate password_reset_tokens.type to LINK/OTP values Existing rows used the legacy "PASSWORD_RESET" string; they are updated to "LINK" because they all used the web link flow. A CHECK constraint is then added to enforce that only "LINK" and "OTP" can be stored, matching the new PasswordResetTokenType enum. --- .../V19__update_password_reset_token_type.sql | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 src/main/resources/db/migration/V19__update_password_reset_token_type.sql diff --git a/src/main/resources/db/migration/V19__update_password_reset_token_type.sql b/src/main/resources/db/migration/V19__update_password_reset_token_type.sql new file mode 100644 index 0000000..9002b3d --- /dev/null +++ b/src/main/resources/db/migration/V19__update_password_reset_token_type.sql @@ -0,0 +1,14 @@ +-- Migrate existing password_reset_tokens.type values from the legacy +-- "PASSWORD_RESET" string to "LINK" (the web link flow). Any in-flight +-- rows from before this migration used the web link behaviour, so LINK +-- is the correct semantic mapping. A CHECK constraint is then added so +-- only the two valid discriminators ("LINK", "OTP") can be stored going +-- forward, matching the PasswordResetTokenType Java enum. + +UPDATE password_reset_tokens + SET type = 'LINK' + WHERE type = 'PASSWORD_RESET'; + +ALTER TABLE password_reset_tokens + ADD CONSTRAINT chk_password_reset_token_type + CHECK (type IN ('LINK', 'OTP')); From 604140e88441b9d80b0543038f1716576c7b616e Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:30:47 +0400 Subject: [PATCH 04/51] feat(security): add generateOtp(int length) to SecureTokenGenerator Adds a numeric OTP generator alongside the existing Base64 URL-safe token generator. The OTP variant uses SecureRandom.nextInt(10) in a loop so each digit is cryptographically random, producing a string of exactly the requested length (6 for account activation and mobile password reset). Keeping both strategies in one component avoids scattering random generation across service classes. --- .../security/SecureTokenGenerator.java | 23 ++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/security/SecureTokenGenerator.java b/src/main/java/com/edgareldy/springboottutorial/security/SecureTokenGenerator.java index 284e406..631dcc5 100644 --- a/src/main/java/com/edgareldy/springboottutorial/security/SecureTokenGenerator.java +++ b/src/main/java/com/edgareldy/springboottutorial/security/SecureTokenGenerator.java @@ -5,9 +5,14 @@ import org.springframework.stereotype.Component; /** - * Generates cryptographically secure random tokens for account activation and - * password reset. Uses {@link SecureRandom} and URL-safe Base64 encoding so - * the output can be embedded directly in a query string without escaping. + * Generates cryptographically secure tokens for account activation and + * password reset. Provides two generation strategies: + *

*

* Created edgar.muhamyangabo on 10/30/26 * Author : edgar.muhamyangabo @@ -26,4 +31,16 @@ public String generate() { secureRandom.nextBytes(bytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); } + + /** + * Generates a numeric OTP of exactly {@code length} digits (0-9). + * Uses {@link SecureRandom} so each digit is cryptographically random. + */ + public String generateOtp(int length) { + StringBuilder otp = new StringBuilder(length); + for (int i = 0; i < length; i++) { + otp.append(secureRandom.nextInt(10)); + } + return otp.toString(); + } } From 748edf9b9a87301499100fc2fafe308d5e8caa28 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:30:52 +0400 Subject: [PATCH 05/51] refactor(entity): change PasswordResetToken.type from String to PasswordResetTokenType enum Replaces the bare String column with @Enumerated(EnumType.STRING) so the Java type system enforces valid values and MapStruct/JPA serialize them consistently. The database column still holds a VARCHAR; the V19 Flyway migration (previous commit) already migrated "PASSWORD_RESET" rows to "LINK" and added a CHECK constraint for LINK/OTP, so this change is in sync with the schema. --- .../springboottutorial/entity/token/PasswordResetToken.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/entity/token/PasswordResetToken.java b/src/main/java/com/edgareldy/springboottutorial/entity/token/PasswordResetToken.java index 950efe7..a9af4a9 100644 --- a/src/main/java/com/edgareldy/springboottutorial/entity/token/PasswordResetToken.java +++ b/src/main/java/com/edgareldy/springboottutorial/entity/token/PasswordResetToken.java @@ -2,6 +2,8 @@ import jakarta.persistence.Column; import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; import jakarta.persistence.Table; import java.time.Instant; import lombok.AllArgsConstructor; @@ -32,8 +34,9 @@ @EqualsAndHashCode(callSuper = true) public class PasswordResetToken extends AuditableToken { + @Enumerated(EnumType.STRING) @Column(name = "type", nullable = false) - private String type; + private PasswordResetTokenType type; @Column(name = "expiry_date", nullable = false) private Instant expiryDate; From 1f511a950f806b80d8382d1fe8a391fe555262c5 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:30:57 +0400 Subject: [PATCH 06/51] feat(repository): add findByUserAndToken to ActivationTokenRepository Adds a user-scoped lookup for the OTP activation flow. Looking up by token alone is sufficient for UUID tokens (globally unique), but a 6-digit OTP is not globally unique: two users could receive the same code. Scoping the query to the requesting user's email prevents one user's OTP from activating another account. --- .../repository/ActivationTokenRepository.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/ActivationTokenRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/ActivationTokenRepository.java index a4bb7d8..0bcf59a 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/ActivationTokenRepository.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/ActivationTokenRepository.java @@ -26,6 +26,15 @@ public interface ActivationTokenRepository extends JpaRepository findByToken(String token); + /** + * Looks up an activation token by both owner and token value. Used by the + * OTP flow to scope the lookup to a specific user, preventing two users + * who happen to share the same 6-digit OTP from activating each other's + * account. + */ + @Lock(LockModeType.PESSIMISTIC_WRITE) + Optional findByUserAndToken(AppUser user, String token); + void deleteAllByExpiresAtBefore(Instant instant); void deleteByUser(AppUser user); From df6da37cf442454038860507cd4bd3d693738447 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:31:00 +0400 Subject: [PATCH 07/51] feat(repository): add findByUserAndToken to PasswordResetTokenRepository Adds the same user-scoped lookup pattern as ActivationTokenRepository for the OTP verify step in the mobile password-reset flow. The existing findByToken stays for the web link flow where the UUID token is globally unique. --- .../repository/PasswordResetTokenRepository.java | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/main/java/com/edgareldy/springboottutorial/repository/PasswordResetTokenRepository.java b/src/main/java/com/edgareldy/springboottutorial/repository/PasswordResetTokenRepository.java index 7823b1e..0a27c5e 100644 --- a/src/main/java/com/edgareldy/springboottutorial/repository/PasswordResetTokenRepository.java +++ b/src/main/java/com/edgareldy/springboottutorial/repository/PasswordResetTokenRepository.java @@ -26,6 +26,15 @@ public interface PasswordResetTokenRepository extends JpaRepository findByToken(String token); + /** + * Looks up a password-reset token by both owner and token value. Used by + * the OTP verify step to scope the lookup to a specific user, preventing + * two users who happen to share the same 6-digit OTP from verifying each + * other's reset request. + */ + @Lock(LockModeType.PESSIMISTIC_WRITE) + Optional findByUserAndToken(AppUser user, String token); + void deleteAllByExpiryDateBefore(Instant instant); void deleteByUser(AppUser user); From 3dd52041f72e6cf5563563ca753d80395db67374 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:33:44 +0400 Subject: [PATCH 08/51] refactor(service): change ActivationTokenService.validate to OTP signature Replaces validate(String token) with validate(String email, String otp) to match the new OTP activation flow. The email parameter is required to scope the token lookup to the requesting user, preventing two accounts that share the same 6-digit code from activating each other. --- .../springboottutorial/service/ActivationTokenService.java | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/ActivationTokenService.java b/src/main/java/com/edgareldy/springboottutorial/service/ActivationTokenService.java index 94f9c49..b1d727b 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/ActivationTokenService.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/ActivationTokenService.java @@ -4,9 +4,10 @@ /** * Contract for account activation token generation and single-use validation. - * Not exposed by a controller directly: {@code AuthServiceImpl} calls + * Not exposed by a controller directly: {@code UserServiceImpl} calls * {@link #generate} after registration and {@link #validate} on the - * activation endpoint. + * activation endpoint. Tokens are 6-digit numeric OTPs (not UUID links) + * so the user just types the code they received by email. *

* Created edgar.muhamyangabo on 10/30/26 * Author : edgar.muhamyangabo @@ -17,5 +18,5 @@ public interface ActivationTokenService { String generate(AppUser user); - AppUser validate(String token); + AppUser validate(String email, String otp); } From 8938d73cb9034c2ed2669a2879197c929c8bb478 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:33:50 +0400 Subject: [PATCH 09/51] refactor(service): rewrite ActivationTokenServiceImpl for OTP flow Switches token generation from a UUID Base64 string to a 6-digit numeric OTP via SecureTokenGenerator.generateOtp(6), and reduces the TTL from 24 hours to 15 minutes (OTPs are short-lived by design). The validate method now takes (email, otp): it resolves the user from the email first, then calls findByUserAndToken to scope the lookup, preventing the theoretical collision where two accounts receive the same code. --- .../impl/ActivationTokenServiceImpl.java | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/ActivationTokenServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/ActivationTokenServiceImpl.java index 84630b6..8cb78bd 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/ActivationTokenServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/ActivationTokenServiceImpl.java @@ -3,8 +3,10 @@ import com.edgareldy.springboottutorial.entity.token.ActivationToken; import com.edgareldy.springboottutorial.entity.user.AppUser; import com.edgareldy.springboottutorial.exception.InvalidTokenException; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; import com.edgareldy.springboottutorial.exception.TokenExpiredException; import com.edgareldy.springboottutorial.repository.ActivationTokenRepository; +import com.edgareldy.springboottutorial.repository.AppUserRepository; import com.edgareldy.springboottutorial.security.SecureTokenGenerator; import com.edgareldy.springboottutorial.service.ActivationTokenService; import java.time.Duration; @@ -15,7 +17,10 @@ /** * Default {@link ActivationTokenService} implementation backed by - * {@link ActivationTokenRepository}. + * {@link ActivationTokenRepository}. Generates 6-digit numeric OTPs + * with a 15-minute TTL. Validation is scoped to the requesting user + * (email + OTP) so two accounts that happen to receive the same code + * cannot activate each other. *

* Created edgar.muhamyangabo on 10/30/26 * Author : edgar.muhamyangabo @@ -26,41 +31,45 @@ @RequiredArgsConstructor public class ActivationTokenServiceImpl implements ActivationTokenService { - private static final Duration EXPIRATION = Duration.ofHours(24); + private static final Duration EXPIRATION = Duration.ofMinutes(15); + private static final int OTP_LENGTH = 6; private final ActivationTokenRepository activationTokenRepository; + private final AppUserRepository appUserRepository; private final SecureTokenGenerator secureTokenGenerator; @Override @Transactional public String generate(AppUser user) { activationTokenRepository.deleteByUser(user); - String rawToken = secureTokenGenerator.generate(); + String otp = secureTokenGenerator.generateOtp(OTP_LENGTH); Instant now = Instant.now(); ActivationToken activationToken = ActivationToken.builder() .user(user) - .token(rawToken) + .token(otp) .createdAt(now) .expiresAt(now.plus(EXPIRATION)) .build(); activationTokenRepository.save(activationToken); - return rawToken; + return otp; } @Override @Transactional - public AppUser validate(String token) { - ActivationToken activationToken = activationTokenRepository.findByToken(token) - .orElseThrow(() -> new InvalidTokenException("Invalid activation token")); + public AppUser validate(String email, String otp) { + AppUser user = appUserRepository.findByEmailIgnoreCase(email) + .orElseThrow(() -> new ResourceNotFoundException("User not found for email: " + email)); + ActivationToken activationToken = activationTokenRepository.findByUserAndToken(user, otp) + .orElseThrow(() -> new InvalidTokenException("Invalid activation code")); if (activationToken.getValidatedAt() != null) { - throw new InvalidTokenException("Activation token already used"); + throw new InvalidTokenException("Activation code already used"); } if (activationToken.getExpiresAt() != null && activationToken.getExpiresAt().isBefore(Instant.now())) { - throw new TokenExpiredException("Activation token expired"); + throw new TokenExpiredException("Activation code expired"); } activationToken.setValidatedAt(Instant.now()); activationTokenRepository.save(activationToken); - return activationToken.getUser(); + return user; } } From 82c7fd61b1af5be5f5e4695e697c3a857411ccee Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:33:54 +0400 Subject: [PATCH 10/51] refactor(service): add type parameter and verifyOtp to PasswordResetTokenService generate now takes a PasswordResetTokenType so callers can request either a web LINK (UUID, 1-hour TTL) or a mobile OTP (6-digit, 5-minute TTL). verifyOtp(email, otp) is a non-destructive check for the mobile UI's intermediate step: it confirms the OTP is valid before showing the new-password screen, without consuming the token. --- .../service/PasswordResetTokenService.java | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/PasswordResetTokenService.java b/src/main/java/com/edgareldy/springboottutorial/service/PasswordResetTokenService.java index 1e73c6f..427cd45 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/PasswordResetTokenService.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/PasswordResetTokenService.java @@ -1,11 +1,19 @@ package com.edgareldy.springboottutorial.service; +import com.edgareldy.springboottutorial.entity.token.PasswordResetTokenType; import com.edgareldy.springboottutorial.entity.user.AppUser; /** - * Contract for password reset token generation and single-use validation. - * Not exposed by a controller directly: {@code AuthServiceImpl} orchestrates - * the forgot-password/reset-password flow around these two methods. + * Contract for password reset token generation and validation. Supports two + * flows distinguished by {@link PasswordResetTokenType}: + *

*

* Created edgar.muhamyangabo on 10/30/26 * Author : edgar.muhamyangabo @@ -14,7 +22,9 @@ */ public interface PasswordResetTokenService { - String generate(AppUser user); + String generate(AppUser user, PasswordResetTokenType type); AppUser validateAndConsume(String token); + + AppUser verifyOtp(String email, String otp); } From 0cc2211fc18c3b71d198d1fd627a838b92786251 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:34:00 +0400 Subject: [PATCH 11/51] refactor(service): rewrite PasswordResetTokenServiceImpl for two-flow reset generate(user, type) branches on PasswordResetTokenType: - LINK: UUID Base64 token, 1-hour TTL (existing web flow, unchanged behaviour) - OTP: 6-digit numeric code, 5-minute TTL (new mobile flow) verifyOtp(email, otp) finds the user by email, looks up the token via findByUserAndToken (user-scoped to prevent OTP collisions), verifies type == OTP, and checks expiry without deleting the row. This lets the mobile client confirm the code is valid before the user types a new password. validateAndConsume is unchanged: it works for both LINK and OTP tokens because each user has at most one pending password reset token at any time. --- .../impl/PasswordResetTokenServiceImpl.java | 59 +++++++++++++------ 1 file changed, 41 insertions(+), 18 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/PasswordResetTokenServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/PasswordResetTokenServiceImpl.java index 630a8ac..2abe2f3 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/PasswordResetTokenServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/PasswordResetTokenServiceImpl.java @@ -1,8 +1,11 @@ package com.edgareldy.springboottutorial.service.impl; import com.edgareldy.springboottutorial.entity.token.PasswordResetToken; +import com.edgareldy.springboottutorial.entity.token.PasswordResetTokenType; import com.edgareldy.springboottutorial.entity.user.AppUser; import com.edgareldy.springboottutorial.exception.InvalidTokenException; +import com.edgareldy.springboottutorial.exception.ResourceNotFoundException; +import com.edgareldy.springboottutorial.repository.AppUserRepository; import com.edgareldy.springboottutorial.repository.PasswordResetTokenRepository; import com.edgareldy.springboottutorial.security.SecureTokenGenerator; import com.edgareldy.springboottutorial.service.PasswordResetTokenService; @@ -13,12 +16,11 @@ import org.springframework.transaction.annotation.Transactional; /** - * Default {@link PasswordResetTokenService} implementation backed by - * {@link PasswordResetTokenRepository}. In {@link #validateAndConsume}, the - * token row is deleted before the expiry check so a valid token is never - * reusable. For an expired token the subsequent {@link InvalidTokenException} - * causes Spring to roll back the transaction, so the row is not actually - * removed; it stays until {@code TokenCleanupScheduler} runs. + * Default {@link PasswordResetTokenService} implementation. Generates either + * a UUID token (LINK, 1-hour TTL) for the web flow or a 6-digit OTP (OTP, + * 5-minute TTL) for the mobile flow. In {@link #validateAndConsume}, the row + * is deleted before the expiry check: if the token is expired the rollback + * leaves it in place until {@code TokenCleanupScheduler} removes it. *

* Created edgar.muhamyangabo on 10/30/26 * Author : edgar.muhamyangabo @@ -29,38 +31,59 @@ @RequiredArgsConstructor public class PasswordResetTokenServiceImpl implements PasswordResetTokenService { - private static final Duration EXPIRATION = Duration.ofHours(1); - private static final String TYPE_PASSWORD_RESET = "PASSWORD_RESET"; + private static final Duration LINK_EXPIRATION = Duration.ofHours(1); + private static final Duration OTP_EXPIRATION = Duration.ofMinutes(5); + private static final int OTP_LENGTH = 6; private final PasswordResetTokenRepository passwordResetTokenRepository; + private final AppUserRepository appUserRepository; private final SecureTokenGenerator secureTokenGenerator; @Override @Transactional - public String generate(AppUser user) { + public String generate(AppUser user, PasswordResetTokenType type) { passwordResetTokenRepository.deleteByUser(user); - String rawToken = secureTokenGenerator.generate(); + String rawToken = type == PasswordResetTokenType.OTP + ? secureTokenGenerator.generateOtp(OTP_LENGTH) + : secureTokenGenerator.generate(); + Duration ttl = type == PasswordResetTokenType.OTP ? OTP_EXPIRATION : LINK_EXPIRATION; Instant now = Instant.now(); - PasswordResetToken passwordResetToken = PasswordResetToken.builder() + PasswordResetToken token = PasswordResetToken.builder() .user(user) .token(rawToken) .createdAt(now) - .type(TYPE_PASSWORD_RESET) - .expiryDate(now.plus(EXPIRATION)) + .type(type) + .expiryDate(now.plus(ttl)) .build(); - passwordResetTokenRepository.save(passwordResetToken); + passwordResetTokenRepository.save(token); return rawToken; } @Override @Transactional public AppUser validateAndConsume(String token) { - PasswordResetToken passwordResetToken = passwordResetTokenRepository.findByToken(token) + PasswordResetToken resetToken = passwordResetTokenRepository.findByToken(token) .orElseThrow(() -> new InvalidTokenException("Invalid password reset token")); - passwordResetTokenRepository.delete(passwordResetToken); - if (passwordResetToken.getExpiryDate().isBefore(Instant.now())) { + passwordResetTokenRepository.delete(resetToken); + if (resetToken.getExpiryDate().isBefore(Instant.now())) { throw new InvalidTokenException("Password reset token expired"); } - return passwordResetToken.getUser(); + return resetToken.getUser(); + } + + @Override + @Transactional(readOnly = true) + public AppUser verifyOtp(String email, String otp) { + AppUser user = appUserRepository.findByEmailIgnoreCase(email) + .orElseThrow(() -> new ResourceNotFoundException("User not found for email: " + email)); + PasswordResetToken resetToken = passwordResetTokenRepository.findByUserAndToken(user, otp) + .orElseThrow(() -> new InvalidTokenException("Invalid OTP")); + if (resetToken.getType() != PasswordResetTokenType.OTP) { + throw new InvalidTokenException("Invalid OTP"); + } + if (resetToken.getExpiryDate().isBefore(Instant.now())) { + throw new InvalidTokenException("OTP expired"); + } + return user; } } From c8220eae79e59ce57eaa6e8a8e5be7635ac14a19 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:35:04 +0400 Subject: [PATCH 12/51] feat(email): add RESET_PASSWORD_OTP template name to EmailTemplateName Registers the new Thymeleaf template name for the mobile password-reset OTP email. All template name lookups go through this enum to avoid hardcoded strings in EmailServiceImpl. --- .../edgareldy/springboottutorial/email/EmailTemplateName.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/email/EmailTemplateName.java b/src/main/java/com/edgareldy/springboottutorial/email/EmailTemplateName.java index b2c21a8..2ece60d 100644 --- a/src/main/java/com/edgareldy/springboottutorial/email/EmailTemplateName.java +++ b/src/main/java/com/edgareldy/springboottutorial/email/EmailTemplateName.java @@ -17,7 +17,8 @@ public enum EmailTemplateName { ACTIVATE_ACCOUNT("activate_account"), - RESET_PASSWORD("reset_password"); + RESET_PASSWORD("reset_password"), + RESET_PASSWORD_OTP("reset_password_otp"); private final String name; From cdd8d13b6022cdc34f9d073ba807e72156d13ad9 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:35:08 +0400 Subject: [PATCH 13/51] feat(service): add sendPasswordResetOtpEmail to EmailService contract Adds the method signature for the mobile password-reset OTP email. sendActivationEmail parameter renamed from token to otp to reflect that activation now sends a 6-digit code rather than a UUID link. --- .../edgareldy/springboottutorial/service/EmailService.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/EmailService.java b/src/main/java/com/edgareldy/springboottutorial/service/EmailService.java index f32f5fb..53c3d16 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/EmailService.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/EmailService.java @@ -14,7 +14,9 @@ */ public interface EmailService { - void sendActivationEmail(AppUser user, String token); + void sendActivationEmail(AppUser user, String otp); void sendPasswordResetEmail(AppUser user, String token); + + void sendPasswordResetOtpEmail(AppUser user, String otp); } From 3408be9a6d97c45ed9373121d467564ba464a4b1 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:35:13 +0400 Subject: [PATCH 14/51] feat(service): update EmailServiceImpl for OTP activation and mobile reset sendActivationEmail no longer builds a frontend link: activation is now done by typing the OTP code, so only the code (activationToken context variable) is passed to the template. sendPasswordResetOtpEmail renders the new reset_password_otp Thymeleaf template with the resetOtp context variable and sends it on the same emailTaskExecutor async pool as the other email methods. --- .../service/impl/EmailServiceImpl.java | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/edgareldy/springboottutorial/service/impl/EmailServiceImpl.java b/src/main/java/com/edgareldy/springboottutorial/service/impl/EmailServiceImpl.java index 99fb8d3..8079ad6 100644 --- a/src/main/java/com/edgareldy/springboottutorial/service/impl/EmailServiceImpl.java +++ b/src/main/java/com/edgareldy/springboottutorial/service/impl/EmailServiceImpl.java @@ -55,12 +55,10 @@ public EmailServiceImpl(JavaMailSender mailSender, @Override @Async("emailTaskExecutor") - public void sendActivationEmail(AppUser user, String token) { - String link = frontendUrl + "/auth/activate-account?token=" + token; + public void sendActivationEmail(AppUser user, String otp) { Context context = new Context(Locale.ENGLISH); context.setVariable("username", user.getUsername()); - context.setVariable("activationToken", token); - context.setVariable("activationLink", link); + context.setVariable("activationToken", otp); String html = templateEngine.process(EmailTemplateName.ACTIVATE_ACCOUNT.getName(), context); sendEmail(user.getEmail(), "Activate your account", html); } @@ -76,6 +74,16 @@ public void sendPasswordResetEmail(AppUser user, String token) { sendEmail(user.getEmail(), "Reset your password", html); } + @Override + @Async("emailTaskExecutor") + public void sendPasswordResetOtpEmail(AppUser user, String otp) { + Context context = new Context(Locale.ENGLISH); + context.setVariable("username", user.getUsername()); + context.setVariable("resetOtp", otp); + String html = templateEngine.process(EmailTemplateName.RESET_PASSWORD_OTP.getName(), context); + sendEmail(user.getEmail(), "Reset your password", html); + } + private void sendEmail(String to, String subject, String html) { try { MimeMessage mimeMessage = mailSender.createMimeMessage(); From 2b967f1df2014837c949bbd8c744c015e6b732b6 Mon Sep 17 00:00:00 2001 From: EdgarEldy Date: Sat, 21 Nov 2026 10:35:17 +0400 Subject: [PATCH 15/51] refactor(template): remove activation link from activate_account.html The activation flow is now purely OTP: the user types the 6-digit code in the app instead of clicking a link. The clickable button and its CSS class are removed, and the expiry notice is updated from 24 hours to 15 minutes to match the new token TTL. --- .../resources/templates/activate_account.html | 22 ++----------------- 1 file changed, 2 insertions(+), 20 deletions(-) diff --git a/src/main/resources/templates/activate_account.html b/src/main/resources/templates/activate_account.html index 731a198..98a69ff 100644 --- a/src/main/resources/templates/activate_account.html +++ b/src/main/resources/templates/activate_account.html @@ -48,21 +48,6 @@ background-color: #EEF2FF; border-radius: 8px; } - .activation-link { - display: block; - text-align: center; - margin-top: 24px; - } - .activation-link a { - display: inline-block; - padding: 12px 32px; - background-color: #4F46E5; - color: #ffffff; - text-decoration: none; - border-radius: 6px; - font-size: 15px; - font-weight: 600; - } .expiry-notice { margin-top: 24px; padding: 12px 16px; @@ -89,16 +74,13 @@

Spring Boot Tutorial

Hello username,

- Thank you for signing up! Please activate your account by clicking the button below. + Thank you for signing up! Enter the code below in the app to activate your account.

000000
-
- This link expires in 24 hours. If you did not create an account, you can safely ignore this email. + This code expires in 15 minutes. If you did not create an account, you can safely ignore this email.