44 lines
1.4 KiB
Kotlin
44 lines
1.4 KiB
Kotlin
package space.luminic.budgerapp.services
|
|
import org.springframework.cache.annotation.CacheEvict
|
|
import org.springframework.stereotype.Service
|
|
import reactor.core.publisher.Mono
|
|
import space.luminic.budgerapp.models.Token
|
|
import space.luminic.budgerapp.models.TokenStatus
|
|
import space.luminic.budgerapp.repos.TokenRepo
|
|
import java.time.LocalDateTime
|
|
|
|
@Service
|
|
class TokenService(private val tokenRepository: TokenRepo) {
|
|
|
|
@CacheEvict("tokens", allEntries = true)
|
|
fun saveToken(token: String, username: String, expiresAt: LocalDateTime): Mono<Token> {
|
|
val newToken = Token(
|
|
token = token,
|
|
username = username,
|
|
issuedAt = LocalDateTime.now(),
|
|
expiresAt = expiresAt
|
|
)
|
|
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)
|
|
.switchIfEmpty(Mono.error(Exception("Token not found")))
|
|
.flatMap { existingToken ->
|
|
val updatedToken = existingToken.copy(status = TokenStatus.REVOKED)
|
|
tokenRepository.save(updatedToken).then()
|
|
}
|
|
|
|
}
|
|
|
|
|
|
@CacheEvict("tokens", allEntries = true)
|
|
fun deleteExpiredTokens() {
|
|
tokenRepository.deleteByExpiresAtBefore(LocalDateTime.now())
|
|
}
|
|
} |