Scala and Play Framework 2.2.0, Action.async and isAuthenticated

I have an application using the isAuthenticated template described in the zentasks example. It also uses Future / Async to minimize blocking ...

def index = isAuthenticated { username => implicit request => val promise = Future { Foo.all() } Async { promise.map(f => Ok(views.html.foo.index(username, f))) } } 

This continues to work in Play 2.2.0, but the Future / Async pattern is deprecated. We must use Action.async; something like:

  def asyncTest = Action.async { val fut = Future { // Artificial delay to test. Thread.sleep(5000) "McFly" } fut.map (f => Ok(f)) } 

My question is: how can I use Action.async with the above authentication method or something like that?

+8
asynchronous scala
source share
1 answer

One option is to use Action Composition , defining IsAuthenticated as follows:

 def username(request: RequestHeader) = request.session.get("email") def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login) def IsAuthenticated(f: => String => Request[AnyContent] => Future[SimpleResult]) = { Action.async { request => username(request).map { login => f(login)(request) }.getOrElse(Future.successful(onUnauthorized(request))) } } 

And then you can use it as follows:

 def index = IsAuthenticated { user => implicit request => val fut = Future { // Artificial delay to test. Thread.sleep(5000) "McFly" } fut.map (f => Ok(f)) } 
+7
source share

All Articles