How to combine parser and security in Play
I'm using a variation of the security solution implemented in ZenTask in the sample project:
The goal is to combine withAuth
and Action(parse.json)
, but I can't figure out how.
My safety property
def withAuth(f: => Int => Request[AnyContent] => Result) = { Security.Authenticated(userid, onUnauthorized) { userid => Action(request => f(userid.toInt)(request)) } }
I want to use the pieces created in the body parser as usual:
def newReport() = Action(parse.json) { request =>
Instead of manually parsing the body to json in my controller.
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")
}
}
+3
source to share
1 answer
Then you should just use the overloaded action that the body parser ( apply[A](bodyParser: BodyParser[A])(block: Request[A] => Result)
) takes .
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)
}
+3
source to share