diff --git a/src/main/kotlin/routes/LoginRoutes.kt b/src/main/kotlin/routes/LoginRoutes.kt index aa2e3ae..5877418 100644 --- a/src/main/kotlin/routes/LoginRoutes.kt +++ b/src/main/kotlin/routes/LoginRoutes.kt @@ -1,6 +1,8 @@ package codes.kalar.routes +import codes.kalar.exception.DbElementNotFoundException import codes.kalar.model.User +import codes.kalar.service.PatronService import com.auth0.jwt.JWT import com.auth0.jwt.algorithms.Algorithm import io.ktor.http.HttpStatusCode @@ -9,14 +11,16 @@ import io.ktor.server.request.receive import io.ktor.server.response.respond import io.ktor.server.routing.post import io.ktor.server.routing.routing +import java.sql.Connection import java.util.Date -fun Application.configureLoginRoutes() { +fun Application.configureLoginRoutes(dbConnection: Connection) { val secret = environment.config.property("jwt.secret").getString() val issuer = environment.config.property("jwt.issuer").getString() val audience = environment.config.property("jwt.audience").getString() val myRealm = environment.config.property("jwt.realm").getString() + val patronService = PatronService(dbConnection) routing { post("/login") { try { @@ -24,17 +28,19 @@ fun Application.configureLoginRoutes() { val name = user.name val password = user.password - // TODO Check is username exists and password matches - - val token = JWT.create() - .withAudience(audience) - .withIssuer(issuer) - .withClaim("name", name) - .withExpiresAt(Date(System.currentTimeMillis() + 160000)) - .sign(Algorithm.HMAC256(secret)) - call.respond(hashMapOf("token" to token)) - } catch (e: Exception) { - call.respond(HttpStatusCode.BadRequest, e.message ?: "Something went wrong") + if (patronService.loginPatronByLoginUsername(name, password)) { + val token = JWT.create() + .withAudience(audience) + .withIssuer(issuer) + .withClaim("name", name) + .withExpiresAt(Date(System.currentTimeMillis() + 160000)) + .sign(Algorithm.HMAC256(secret)) + call.respond(hashMapOf("token" to token)) + } else { + call.respond(HttpStatusCode.Unauthorized, "Invalid login") + } + } catch (cause: DbElementNotFoundException) { + call.respond(HttpStatusCode.BadRequest, cause.message ?: "Something went wrong") } }