core/features/roles/server/src/jvmMain/kotlin/dev/inmo/postssystem/features/roles/server/UsersRolesAuthenticationConfigurator.kt

39 lines
1.5 KiB
Kotlin
Raw Normal View History

2021-11-24 07:52:27 +00:00
package dev.inmo.postssystem.features.roles.server
import dev.inmo.postssystem.features.auth.common.AuthToken
import dev.inmo.postssystem.features.auth.server.principal
import dev.inmo.postssystem.features.auth.server.tokens.AuthTokensService
import dev.inmo.postssystem.features.common.server.sessions.ApplicationAuthenticationConfigurator
2021-11-27 19:11:04 +00:00
import dev.inmo.postssystem.features.roles.common.Role
import dev.inmo.postssystem.features.roles.common.RolesStorage
2021-11-24 07:52:27 +00:00
import io.ktor.http.HttpStatusCode
2022-05-07 14:48:17 +00:00
import io.ktor.server.auth.*
import io.ktor.server.response.respond
2021-11-24 07:52:27 +00:00
2021-11-27 19:11:04 +00:00
class RolesAuthenticationConfigurator<T : Role>(
private val usersRolesStorage: RolesStorage<T>,
2021-11-24 07:52:27 +00:00
private val authTokensService: AuthTokensService,
2021-11-27 19:11:04 +00:00
private val rolesCheckers: List<RolesChecker<T>>
2021-11-24 07:52:27 +00:00
) : ApplicationAuthenticationConfigurator.Element {
2022-05-07 14:48:17 +00:00
override fun AuthenticationConfig.invoke() {
2021-11-24 07:52:27 +00:00
rolesCheckers.forEach { checker ->
session<AuthToken>(checker.key) {
validate {
val result = authTokensService.getUserPrincipal(it)
if (result.isSuccess) {
val user = result.getOrThrow().principal()
if (checker.run { invoke(usersRolesStorage, user.user) }) {
user
} else {
null
}
} else {
null
}
}
challenge { call.respond(HttpStatusCode.Unauthorized) }
}
}
}
}