Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala and Play framework 2.2.0, Action.async and isAuthenticated

I have an app using the isAuthenticated pattern described in the zentasks example. It's also using 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're supposed to 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 would I use Action.async with the authentication method above, or something similar?

like image 235
seand Avatar asked Nov 12 '13 18:11

seand


1 Answers

One option would be to use Action Composition by defining IsAuthenticated like so:

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 could use it in the following way:

def index = IsAuthenticated { user => implicit request =>
  val fut = Future {
    // Artificial delay to test.
    Thread.sleep(5000)
    "McFly"
  }
  fut.map (f => Ok(f))      
}
like image 62
mantithetical Avatar answered Nov 15 '22 23:11

mantithetical