Eman
04/27/2023, 10:34 AMpost("api/auth/endpoint") {
// start - block of code that is repeated
val principal = call.principal<JWTPrincipal>()
val userId = principal?.getClaim("userId", String::class)
if (userId == null) {
call.respond(
HttpStatusCode.Forbidden,
CyrCloError(401, "User not authenticated. Please login in again")
)
return@post
}
// end
}
how can this code refactored? because i have been keep repeating that code to my other endpoints
Thanks,edrd
04/27/2023, 1:24 PMEman
04/27/2023, 1:44 PMedrd
04/27/2023, 2:07 PM@JvmInline
value class UserId(val value: String)
fun <http://Routing.post|Routing.post>(path: String, handle: (UserId) -> Unit) {
post(path) {
val principal = ...
val userId = ...
// ... null check + return
handle(userId)
}
}
// Then in your routers
post("/api/auth/endpoint") { userId ->
doSomething(userId)
}
userId
claim is always required, you should probably move this check to the validate
method of the JWT authenticatorEman
04/27/2023, 3:13 PMedrd
04/27/2023, 5:59 PMApplicationCall.(UserId) -> Unit
Eman
04/28/2023, 12:36 PMsuspend fun ApplicationCall.getUserId(handleUser: (String) -> Unit) {
val principal = principal<JWTPrincipal>()
val userId = principal?.getClaim("userId", String::class)
if (userId == null) {
respond(
HttpStatusCode.Forbidden,
CyrCloError(401, "User not authenticated. Please login in again")
)
return@getUserId
}
handleUser(userId)
}