Scala和Play框架2.2.0,Action.async和isAuthenticated

时间:2013-11-12 18:06:54

标签: 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(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与上面的身份验证方法或类似的东西一起使用?

1 个答案:

答案 0 :(得分:7)

一种选择是通过定义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))      
}