https://kotlinlang.org logo
#ktor
Title
# ktor
d

Dávid

10/15/2020, 8:46 AM
Hey all. I googled and dug through docs and I am still a bit confused about this. I am trying to make an interceptor that will check if an authorized principal has rights to access a route based on roles. This is my interceptor, which I based on the one in the docs:
Copy code
fun Route.authorizedBy(roles: List<String>, callback: Route.() -> Route): Route {
    val routeWithRoles = this.createChild(object : RouteSelector(RouteSelectorEvaluation.qualityConstant) {
        override fun toString(): String {
            return "(roles: $roles)"
        }

        override fun evaluate(context: RoutingResolveContext, segmentIndex: Int): RouteSelectorEvaluation =
            RouteSelectorEvaluation.Constant
    })

    routeWithRoles.intercept(ApplicationCallPipeline.Call) {
        if (!hasAccess(roles, call.user)) {
            call.respond(HttpStatusCode.Unauthorized, "Not sufficient authority") //todo I am not sure if I should respond or throw errror
            finish() //todo i am not sure if I should call finish here
        }
    }

    callback(routeWithRoles)
    return routeWithRoles
}
1. In my code I am uncertain if I should throw an exception from the interceptor or is it ok to call the
respond
method? 2. Also is it necessary to call the
finish()
there? 3. Should I call
proceed()
in the
else
branch or is that not necessary? In general I think it is unclear when to use the proceed and finish methods and what is an intended way to break out of an interceptor with errors.
r

Rustam Siniukov

10/15/2020, 9:10 AM
d

Dávid

10/15/2020, 9:25 AM
Thanks and I found this. And I guess the answer is that I should throw exceptions, but @Rustam Siniukov do you know what is the use case for
finish
and
proceed
methods in the pipelines so I also learn from this?
r

Rustam Siniukov

10/15/2020, 9:38 AM
proceed
is needed when you want to do something at the end of pipeline execution. For example
Logging
feature calls it to log success or failure of the request.
finish
is needed when you already have response for the request and don’t need to execute rest of the pipeline. For example you got response from cache and don’t need to make an actual request
🙌 2
d

Dávid

10/15/2020, 9:39 AM
This one sentence should be in the docs 😄
Thanks!
👍 1