3

我在示例项目中使用 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 =>

而不是在我的控制器中手动将正文解析为 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")
      }
    }
4

1 回答 1

3

然后,您应该简单地使用带有主体解析器 ( apply[A](bodyParser: BodyParser[A])(block: Request[A] => Result)) 的重载 Action。

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)
}
于 2013-02-04T18:16:34.247 回答