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?
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With