extract rotation logic to TokenService
All checks were successful
CI / Maven unit tests (push) Successful in 15s
CI / Build and push images (push) Has been skipped
CI / Deploy to server (push) Has been skipped

This commit is contained in:
2026-10-05 19:30:50 +01:00
parent cbb8c2195f
commit 11115a435a
3 changed files with 125 additions and 104 deletions

View File

@@ -2,9 +2,6 @@ package com.ddf.vodsystem.services;
import com.ddf.vodsystem.dto.GoogleUser;
import com.ddf.vodsystem.dto.TokenPackage;
import com.ddf.vodsystem.dto.properties.AuthProperties;
import com.ddf.vodsystem.entities.RefreshToken;
import com.ddf.vodsystem.entities.TokenFamily;
import com.ddf.vodsystem.entities.User;
import com.ddf.vodsystem.exceptions.NotAuthenticated;
import com.ddf.vodsystem.repositories.UserRepository;
@@ -17,7 +14,6 @@ import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.HexFormat;
import java.util.Optional;
@@ -28,25 +24,17 @@ public class UserService {
private final UserRepository userRepository;
private final JwtService jwtService;
private final long tokenFamilyExpirationMs;
private final long refreshTokenExpirationMs;
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private static final int REFRESH_GRACE_PERIOD_SECONDS = 5;
private final TokenService tokenService;
public UserService(UserRepository userRepository,
JwtService jwtService,
GoogleVerifierService googleVerifierService,
AuthProperties props,
TokenService tokenService) {
this.userRepository = userRepository;
this.googleVerifierService = googleVerifierService;
this.jwtService = jwtService;
this.tokenService = tokenService;
this.refreshTokenExpirationMs = props.expiration().refreshToken().toMillis();
this.tokenFamilyExpirationMs = props.expiration().tokenFamily().toMillis();
}
/**
@@ -84,62 +72,17 @@ public class UserService {
GoogleUser googleUser = googleVerifierService.verify(idToken);
User user = createOrUpdateGoogleUser(googleUser);
byte[] rawRefresh = generateRandomBytes(32);
TokenFamily tokenFamily = tokenService.createTokenFamily(user, tokenFamilyExpirationMs);
tokenService.createRefreshToken(tokenService.hashToken(rawRefresh), tokenFamily, refreshTokenExpirationMs);
String refreshToken = tokenService.createSession(user);
String jwt = jwtService.generateToken(user.getId());
return new TokenPackage(tokenService.bytesToHex(rawRefresh), jwt);
return new TokenPackage(refreshToken, jwt);
}
@Transactional(noRollbackFor = NotAuthenticated.class)
public TokenPackage refresh(String refreshToken) {
if (refreshToken == null || refreshToken.isBlank()) {
throw new NotAuthenticated("Missing refresh token");
}
TokenService.Rotation rotation = tokenService.rotate(refreshToken);
String jwt = jwtService.generateToken(rotation.userId());
// Check Refresh Token is real
byte[] rawToken = tokenService.hexToBytes(refreshToken);
RefreshToken token = tokenService.getRefreshTokenByHash(rawToken)
.orElseThrow(() -> new NotAuthenticated("No such refresh token"));
// Find Token Family
Optional<TokenFamily> tokenFamily = tokenService.getFamilyByRefreshToken(token);
if (tokenFamily.isEmpty()) {
throw new IllegalStateException("Token must be tied to a family");
}
if (tokenFamily.get().getRevokedAt() != null) {
throw new NotAuthenticated("Token family has been revoked");
}
Instant now = Instant.now();
// Reuse Check
if (token.getUsedAt() != null) {
if (Duration.between(token.getUsedAt(), now).getSeconds() > REFRESH_GRACE_PERIOD_SECONDS) {
tokenService.revokeTokenFamily(tokenFamily.get());
}
throw new NotAuthenticated("Refresh token already used");
}
// Expiry Check
if (now.isAfter(token.getExpiresAt()) || now.isAfter(tokenFamily.get().getExpiresAt())) {
throw new NotAuthenticated("Refresh token or family expired");
}
// Rotate
token.setUsedAt(now);
byte[] newRawToken = generateRandomBytes(32);
tokenService.createRefreshToken(
newRawToken,
tokenFamily.get(),
refreshTokenExpirationMs
);
String jwt = jwtService.generateToken(tokenFamily.get().getUser().getId());
return new TokenPackage(tokenService.bytesToHex(newRawToken), jwt);
return new TokenPackage(rotation.newRefreshToken(), jwt);
}
/**
@@ -170,7 +113,7 @@ public class UserService {
user.setEmail(googleUser.email());
user.setName(googleUser.name());
user.setProfilePictureUrl(googleUser.profilePictureUrl());
return userRepository.saveAndFlush(user);
return userRepository.save(user);
}
private byte[] generateRandomBytes(int length) {