Scala和Play framework 2.2.0、Action.async和isAuthenticated
我有一个应用程序使用zentasks示例中描述的isAuthenticated模式。 它还使用Future/Async来最小化阻塞Scala和Play framework 2.2.0、Action.async和isAuthenticated,scala,asynchronous,playframework-2.0,Scala,Asynchronous,Playframework 2.0,我有一个应用程序使用zentasks示例中描述的isAuthenticated模式。 它还使用Future/Async来最小化阻塞 def index = isAuthenticated { username => implicit request => val promise = Future { Foo.all() } Async { promise.map(f => Ok(v
def index = isAuthenticated { username => implicit request =>
val promise =
Future {
Foo.all()
}
Async {
promise.map(f => Ok(views.html.foo.index(username, f)))
}
}
这在Play 2.2.0中仍然有效,但不推荐使用Future/Async模式。我们应该使用Action.async;比如:
def asyncTest = Action.async {
val fut = Future {
// Artificial delay to test.
Thread.sleep(5000)
"McFly"
}
fut.map (f => Ok(f))
}
我的问题是,;如何将Action.async与上述身份验证方法或类似方法结合使用?一个选项是通过定义
IsAuthenticated
来使用,如下所示:
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)))
}
}
然后你可以用以下方式使用它:
def index = IsAuthenticated { user => implicit request =>
val fut = Future {
// Artificial delay to test.
Thread.sleep(5000)
"McFly"
}
fut.map (f => Ok(f))
}
工作完美,让我深入了解这些东西的实际工作原理。谢谢