token auth

This commit is contained in:
Aria Moradi
2022-04-16 18:26:44 +04:30
parent a26b8ecca0
commit 53c3ac5676
3 changed files with 18 additions and 5 deletions

View File

@@ -56,14 +56,16 @@ object JavalinSetup {
config.enableCorsForAllOrigins()
config.accessManager { handler, ctx, _ ->
fun credentialsValid(): Boolean {
fun basicAuthCredentialsValid(): Boolean {
val (username, password) = ctx.basicAuthCredentials()
return username == serverConfig.basicAuthUsername && password == serverConfig.basicAuthPassword
}
if (serverConfig.basicAuthEnabled && !(ctx.basicAuthCredentialsExist() && credentialsValid())) {
ctx.header("WWW-Authenticate", "Basic")
ctx.status(401).json("Unauthorized")
if (serverConfig.authType != "none") {
if (serverConfig.authType == "basicAuth" && !(ctx.basicAuthCredentialsExist() && basicAuthCredentialsValid())) {
ctx.header("WWW-Authenticate", "Basic")
ctx.status(401).json("Unauthorized")
}
} else {
handler.handle(ctx)
}

View File

@@ -11,6 +11,7 @@ import com.typesafe.config.Config
import xyz.nulldev.ts.config.GlobalConfigManager
import xyz.nulldev.ts.config.SystemPropertyOverridableConfigModule
import xyz.nulldev.ts.config.debugLogsEnabled
import kotlin.reflect.KProperty
private const val MODULE_NAME = "server"
class ServerConfig(config: Config, moduleName: String = MODULE_NAME) : SystemPropertyOverridableConfigModule(config, moduleName) {
@@ -34,6 +35,15 @@ class ServerConfig(config: Config, moduleName: String = MODULE_NAME) : SystemPro
val electronPath: String by overridableConfig
// Authentication
val authType: String by object {
operator fun <R> getValue(thisRef: R, property: KProperty<*>): String {
val propValue: String = overridableConfig.getValue(thisRef, property)
if (basicAuthEnabled) {
return "basicAuth"
}
return propValue
}
}
val basicAuthEnabled: Boolean by overridableConfig
val basicAuthUsername: String by overridableConfig
val basicAuthPassword: String by overridableConfig

View File

@@ -14,7 +14,8 @@ server.webUIInterface = "browser" # "browser" or "electron"
server.electronPath = ""
# Authentication
server.basicAuthEnabled = false
server.authType = "none" # "none" or "basicAuth" or "token"
server.basicAuthEnabled = false # This is deprecated, use server.authType
server.basicAuthUsername = ""
server.basicAuthPassword = ""