Bertram Kirsch
03/19/2021, 4:15 PMunderpants()
and groot()
?
class SomeApp {
fun Application.main(testing: Boolean = false) {
when {
isDev -> {
// For dev environment only
routing {
groot()
underpants()
}
}
isProd -> {
// Do things only in prod
routing {
authenticate {
groot()
underpants()
}
}
}
}
// Do things for all the environments
install(ContentNegotiation) {
gson {
setPrettyPrinting()
}
}
}
}
fun Route.groot(
) {
get("/api/groot") {
val map: HashMap<Int, String> = hashMapOf(1 to "I", 2 to "am", 3 to "groot!")
call.respond(map)
}
}
:
:
Marius Weidner
03/20/2021, 2:14 PMBertram Kirsch
03/20/2021, 4:54 PMRoute.authenticate()
has a parameter optional: Boolean = false
.
So, thank you for pointing me into the right direction, I ended up with this:
class SomeApp {
fun Application.main(testing: Boolean = false) {
var authOptional = testing
when {
isDev -> {
// For dev environment only
install(ContentNegotiation) {
gson {
setPrettyPrinting()
}
}
install(Authentication) {
basic {
realm = "devMode"
validate { credentials ->
UserIdPrincipal("developer")
}
}
}
authOptional = true
}
isProd -> {
// Do things only in prod
}
}
// Do things for all the environments
routing {
authenticate(optional = authOptional) {
groot()
}
}
}
}
In prod mode, feature Authentication
is installed by some other application. In dev mode Authentication
is provided by the basic auth implemented here. Actually, in dev mode it is never called, but authenticate() throws MissingApplicationFeatureException
if no Authentication
is presentJoost Klitsie
03/21/2021, 10:33 AMJoost Klitsie
03/21/2021, 10:33 AMMarius Weidner
03/21/2021, 10:34 AMBertram Kirsch
03/21/2021, 11:19 AMe5l
03/22/2021, 7:55 AMfun Routing.myAuthenticate(isDev: Boolean, block: Routing.() -> Unit) {
if (isDev) {
authenticate {
block()
}
} else {
block()
}
}
Bertram Kirsch
03/22/2021, 8:19 AMmyAuthenticate()
is the Routing block passed.
routing {
myAuthenticate(isDev = true){
groot()
}
}
fun Routing.myAuthenticate(isDev: Boolean, block: Routing.() -> Unit) {
if (isDev) {
authenticate {
this@myAuthenticate.block()
}
} else {
this@myAuthenticate.block()
}
}
There was one compile error:
Kotlin: Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
public abstract operator fun Routing.invoke(): Unit defined in kotlin.Function1
IDEA inserted this@myAuthenticate
when I applied the proposed IDE fix.e5l
03/22/2021, 8:22 AM