Question

I have a global filter that I would like to implement in my scalatra based API. For the sake of simplicity, I want ANY API call that has a variable foo with a value bar to throw a 403. I started this problem with an inheritance chain.

class NoFooBarRouter extends ScalatraServlet{
    before() {
        if(params.getOrElse("foo", "") == "bar") //params is empty here. 
            halt(403, "You are not allowed here")
        else
            pass()
    }  
}

class APIRouter extends NoFooBarRouter{
    get("/someurl/:foo") {
        "Hello world!"
    }        
}

This does not work. During the debug process, I noticed that the params variable is always empty regardless of whether there is a param or not. Is there a better approach or is there another method to extract the params from the before filter?

Was it helpful?

Solution

The params are not filled out during the before method. You can override the invoke method.

class NoFooBarRouter extends ScalatraServlet{
    override def invoke(matchedRoute: MatchedRoute): Option[Any] = {
        withRouteMultiParams(Some(matchedRoute)){
            val foo = params.getOrElse("foo", "")
            if(foo =="bar")
                halt(403, "You are not authorized for the requested client.")
            else
                NoFooBarRouter.super.invoke(matchedRoute)
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top