diff --git a/api/src/routing/LoginController.kt b/api/src/routing/LoginController.kt index cf626b5..78c7be2 100644 --- a/api/src/routing/LoginController.kt +++ b/api/src/routing/LoginController.kt @@ -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() + post("/user/login") { + val credential = call.receive() - 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()!!.name + val info = userService.getUserInfo(email) + if (info != null) call.respond(mapOf("user" to info)) + else call.respondStatus(HttpStatusCode.Unauthorized) } } - } \ No newline at end of file diff --git a/api/src/services/UserService.kt b/api/src/services/UserService.kt index f7020ac..75a6063 100644 --- a/api/src/services/UserService.kt +++ b/api/src/services/UserService.kt @@ -48,6 +48,15 @@ class UserService(override val kodein: Kodein) : KodeinAware { .firstOrNull() != null } + fun getUserInfo(email: String): UserInfoDto? { + return db.from(Users) + .select(Users.email, Users.username) + .where { Users.email eq email } + .limit(0, 1) + .map { UserInfoDto(it[Users.username]!!, it[Users.email]!!) } + .firstOrNull() + } + /** * create a new user * password should already be hashed @@ -85,4 +94,5 @@ class UserService(override val kodein: Kodein) : KodeinAware { } } -data class UserDto(val username: String, val email: String, val password: String) \ No newline at end of file +data class UserDto(val username: String, val email: String, val password: String) +data class UserInfoDto(val username: String, val email: String) \ No newline at end of file