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 PMEman
04/27/2023, 1:45 PMedrd
04/27/2023, 2:07 PMedrd
04/27/2023, 2:13 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)
}
edrd
04/27/2023, 2:18 PMuserId
claim is always required, you should probably move this check to the validate
method of the JWT authenticatorEman
04/27/2023, 3:13 PMEman
04/27/2023, 4:32 PMedrd
04/27/2023, 5:59 PMApplicationCall.(UserId) -> Unit
edrd
04/27/2023, 5:59 PMedrd
04/27/2023, 5:59 PMedrd
04/27/2023, 6:01 PMEman
04/28/2023, 12:36 PMEman
04/28/2023, 12:37 PMEman
04/29/2023, 10:05 AMsuspend 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)
}