Search code examples
scalaasynchronousplayframework-2.4

Async version of AuthenticatedBuilder in play 2


I am trying to compose a basic authentication with some other action:

  def findByNameSecure(username: String) = Authenticated { _ =>
    val cursor: Cursor[JsObject] = persons.
      find(Json.obj("userdetails.username" -> username)).
      cursor[JsObject](ReadPreference.primary)
    val res = cursor.collect[List]().map { persons =>
      Ok(Json.toJson(persons))
    }   .recover {
      case _ => BadRequest(Json.parse("{'error': 'failed to read from db'}"))
    }
    Await.result(res, 10.seconds)
  }

Route:

 GET      /secure/user/findbyname     controllers.UserController.findByNameSecure(username: String)

This works as expected. What is disturbing is that I used Await.result which is blocking. How can I compose an async version of this kind of authentication?

I am using play 2.4.


Solution

  • AuthendicatedBuilder is child of ActionBuilder. So I supposed its async method should work as well.

    Example of usage:

    def findByNameSecure(username: String) = Authenticated.async { _ =>