Play 2.0 Framework using BodyParser with authenticated request

I would like to be able to use BodyParser for an authenticated request, and it’s hard for me to figure out how to do this if my authentication is configured, as an example of ZenTasks.

My authentication method,

def IsAuthenticated(f: => String => Request[AnyContent] => Result) = { Security.Authenticated(username, onUnauthorized) { user => Action(request => f(user)(request)) } } def HasRole(role: List[String]) (f: => String => Request[AnyContent] => Result) = IsAuthenticated { user => request => if (role.contains(getRole(user))) { f(user)(request) // This function returns the result. } else { Results.Forbidden } } 

My management method,

 def controller = HasRole(List("admin")) { user => _ => { Action(parse.temporaryFile){ implicit request => request.body.moveTo(new File("/tmp/filepath")) Redirect(routes.home) } } 

This is the mistake that I see

 [error] found : play.api.mvc.Action[play.api.libs.Files.TemporaryFile] [error] required: play.api.mvc.Result [error] Action(parse.temporaryFile){ implicit request => [error] ^ 

Here's a related question: parse.json authenticated request for a game

This person has found a workaround, and I believe there is one example for a temporary file, but I would like to know how (or why) what I am doing does not work.

+6
source share
1 answer

I believe that I understood this, mainly because I left some details from the original question, which I did not understand, was important.

The problem was that I was wrapping Action { Action { } } because the IsAuthenticated method already had an Action function call inside it. What I ended up with was an overload of the IsAuthenticated function using the method that took BodyParser as a parameter. Since I use the TemporaryFile method, which is not a subclass of AnyContent , I also had to change the type of request.

Now here's what my Secured trait looks like:

 def IsAuthenticated(f: => String => Request[Any] => Result) = { Security.Authenticated(username, onUnauthorized) { user => Action(request => f(user)(request)) } } def IsAuthenticated(b: BodyParser[Any] = parse.anyContent) (f: => String => Request[Any] => Result) = { Security.Authenticated(username, onUnauthorized) { user => Action(b)(request => f(user)(request)) } } def HasRole(role: List[String])(b: BodyParser[Any] = parse.anyContent) (f: => String => Request[Any] => Result) = IsAuthenticated(b) { user => request => getRole(user) match { case Some(r) if role.contains(r) => f(user)(request) case _ => Results.Forbidden } } 

And here is what my controller looks like:

 def controller = HasRole(List("admin"))(parse.temporaryFile) { user => request => request.body match { case b:TemporaryFile => b.moveTo(new File("/tmp/file")) case _ => Status(404) } } 

Hope this helps someone else!

+6
source

Source: https://habr.com/ru/post/912652/


All Articles