Skip to content

Commit

Permalink
fix auth logic (#2)
Browse files Browse the repository at this point in the history
Co-authored-by: t1r <>
  • Loading branch information
t1r authored Dec 12, 2022
1 parent e7cb476 commit 68260a1
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 21 deletions.
12 changes: 1 addition & 11 deletions src/main/kotlin/dev/csworkshop/auth/AuthBasic.kt
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
package dev.csworkshop.auth

import dev.csworkshop.auth.AuthService.hashedUserTable
import io.ktor.server.auth.*
import io.ktor.util.*

internal val digestFunction = getDigestFunction("SHA-256") { "ktor${it.length}" }
internal val hashedUserTable = UserHashedTableAuth(
table = mapOf(
"jetbrains" to digestFunction("foobar"),
"admin" to digestFunction("password"),
"root" to digestFunction("root"),
),
digester = digestFunction
)

internal fun AuthenticationConfig.setupBasicAuth() {
basic(AUTH_CONFIGURATION_NAME) {
Expand Down
20 changes: 20 additions & 0 deletions src/main/kotlin/dev/csworkshop/auth/AuthService.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package dev.csworkshop.auth

import io.ktor.server.auth.*
import io.ktor.util.*

object AuthService {
internal val digestFunction = getDigestFunction("SHA-256") { "ktor${it.length}" }
private val credentialsMap = mutableMapOf(
"root" to digestFunction("root"),
)

internal val hashedUserTable = UserHashedTableAuth(
table = credentialsMap,
digester = digestFunction
)

fun addCredential(name: String, password: String) {
credentialsMap[name] = digestFunction(password)
}
}
15 changes: 5 additions & 10 deletions src/main/kotlin/dev/csworkshop/plugins/AuthBasic.kt
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package dev.csworkshop.plugins

import dev.csworkshop.auth.hashedUserTable
import dev.csworkshop.auth.AuthService
import dev.csworkshop.plugins.Constants.PREFIX_API
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
Expand All @@ -14,15 +13,11 @@ fun Application.authRouting() {
post("$PREFIX_API/auth") {
try {
val parameters = call.receiveParameters()
val name = parameters["name"]!!
val password = parameters["password"]!!
val name = parameters["name"]
val password = parameters["password"]
if (name.isNullOrBlank() || password.isNullOrBlank()) throw RuntimeException()

hashedUserTable.authenticate(
UserPasswordCredential(
name = name,
password = password,
)
)
AuthService.addCredential(name, password)
call.respondText("Auth successful", status = HttpStatusCode.OK)
} catch (throwable: Throwable) {
throwable.printStackTrace()
Expand Down

0 comments on commit 68260a1

Please sign in to comment.