Refactor jwt
This commit is contained in:
@@ -1,28 +1,33 @@
|
||||
package be.simplenotes.domain.security
|
||||
|
||||
import be.simplenotes.config.JwtConfig
|
||||
import be.simplenotes.types.LoggedInUser
|
||||
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
|
||||
|
||||
internal const val userIdField = "i"
|
||||
internal const val usernameField = "u"
|
||||
|
||||
@Singleton
|
||||
class SimpleJwt(jwtConfig: JwtConfig) {
|
||||
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()
|
||||
|
||||
val verifier: JWTVerifier = JWT.require(algorithm).build()
|
||||
fun sign(loggedInUser: LoggedInUser): String = JWT.create()
|
||||
.withClaim(userIdField, loggedInUser.userId)
|
||||
.withClaim(usernameField, loggedInUser.username)
|
||||
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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user