将ActionBuilder与securesocial SecuredAction一起使用

时间:2013-11-22 13:42:13

标签: scala playframework playframework-2.2 securesocial

我正在使用带有securesocial的play 2.2.1,我的许多操作都是使用securesocial提供的SecuredAction进行身份验证的。

现在我想为特定类型的请求创建ActionBuilder,例如文档中的ItemAction。

我尝试做这样的事情

  /**
   * ActionBuilder for use with actions that use Item objects.
   */
  def ItemAction() = new ActionBuilder[RequestWithItem] {
    def invokeBlock[A](request: SecuredRequest[A], block: (RequestWithItem[A]) => Future[SimpleResult]) = {
      val futureItem = itemsCollection.
        find(Json.obj("identityId" -> request.user.identityId)).one[Item]
      futureItem.flatMap { maybeItem =>
        maybeItem match {
          case Some(item) => {
            block(new RequestWithItem(item, request))
          }
          case _ => Future(BadRequest("could not get a item for this user."))
        }
      }
    }
  }

我得到了这个编译错误

 object creation impossible, since method invokeBlock in trait ActionBuilder of type [A](request: play.api.mvc.Request[A], block: models.RequestWithitem[A] => scala.concurrent.Future[play.api.mvc.SimpleResult])scala.concurrent.Future[play.api.mvc.SimpleResult] is not defined

我知道invokeBlock应该使用play.api.mvc.Request[A]代替securesocial.core.SecuredRequest[A],但我无法让它工作。

1 个答案:

答案 0 :(得分:4)

假设你想用SecuredAction(通过SecureSocial)编写ItemAction,这将是一种方法:

case class Item(id: Long) // replace with your real world item

def SecuredItemAction(f: => Item => Request[AnyContent] => Result) = 
  SecuredAction { implicit request =>
  val item = Some(new Item(7)) // replace with your real world item fetch
  item.map { item =>
    f(item)(request)
  }.getOrElse(NotFound)
}

然后您可以通过以下方式使用它:

def index = SecuredItemAction { item =>
  implicit request =>
    Ok(item.id.toString)
}