Replaced hardcoded mapping with reflection (yay reflection)

This commit is contained in:
grimsi
2024-09-26 17:00:56 +02:00
parent b28b5d048c
commit c864a6a491
3 changed files with 9 additions and 15 deletions
@@ -17,7 +17,7 @@ abstract class TokenService<T : TokenType>(
) )
tokenRepository.findByUserAndType(user, type)?.let { tokenRepository.findByUserAndType(user, type)?.let {
log.warn { "Deleting existing '${it.type}' token for user '${user.username}'" } log.warn { "Deleting existing ${it.type.key} token for user '${user.username}'" }
delete(it) delete(it)
} }
@@ -1,20 +1,13 @@
package de.grimsi.gameyfin.shared.token package de.grimsi.gameyfin.shared.token
import java.io.Serializable
import kotlin.time.Duration import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.minutes
sealed class TokenType( sealed class TokenType(
val key: String, val key: String,
val expiration: Duration val expiration: Duration
) : Serializable { ) {
data object PasswordReset : TokenType("password-reset", 15.minutes) data object PasswordReset : TokenType("password-reset", 15.minutes)
data object EmailVerification : TokenType("email-verification", Duration.INFINITE) data object EmailVerification : TokenType("email-verification", Duration.INFINITE)
data object Invitation : TokenType("invitation", Duration.INFINITE) data object Invitation : TokenType("invitation", Duration.INFINITE)
fun readResolve(): Any = when (this) {
PasswordReset -> PasswordReset
EmailVerification -> EmailVerification
Invitation -> Invitation
}
} }
@@ -6,6 +6,7 @@ import java.io.Serializable
import java.sql.PreparedStatement import java.sql.PreparedStatement
import java.sql.ResultSet import java.sql.ResultSet
import java.sql.Types import java.sql.Types
import kotlin.reflect.full.createInstance
class TokenTypeUserType : UserType<TokenType> { class TokenTypeUserType : UserType<TokenType> {
@@ -24,12 +25,12 @@ class TokenTypeUserType : UserType<TokenType> {
owner: Any? owner: Any?
): TokenType? { ): TokenType? {
val key = rs.getString(position) ?: return null val key = rs.getString(position) ?: return null
return when (key) { val tokenTypeClass = TokenType::class
TokenType.PasswordReset.key -> TokenType.PasswordReset
TokenType.EmailVerification.key -> TokenType.EmailVerification return tokenTypeClass.sealedSubclasses
TokenType.Invitation.key -> TokenType.Invitation .map { it.objectInstance ?: it.createInstance() }
else -> throw IllegalArgumentException("Unknown TokenType key: $key") .firstOrNull { it.key == key }
} ?: throw IllegalArgumentException("Unknown TokenType: $key")
} }
override fun nullSafeSet( override fun nullSafeSet(