34 lines
1.1 KiB
Kotlin
34 lines
1.1 KiB
Kotlin
package be.simplenotes.domain.security
|
|
|
|
import be.simplenotes.config.JwtConfig
|
|
import com.auth0.jwt.JWT
|
|
import com.auth0.jwt.JWTVerifier
|
|
import com.auth0.jwt.algorithms.Algorithm
|
|
import com.auth0.jwt.exceptions.JWTVerificationException
|
|
import java.util.*
|
|
import java.util.concurrent.TimeUnit
|
|
import javax.inject.Singleton
|
|
|
|
@Singleton
|
|
class SimpleJwt<T>(jwtConfig: JwtConfig, private val mapper: JwtMapper<T>) {
|
|
private val validityInMs = TimeUnit.MILLISECONDS.convert(jwtConfig.validity, jwtConfig.timeUnit)
|
|
private val algorithm = Algorithm.HMAC256(jwtConfig.secret)
|
|
private val verifier: JWTVerifier = JWT.require(algorithm).build()
|
|
|
|
fun sign(value: T): String = JWT.create()
|
|
.apply { mapper.build(this, value) }
|
|
.withExpiresAt(getExpiration())
|
|
.sign(algorithm)
|
|
|
|
fun extract(token: String): T? = try {
|
|
val decodedJWT = verifier.verify(token)
|
|
mapper.extract(decodedJWT)
|
|
} catch (e: JWTVerificationException) {
|
|
null
|
|
} catch (e: IllegalArgumentException) {
|
|
null
|
|
}
|
|
|
|
private fun getExpiration() = Date(System.currentTimeMillis() + validityInMs)
|
|
}
|