Add new route /user/me
This commit is contained in:
@@ -2,8 +2,10 @@ package be.vandewalleh.routing
|
||||
|
||||
import be.vandewalleh.auth.SimpleJWT
|
||||
import be.vandewalleh.auth.UsernamePasswordCredential
|
||||
import be.vandewalleh.extensions.respondStatus
|
||||
import be.vandewalleh.services.UserService
|
||||
import io.ktor.application.*
|
||||
import io.ktor.auth.*
|
||||
import io.ktor.http.*
|
||||
import io.ktor.request.*
|
||||
import io.ktor.response.*
|
||||
@@ -18,20 +20,27 @@ fun Routing.login(kodein: Kodein) {
|
||||
|
||||
data class TokenResponse(val token: String)
|
||||
|
||||
route("/user/login"){
|
||||
post {
|
||||
val credential = call.receive<UsernamePasswordCredential>()
|
||||
post("/user/login") {
|
||||
val credential = call.receive<UsernamePasswordCredential>()
|
||||
|
||||
val (email, password) = userService.getEmailAndPasswordFromUsername(credential.username)
|
||||
?: return@post call.respond(HttpStatusCode.Unauthorized)
|
||||
val (email, password) = userService.getEmailAndPasswordFromUsername(credential.username)
|
||||
?: return@post call.respond(HttpStatusCode.Unauthorized)
|
||||
|
||||
if (!BCrypt.checkpw(credential.password, password)) {
|
||||
return@post call.respond(HttpStatusCode.Unauthorized)
|
||||
}
|
||||
if (!BCrypt.checkpw(credential.password, password)) {
|
||||
return@post call.respond(HttpStatusCode.Unauthorized)
|
||||
}
|
||||
|
||||
return@post call.respond(TokenResponse(simpleJwt.sign(email)))
|
||||
return@post call.respond(TokenResponse(simpleJwt.sign(email)))
|
||||
}
|
||||
|
||||
authenticate {
|
||||
get("/user/me") {
|
||||
// retrieve email from token
|
||||
val email = call.principal<UserIdPrincipal>()!!.name
|
||||
val info = userService.getUserInfo(email)
|
||||
if (info != null) call.respond(mapOf("user" to info))
|
||||
else call.respondStatus(HttpStatusCode.Unauthorized)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user