简体   繁体   中英

Scala and Play framework 2.2.0, Action.async and isAuthenticated

I have an app using the isAuthenticated pattern described in the zentasks example. It's also using Future/Async to minimize blocking...

  def index = isAuthenticated { username => implicit request =>        
    val promise = 
      Future {
        Foo.all()    
      }
    Async {
      promise.map(f => Ok(views.html.foo.index(username, f)))
    }        
  }

This continues to work in Play 2.2.0 but the Future/Async pattern is deprecated. We're supposed to use Action.async; something like:

  def asyncTest = Action.async {
    val fut = Future {
      // Artificial delay to test.
      Thread.sleep(5000)
      "McFly"
    }
    fut.map (f => Ok(f))      
  }

My question is; how would I use Action.async with the authentication method above, or something similar?

One option would be to use Action Composition by defining IsAuthenticated like so:

def username(request: RequestHeader) = request.session.get("email")

def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.Application.login)

def IsAuthenticated(f: => String => Request[AnyContent] => Future[SimpleResult]) = {
  Action.async { request =>
    username(request).map { login =>
      f(login)(request)        
    }.getOrElse(Future.successful(onUnauthorized(request)))
  }
}

And then you could use it in the following way:

def index = IsAuthenticated { user => implicit request =>
  val fut = Future {
    // Artificial delay to test.
    Thread.sleep(5000)
    "McFly"
  }
  fut.map (f => Ok(f))      
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM