0
votes

I've implemented authentication action and put it in the beginning of every method in my controller def addFile(itemId: Long) = AuthenticatedAction.async(FSBodyParser(itemId)){ request => ...

Then I've implemented my own body parser based on MultipartFormData

 def FSBodyParser(itemId:Long): BodyParser[MultipartFormData[Future[BaseFileInfo]]] = {
    multipartFormData(Multipart.handleFilePart {
      case Multipart.FileInfo(partName, filename, contentType) =>
        //println(s"FileInfo($partName, $filename, $contentType)")
        getIteratee(1, itemId, filename, contentType)
    })
  }

And I found that my file is uploaded first and then authentication action check if user is valid. I would like to check user authentication fist and only after that save uploaded file.

Do you have any ideas how to implement this the best way? Probably using Play filters for authentication?

1

1 Answers

0
votes

I've implemented it as following (using EssentialAction)

def authenticate(): Future[Option[Long]] = {
    // here we should pass correct user id
    Future.successful(Some(421))
  }

  def Authenticated[A](action: Action[A]) = EssentialAction{ rh =>
    Iteratee.flatten(authenticate() map{
      case Some(userId) => action(rh)
      case None => Done(Results.Unauthorized)
    })
  }

 //this is method of my service
 //Authenticated is called before FSBodyParser starts working
 def addFile(itemId: Long) = Authenticated{
    Action.async(FSBodyParser(itemId)){ requestHeaders =>
      ItemRepository.addFile(1, itemId, null) map( fileId => Ok)
    }
  }