generated from pricelees/issue-pr-template
51 lines
2.1 KiB
Kotlin
51 lines
2.1 KiB
Kotlin
package roomescape.auth.infrastructure.jwt
|
|
|
|
import io.jsonwebtoken.*
|
|
import org.springframework.beans.factory.annotation.Value
|
|
import org.springframework.http.HttpStatus
|
|
import org.springframework.stereotype.Component
|
|
import roomescape.common.exception.ErrorType
|
|
import roomescape.common.exception.RoomEscapeException
|
|
import java.util.*
|
|
|
|
@Component
|
|
class JwtHandler(
|
|
@Value("\${security.jwt.token.secret-key}")
|
|
private val secretKey: String,
|
|
|
|
@Value("\${security.jwt.token.access.expire-length}")
|
|
private val accessTokenExpireTime: Long
|
|
) {
|
|
fun createToken(memberId: Long): String {
|
|
val date = Date()
|
|
val accessTokenExpiredAt = Date(date.time + accessTokenExpireTime)
|
|
|
|
return Jwts.builder()
|
|
.claim("memberId", memberId)
|
|
.setIssuedAt(date)
|
|
.setExpiration(accessTokenExpiredAt)
|
|
.signWith(SignatureAlgorithm.HS256, secretKey.toByteArray())
|
|
.compact()
|
|
}
|
|
|
|
fun getMemberIdFromToken(token: String?): Long {
|
|
try {
|
|
return Jwts.parser()
|
|
.setSigningKey(secretKey.toByteArray())
|
|
.parseClaimsJws(token)
|
|
.getBody()
|
|
.get("memberId", Number::class.java)
|
|
.toLong()
|
|
} catch (e: Exception) {
|
|
when (e) {
|
|
is ExpiredJwtException -> throw RoomEscapeException(ErrorType.EXPIRED_TOKEN, HttpStatus.UNAUTHORIZED)
|
|
is UnsupportedJwtException -> throw RoomEscapeException(ErrorType.UNSUPPORTED_TOKEN, HttpStatus.UNAUTHORIZED)
|
|
is MalformedJwtException -> throw RoomEscapeException(ErrorType.MALFORMED_TOKEN, HttpStatus.UNAUTHORIZED)
|
|
is SignatureException -> throw RoomEscapeException(ErrorType.INVALID_SIGNATURE_TOKEN, HttpStatus.UNAUTHORIZED)
|
|
is IllegalArgumentException -> throw RoomEscapeException(ErrorType.INVALID_TOKEN, HttpStatus.UNAUTHORIZED)
|
|
else -> throw RoomEscapeException(ErrorType.UNEXPECTED_ERROR, HttpStatus.INTERNAL_SERVER_ERROR)
|
|
}
|
|
}
|
|
}
|
|
}
|