scheduling

This commit is contained in:
Vladimir Voronin
2025-01-07 13:31:08 +03:00
parent 8b440ad9e8
commit 84f61532d0
5 changed files with 73 additions and 29 deletions

View File

@@ -5,10 +5,8 @@ import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.stereotype.Service
import reactor.core.publisher.Mono
import space.luminic.budgerapp.configs.AuthException
import space.luminic.budgerapp.models.Token
import space.luminic.budgerapp.models.TokenStatus
import space.luminic.budgerapp.models.User
import space.luminic.budgerapp.repos.TokenRepo
import space.luminic.budgerapp.repos.UserRepo
import space.luminic.budgerapp.utils.JWTUtil
import java.time.LocalDateTime
@@ -19,7 +17,7 @@ import java.util.Date
@Service
class AuthService(
private val userRepository: UserRepo,
private val tokenRepo: TokenRepo,
private val tokenService: TokenService,
private val jwtUtil: JWTUtil
) {
@@ -31,18 +29,14 @@ class AuthService(
if (passwordEncoder.matches(password, user.password)) {
val token = jwtUtil.generateToken(user.username)
val expireAt = Date(System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 10)
tokenRepo.save(
Token(
token = token,
username = username,
issuedAt = LocalDateTime.now(),
expiresAt = LocalDateTime.ofInstant(
expireAt.toInstant(),
ZoneId.systemDefault()
)
tokenService.saveToken(
token = token,
username = username,
expiresAt = LocalDateTime.ofInstant(
expireAt.toInstant(),
ZoneId.systemDefault()
)
)
.thenReturn(token)
).thenReturn(token)
} else {
Mono.error(AuthException("Invalid credentials"))
}
@@ -51,16 +45,21 @@ class AuthService(
@Cacheable("tokens")
fun isTokenValid(token: String): Mono<User> {
// print("checking token: $token")
return tokenRepo.findByToken(token)
.flatMap {
if (it.status == TokenStatus.ACTIVE &&
it.expiresAt.isAfter(LocalDateTime.now())
) {
userRepository.findByUsername(it.username)
} else {
Mono.error(AuthException("Token expired"))
return tokenService.getToken(token)
.flatMap { tokenDetails ->
when {
tokenDetails.status == TokenStatus.ACTIVE && tokenDetails.expiresAt.isAfter(LocalDateTime.now()) -> {
userRepository.findByUsername(tokenDetails.username)
.switchIfEmpty(Mono.error(AuthException("User not found for token")))
}
else -> {
tokenService.revokeToken(token)
.then(Mono.error(AuthException("Token expired or inactive")))
}
}
}.switchIfEmpty(Mono.error(AuthException("User not found")))
}
.switchIfEmpty(Mono.error(AuthException("Token not found")))
}
}

View File

@@ -21,6 +21,10 @@ class TokenService(private val tokenRepository: TokenRepo) {
return tokenRepository.save(newToken)
}
fun getToken(token: String): Mono<Token> {
return tokenRepository.findByToken(token)
}
@CacheEvict("tokens", allEntries = true)
fun revokeToken(token: String): Mono<Void> {
return tokenRepository.findByToken(token)