Question

I'd like to add a (per method / global) filter to requests, that simply rejects (404/403 page) any request that doesn't have a specific URL parameter.

I know Play has one-two mechanism to do this (e.g. register on Global.onRouteRequest()), so don't just send me a link to the documentation unless it contains a code sample that covers this question. I tried playing with the API but got a bit stuck.

Was it helpful?

Solution

Is this what you mean?

object Global extends WithFilters(AccessCheck)

object AccessCheck extends Filter with Results {

  override def apply(next:RequestHeader => Result)(request:RequestHeader):Result =
    request
      .getQueryString("myCheck")
      .map( myCheck => next(request)) 
      .getOrElse(Forbidden)
}

http://www.playframework.com/documentation/2.1.0/ScalaInterceptors

OTHER TIPS

If you are just trying to make some reusable code to filter requests on specific actions you my want to try creating an EssentialAction like this. This is known as action composition. This is what it would look like in the case you described. There is more information in the docs: http://www.playframework.com/documentation/2.1.1/ScalaActionsComposition

Note that you can do this in Play 2.0.X as well but EssentialAction doesn't exist, instead you use an Action, and there is just a little more syntax involved.

def RequireMyCheck(action: => EssentialAction): EssentialAction = {
  EssentialAction { request =>
    request
      .getQueryString("myCheck")
      .map( myCheck => action()(request)) 
      .getOrElse(Forbidden)
  }
}

You can use it like this:

def index = RequireMyCheck {
  Action { request =>
    Ok("Hello")
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top