fix:"保证验证码消费与账号变更原子提交"

This commit is contained in:
xpp committed 2026-10-21 23:09:02 +08:00
1 parent 32f6f67b9f
commit 02c21e5c19
9 files changed
+345 -14

No files matched your search

@@ -28,17 +28,20 @@ public class AuthController {
private static final String SESSION_COOKIE = "moyi_session";
private final AuthService authService;
private final VerificationService verification;
private final VerifiedAccountService verifiedAccounts;
private final int sessionTtlHours;
private final boolean secureCookie;
public AuthController(
AuthService authService,
VerificationService verification,
VerifiedAccountService verifiedAccounts,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours,
@Value("${moyi.auth.secure-cookie}") boolean secureCookie
) {
this.authService = authService;
this.verification = verification;
this.verifiedAccounts = verifiedAccounts;
this.sessionTtlHours = sessionTtlHours;
this.secureCookie = secureCookie;
}
@@ -67,10 +70,8 @@ public class AuthController {
@PostMapping("/auth/password-reset")
public ResponseEntity<Void> resetPassword(@RequestBody PasswordResetRequest input,HttpServletRequest request) {
PasswordPolicy.validate(input.newPassword());
String account = verification.consumeReset(input.account(), input.verificationCode());
authService.resetPassword(account, input.newPassword(), meta(request));
return ResponseEntity.noContent().build();
verifiedAccounts.resetPassword(input.account(), input.verificationCode(), input.newPassword(), meta(request));
return ResponseEntity.noContent().header(HttpHeaders.SET_COOKIE, sessionCookie("", Duration.ZERO).toString()).build();
}
public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {}
@@ -103,10 +104,8 @@ public class AuthController {
HttpServletRequest request,
HttpServletResponse response
) {
PasswordPolicy.validate(input.password());
verification.consume(input.account(),input.verificationCode());
AuthService.AuthResult result = authService.register(
input.invitationCode(), input.account(), input.password(), input.displayName(), meta(request)
AuthService.AuthResult result = verifiedAccounts.register(
input.invitationCode(), input.account(), input.password(), input.displayName(), input.verificationCode(), meta(request)
);
response.addHeader(HttpHeaders.SET_COOKIE, sessionCookie(result.token(), null).toString());
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("user", result.user()));
@@ -0,0 +1,60 @@
package com.moyi.controlplane.auth;
import com.moyi.controlplane.common.ApiException;
import java.util.function.Function;
import java.util.function.Supplier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
/** Public registration/recovery transaction boundary. Never call these flows inside a business transaction. */
@Service
public class VerifiedAccountService {
private final AuthService auth;
private final VerificationService verification;
private final TransactionTemplate transactions;
public VerifiedAccountService(AuthService auth, VerificationService verification, PlatformTransactionManager manager) {
this.auth = auth;
this.verification = verification;
transactions = new TransactionTemplate(manager);
// Own the public operation; a caller rollback cannot erase committed incorrect-code counters.
transactions.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
}
public AuthService.AuthResult register(String invitation, String account, String password, String displayName,
String code, AuthService.RequestMeta meta) {
PasswordPolicy.validate(password);
return complete(() -> { verification.consume(account, code); return account; },
verified -> auth.register(invitation, verified, password, displayName, meta));
}
public void resetPassword(String account, String code, String password, AuthService.RequestMeta meta) {
PasswordPolicy.validate(password);
complete(() -> verification.consumeReset(account, code), verified -> {
auth.resetPassword(verified, password, meta);
return Boolean.TRUE;
});
}
private record Completion<T>(T result, ApiException rejectedCode) {}
private <T> T complete(Supplier<String> consume, Function<String, T> changeAccount) {
Completion<T> outcome = transactions.execute(status -> {
String account;
try { account = consume.get(); }
catch (ApiException rejected) {
// VerificationService intentionally commits wrong-code attempts. Return the rejection,
// then throw AFTER commit. No account mutation has run at this point.
return new Completion<T>(null, rejected);
}
// Do not catch business/audit/storage failures here: roll back successful code consumption,
// invitation redemption, password/session changes and audit as one operation.
return new Completion<>(changeAccount.apply(account), null);
});
if (outcome == null) throw new IllegalStateException("Verified account transaction returned no outcome");
if (outcome.rejectedCode() != null) throw outcome.rejectedCode();
return outcome.result();
}
}