[英]Scala and Play framework 2.2.0, Action.async and isAuthenticated
我有一个使用zentasks示例中描述的isAuthenticated模式的应用程序。 它还使用Future / Async来最小化阻塞...
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
来使用Action Composition , 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))
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.