Added role token creation
This commit is contained in:
@@ -3,6 +3,7 @@ package codes.kalar.routes
|
||||
import codes.kalar.exception.DbElementNotFoundException
|
||||
import codes.kalar.model.User
|
||||
import codes.kalar.service.PatronService
|
||||
import codes.kalar.service.StaffService
|
||||
import com.auth0.jwt.JWT
|
||||
import com.auth0.jwt.algorithms.Algorithm
|
||||
import io.ktor.http.HttpStatusCode
|
||||
@@ -18,8 +19,10 @@ 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 auth0Map = mapOf("secret" to secret, "issuer" to issuer, "audience" to audience)
|
||||
|
||||
val patronService = PatronService(dbConnection)
|
||||
val staffService = StaffService(dbConnection)
|
||||
routing {
|
||||
post("/login") {
|
||||
try {
|
||||
@@ -28,14 +31,14 @@ fun Application.configureLoginRoutes(dbConnection: Connection) {
|
||||
val password = user.password
|
||||
|
||||
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 {
|
||||
val token = createToken(user.name, "patron", auth0Map)
|
||||
call.respond(HttpStatusCode.OK, mapOf("token" to token))
|
||||
}
|
||||
else if (staffService.loginStaffByLoginUsername(name, password)) {
|
||||
val token = createToken(user.name, "staff", auth0Map)
|
||||
call.respond(HttpStatusCode.OK, mapOf("token" to token))
|
||||
}
|
||||
else {
|
||||
call.respond(HttpStatusCode.Unauthorized, "Invalid login")
|
||||
}
|
||||
} catch (cause: DbElementNotFoundException) {
|
||||
@@ -44,4 +47,14 @@ fun Application.configureLoginRoutes(dbConnection: Connection) {
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun createToken(username: String, role: String, auth: Map<String, String>): String {
|
||||
return JWT.create()
|
||||
.withAudience(auth["audience"])
|
||||
.withIssuer(auth["issuer"])
|
||||
.withClaim("name", username)
|
||||
.withClaim("role", role)
|
||||
.withExpiresAt(Date(System.currentTimeMillis() + 160000))
|
||||
.sign(Algorithm.HMAC256(auth["secret"]))
|
||||
}
|
||||
Reference in New Issue
Block a user