Skip to content

Instantly share code, notes, and snippets.

@VEINHORN
Created March 28, 2018 12:11
Show Gist options
  • Save VEINHORN/b3a129499d9457b021f83b2a39e125e3 to your computer and use it in GitHub Desktop.
Save VEINHORN/b3a129499d9457b021f83b2a39e125e3 to your computer and use it in GitHub Desktop.
package models.auth
import play.api.mvc.Results.Unauthorized
import play.api.mvc.Security.AuthenticatedRequest
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
import scala.language.reflectiveCalls
class AsyncAuthenticatedBuilder[U](
userinfo: RequestHeader => Future[U], // Future[U] against Option[U]
defaultParser: BodyParser[AnyContent],
onUnauthorized: (RequestHeader, Throwable) => Result = _ => Unauthorized(views.html.defaultpages.unauthorized()))(implicit val executionContext: ExecutionContext) extends ActionBuilder[({ type R[A] = AuthenticatedRequest[A, U] })#R, AnyContent] {
lazy val parser = defaultParser
def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A, U]) => Future[Result]) =
authenticate(request, block)
/**
* Authenticate the block
*/
def authenticate[A](request: Request[A], block: (AuthenticatedRequest[A, U]) => Future[Result]) = {
userinfo(request).flatMap { user =>
block(new AuthenticatedRequest(user, request))
} recoverWith {
case t: Throwable => Future.successful[Result](onUnauthorized(request, t))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment