Added initial Login Routes

This commit is contained in:
2025-08-16 17:01:02 -04:00
parent 86590ebf27
commit e5f21844d8

View File

@@ -0,0 +1,42 @@
package codes.kalar.routes
import codes.kalar.model.User
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.*
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.util.Date
fun Application.configureLoginRoutes() {
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()
routing {
post("/login") {
try {
val user = call.receive<User>()
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")
}
}
}
}