hello all, I have been working with custom plugin ...
# ktor
p
hello all, I have been working with custom plugin for scope authorization and got stuck due to Duplicate plugin exception. It can be solved with by naming all instances uniquely, but it feels like an antipattern and have bad feeling that it will have some serious performance issue. is there any better way to handle it
Copy code
requireScope(ApiV1Path.SCOPE, UserPath.SCOPE, AvatarPath.SCOPE) {
    post<AvatarPath, ByteArray> { _, data ->
        this@UserResource.onAuthenticate {
            val response = this@UserResource.updateUserAvatar(data = data)
            call.respond(apiResponse = response)
        }
    }
}
b
we've been talking about introducing a general solution for this https://youtrack.jetbrains.com/issue/KTOR-9746/Allow-re-applying-route-scoped-plugins but for the time being, you can use your DSL function to check and apply as needed like with the routing plugin:
Copy code
public fun Application.routing(configuration: Routing.() -> Unit): RoutingRoot =
    pluginOrNull(RoutingRoot)?.apply(configuration) ?: install(RoutingRoot, configuration)
👍 2
you might also want to check out https://github.com/ktorio/ktor/pull/5565 and https://github.com/ktorio/ktor-klip/pull/6 to see if there's some overlap with the plugin you're working on and maybe suggest any changes that'd help solve your problem... it looks a bit like the role-based authorization we're implementing
👍 2
p
thank you Bruce, I'll check this out
a
You can create a child route with a transparent route selector to make each plugin installation unique. Here is an example:
Copy code
fun main() {
    embeddedServer(Netty, 8083) {
        routing {
            requireScope("scope1", "scope2") {
                get {
                    call.respondText("GET")
                }
            }

            requireScope("scope3", "scope4") {
                post {
                    call.respondText("POST")
                }
            }

        }
    }.start(wait = true)
}

fun Route.requireScope(vararg paths: String, block: Route.() -> Unit): Route {
    val selector = MySelector()
    val route = createChild(selector)
    route.install(createRouteScopedPlugin("Authorization") {
        onCall {
            println(paths.contentToString())
        }
    })
    route.block()
    return route
}

class MySelector: RouteSelector() {
    override suspend fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation {
        return RouteSelectorEvaluation.Transparent
    }
}