Scala和Play框架2.2.0,Action.async和isAuthenticated
发布时间:2020-12-16 08:55:52 所属栏目:安全 来源:网络整理
导读:我有一个使用zentasks示例中描述的isAuthenticated模式的应用程序. 它还使用Future / Async来最小化阻塞… def index = isAuthenticated { username = implicit request = val promise = Future { Foo.all() } Async { promise.map(f = Ok(views.html.foo.in
我有一个使用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,如下所示:
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)) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |