Repository navigation
feat(user-management+docs): OTP activation, mobile password reset, PasswordResetController - #34
Merged
Merged
Conversation
…ork 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.
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.
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.
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.
…ordResetTokenType 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.
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.
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.
…ature 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.
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.
…okenService 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.
… 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.
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.
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.
…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.
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.
… flow New Thymeleaf template that displays a 6-digit OTP code for the mobile password-reset flow. Same styling as the existing activation email but with a red palette to signal a security-sensitive action. Template variables: username and resetOtp. Expiry notice states 5 minutes to match PasswordResetTokenServiceImpl.OTP_EXPIRATION.
All tests updated to match the new OTP-based signatures: - generate() now stubs generateOtp(6) instead of generate() - validate() stubs are split into findByEmailIgnoreCase (AppUserRepository) then findByUserAndToken, replacing the old findByToken calls - Expiry timing in test fixtures reduced to minutes (not hours) to match the 15-minute TTL - AppUserRepository added as a @mock field
… reset Tests updated to match the new PasswordResetTokenService contract: - _01_ and _02_ now test generate(user, LINK) and generate(user, OTP) separately, verifying the correct token format and type for each - _03_ to _05_ (validateAndConsume) use PasswordResetTokenType.LINK enum instead of the old "PASSWORD_RESET" string - _06_ to _09_ are new tests for verifyOtp: valid OTP, OTP not found, wrong type (LINK), and expired OTP - AppUserRepository added as a @mock field
New DTO carrying the email and 6-digit activation code submitted by the user. The OTP field is validated with @pattern to enforce exactly 6 digits, consistent with the token length produced by SecureTokenGenerator.generateOtp. Field serialises as activation_code in JSON (snake_case convention).
activate(String token) is replaced by activate(String email, String otp) to match the new ActivationTokenService contract, which scopes validation to the requesting user's email.
activate now delegates to activationTokenService.validate(email, otp) instead of validate(token). forgotPassword calls passwordResetTokenService.generate(user, LINK) to stay on the web link flow for this endpoint. The mobile OTP flow will be exposed via a separate endpoint on feature/user-management.
… with body
The activation flow now uses a 6-digit OTP submitted as a JSON body
{email, activation_code} rather than a UUID token in a query string.
GET /activate-account becomes POST /activate-account accepting
@Valid ActivateAccountRequest.
…count
_10_ now sends POST /api/v1/auth/activate-account with
{email, activation_code} JSON body and stubs userService.activate(email, otp),
replacing the previous GET ?token= form.
_01_ stubs activationTokenService.validate(email, otp) and calls userService.activate(email, otp). _02_ stubs passwordResetTokenService.generate(user, LINK) to match the forgotPassword web flow.
…asswordResetOtpEmail _01_ no longer asserts activationLink (removed from sendActivationEmail) and uses "123456" as the OTP token. _03_ is new: verifies that sendPasswordResetOtpEmail passes username and resetOtp to the RESET_PASSWORD_OTP template. _04_ (renamed from _03_) extends the @async executor assertion to cover the new sendPasswordResetOtpEmail method.
Replace .type("PASSWORD_RESET") with .type(PasswordResetTokenType.LINK)
in all three token fixtures so the test compiles against the updated
PasswordResetToken entity whose type field is now a PasswordResetTokenType
enum instead of a plain String.
Two related changes to SecurityConfig: 1. .cors(withDefaults()) activates the CorsConfigurationSource bean defined in CorsConfig (introduced on feature/core-architecture and merged into this branch). Without this call Spring Security ignores the bean entirely and rejects every OPTIONS pre-flight with 403. 2. The activate-account endpoint changed from GET ?token= to POST with a JSON body (ActivateAccountRequest) on this branch. The permitAll rule was still scoped to HttpMethod.GET, so unauthenticated POST requests hit the catch-all authenticated() rule and received 401. Changed to HttpMethod.POST to match the new endpoint.
Two different tests shared the number prefix _08_: - _08_ShouldReturn400_WhenLoginEmailInvalid (login validation) - _08_ShouldReturn200_WhenLogoutWithValidToken (logout) The login test was inserted without renumbering. Renamed to _19_ to restore the unique-sequential-number convention used throughout the project.
…viceImpl verifyOtp calls passwordResetTokenRepository.findByUserAndToken, which carries @lock(PESSIMISTIC_WRITE). Combining a pessimistic write lock with readOnly = true is semantically contradictory: the lock signals intent to prevent concurrent writes, while readOnly = true signals no data will be modified. Although HikariCP + PostgreSQL tolerate this at runtime (setReadOnly(true) does not map to BEGIN READ ONLY), the combination is misleading and fragile under stricter JPA configurations. Since verifyOtp performs a scoped lookup to prevent OTP collision and uses PESSIMISTIC_WRITE for correctness, the transaction is treated as a plain write transaction.
…ImplTest validate(email, otp) throws ResourceNotFoundException when the email is not registered. The five previous tests only stubbed findByEmailIgnoreCase to return a present Optional; the error path was untested.
…iceImplTest verifyOtp(email, otp) throws ResourceNotFoundException when the email is not registered. Tests _06_ through _09_ only stubbed findByEmailIgnoreCase to return a present Optional; the error path was untested.
…reset to feature/user-management 9 conflicts resolved: - ActivationTokenService: replace validate(token) with validate(email, otp), drop getUserByToken - UserService: replace activate(token) with activate(email, otp) - EmailServiceImpl: set activationToken context variable (was stale activationLink reference) - UserServiceImpl: adopt activate(email, otp); merge forgotPassword guards from HEAD with generate(user, PasswordResetTokenType.LINK) signature from feature/token-management - activate_account.html: replace link button with OTP code display - AuthControllerTest: replace old token-based _08_/_09_ tests with logout _08_/_09_ and new OTP activation _10_; renumber affected tests; remove duplicate _14_/_15_ logout tests and duplicate _16_/_17_ prefixes - ActivationTokenServiceImplTest: replace getUserByToken tests with user-not-found path test - EmailServiceImplTest: assert activationToken variable (not activationLink) - UserServiceImplTest: update _08_ to OTP signature, drop _08b_ re-send test, update _09_ generate stub to include PasswordResetTokenType.LINK, fix generate(any(), any()) in _10_/_10b_/_10c_ verify calls
The mobile password-reset flow has two distinct steps before the user can enter a new password: submit OTP and get confirmation the code is valid (non-destructive), then submit the same OTP again to actually change the password. This DTO carries email + otp for the first step, served by POST /api/v1/password-reset/verify-otp.
… UserService Two new contract methods for the mobile password-reset flow: - forgotPasswordMobile(email): sends a 6-digit OTP via email (PasswordResetTokenType.OTP) - verifyPasswordResetOtp(email, otp): non-destructive check before the user types their new password; delegates to PasswordResetTokenService.verifyOtp
forgotPasswordMobile mirrors forgotPassword but generates an OTP token (PasswordResetTokenType.OTP, 5-min TTL) and sends it via sendPasswordResetOtpEmail. The same guard as forgotPassword is applied: disabled or locked accounts silently short-circuit so the caller cannot enumerate account states. verifyPasswordResetOtp delegates to PasswordResetTokenService.verifyOtp which is non-destructive: the token survives so the client can reuse the same OTP in the subsequent /confirm call.
…t flows Four public POST endpoints under /api/v1/password-reset: - /web: triggers the LINK (UUID) flow, same as auth/forgot-password but grouped here for clarity alongside the mobile variant - /mobile: triggers the OTP flow; sends a 6-digit code by email - /verify-otp: non-destructive OTP check; the client can confirm the code before showing the new-password screen, avoiding a wasted /confirm call - /confirm: accepts a token query param (UUID or OTP) + new password body, delegates to userService.resetPassword which calls validateAndConsume
…onfig All four password-reset endpoints (/web, /mobile, /verify-otp, /confirm) must be reachable without a bearer token: the caller is by definition unauthenticated when resetting their password. A single wildcard rule covers all current and future sub-paths under this prefix.
…endpoints Five cases: /web and /mobile both return 200 and delegate to the correct service method; /verify-otp returns 200 on a valid OTP and 400 when InvalidTokenException is thrown; /confirm returns 200 and delegates to resetPassword. The full filter chain is loaded (SecurityConfig imported) to verify the permit-all rule covers each path without authentication.
…in UserServiceImplTest Three new cases covering the two new UserService methods: - _09b_: forgotPasswordMobile sends OTP email when account is active - _09c_: forgotPasswordMobile silently skips disabled accounts (same guard as forgotPassword) - _09d_: verifyPasswordResetOtp delegates to passwordResetTokenService.verifyOtp
…erviceImpl getUserByToken was used by the expired-token re-send flow in UserServiceImpl, which was removed when switching to 6-digit OTPs. The method was no longer declared in ActivationTokenService, making the @OverRide invalid.
The field was referenced in seedDemoData() but never declared, causing a compilation error. Added as a private static final boolean defaulting to false so the class compiles and the password-reset utility block remains available for future use without active effect.
…erifyPasswordResetOtp The method delegates entirely to passwordResetTokenService.verifyOtp, which manages its own transaction boundary. The outer readOnly annotation was redundant and misleading since it would override the delegate's own transaction setting.
…oller endpoints Each endpoint now declares its expected HTTP error responses via the qualified @io.swagger.v3.oas.annotations.responses.ApiResponse form (convention: avoid importing Swagger's ApiResponse to prevent name conflict with the project's own ApiResponse DTO).
…setControllerTest Covers the case where resetPassword throws InvalidTokenException, which GlobalExceptionHandler maps to 400. Mirrors the analogous _04_ test for /verify-otp.
…Mobile forgotPasswordMobile shares the same !enabled || isAccountLocked() guard as forgotPassword. The not-enabled path was already covered by _09c_; this test covers the locked path, mirroring _10c_ for the web flow.
…ngs.local.json ignored Previously the whole .claude/ directory was ignored. Only session-specific files (settings.local.json, memory/) should stay ignored; project files (CLAUDE.md, GAP_ANALYSIS.md, agents/, commands/, skills/) should be tracked.
…ills to version control These project files were previously ignored by .claude/ in .gitignore. Now that the ignore rule is scoped to memory/ and settings.local.json only, this initial commit tracks all Claude Code project configuration files.
…d reset to feature/docs 2 conflicts resolved: - EmailTemplateName: merge ORDER_CONFIRMATION/ORDER_ADMIN_NOTIFICATION (docs) with RESET_PASSWORD_OTP (user-management); keep all three. - DataSeeder: combine @value("${app.seed.reset-user-passwords:false}") approach from docs (Spring-config-driven, no static field) with the package-private seedDemoData(boolean) overload from user-management (testability). @bean method now delegates to the overload; static field removed.
…ile reset Documents the PasswordResetTokenType enum (LINK/OTP), OTP-based activation (6-digit code, 15-min TTL, user-scoped lookup), two password reset flows (UUID link vs OTP), and the non-destructive verifyOtp/destructive validateAndConsume distinction. Updates key-files table with new files.
Documents the new PasswordResetController (4 public endpoints: /web, /mobile, /verify-otp, /confirm), the two new UserService methods, the VerifyOtpRequest DTO, the DataSeeder app.seed.reset-user-passwords property, and the deliberate /web doublon rationale. Updates key-files table.
…folder
- activate-account: changed from GET ?token= to POST with JSON body
{"email", "activation_code"} to reflect the OTP migration.
- New 'Password Reset' folder with 4 requests: /web (LINK flow),
/mobile (OTP flow), /verify-otp (non-destructive check),
/confirm (token param + new_password body).
…licate signature The @bean method seedDemoData(@value boolean) and the package-private overload seedDemoData(boolean) have identical Java signatures, causing a compilation error that cascades to prevent Lombok from generating getters across the whole module. Renamed the overload to buildRunner(boolean) to resolve the conflict. DataSeederTest updated accordingly.
6 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
feature/user-management(OTP activation + mobile password reset flows)PasswordResetControllerwith 4 public endpoints under/api/v1/password-reset:POST /web- UUID reset link (web flow)POST /mobile- 6-digit OTP (mobile flow)POST /verify-otp- non-destructive OTP checkPOST /confirm- token or OTP + new passwordGET ?token=toPOSTwith JSON body{email, activation_code}PasswordResetTokenTypeenum (LINK/OTP), V19 migration,reset_password_otp.htmltemplateDataSeeder:@Value-driven reset flag + package-private overload for testabilityfeature/token-managementandfeature/user-managementTest plan
feature/user-management