如何在Play中组合体解析器和安全性

时间:2013-02-04 14:09:22

标签: scala functional-programming playframework-2.0 playframework-2.1

我正在使用示例项目中ZenTask中实现的安全解决方案的变体:

目标是合并withAuthAction(parse.json),但我无法弄清楚如何。

我的安全特性

def withAuth(f: => Int => Request[AnyContent] => Result) = {
    Security.Authenticated(userid, onUnauthorized) { userid =>
      Action(request => f(userid.toInt)(request))
    }
  }

我想像我通常那样使用内置解析器中的游戏:

def newReport() = Action(parse.json) { request =>

而不是在我的Controller中手动将主体解析为json。

def newReport() = withAuth { userId =>
    { request =>
      request.body.asJson match {
        case Some(json) =>
          json.validate[Report](Reports.readsWithoutUser).map {
            case _: Report =>
              Reports.newReport(_)
              Ok("")
          }.recoverTotal {
            e =>
              val errors = JsError.toFlatJson(e)
              Logger.error(errors.toString)
              BadRequest("Detected error:" + errors)
          }
        case None => BadRequest("Json object missing from request")
      }
    }

1 个答案:

答案 0 :(得分:3)

然后你应该只使用带有正文解析器的重载Action(apply[A](bodyParser: BodyParser[A])(block: Request[A] => Result))。

def withAuth[A](p: BodyParser[A])(f: => Int => Request[A] => Result): Action[(Action[A], A)] = {
  Security.Authenticated(userid, onUnauthorized) { userid =>
    Action(p)(request => f(userid.toInt)(request))
  }
}

// Convenience for when you don't need a BP
def withAuth(f: => Int => Request[AnyContent] => Result): Action[(Action[AnyContent], AnyContent)] = {
  withAuth(BodyParsers.parse.anyContent)(f)
}