Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@martinburger
Created February 10, 2014 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save martinburger/8916027 to your computer and use it in GitHub Desktop.
Save martinburger/8916027 to your computer and use it in GitHub Desktop.
How to wrap Actions (in any order) when using Play's ActionBuilder?
package controllers
import play.api._
import play.api.mvc._
import scala.concurrent.Future
/**
* Provide security features via `ActionBuilder`
*/
trait SecuredViaActionBuilder {
case class AuthRequest[A](user: String, request: Request[A]) extends WrappedRequest[A](request)
private[controllers] object IsAuthenticated extends ActionBuilder[AuthRequest] {
def invokeBlock[A](req: Request[A], block: (AuthRequest[A]) => Future[SimpleResult]) = {
req.session.get("user").map { user =>
block(new AuthRequest(user, req))
} getOrElse {
Future.successful(Results.Unauthorized("401 No user\n"))
}
}
}
case class TokenRequest[A](token: String, request: Request[A]) extends WrappedRequest[A](request)
private[controllers] object HasToken extends ActionBuilder[TokenRequest] {
def invokeBlock[A](request: Request[A], block: (TokenRequest[A]) => Future[SimpleResult]) = {
request.headers.get("X-TOKEN") map { token =>
block(TokenRequest(token, request))
} getOrElse {
Future.successful(Results.Unauthorized("401 No Security Token\n"))
}
}
}
}
package controllers
import play.api._
import play.api.mvc._
object ControllerActionComposition extends Controller with SecuredViaActionBuilder {
def auth = IsAuthenticated { implicit authRequest =>
val user = authRequest.user
Ok(user)
}
def token = HasToken { implicit tokeRequest =>
val token = tokeRequest.token
Ok(token)
}
// How to implement this?
// def tokenAndAuth = HasToken { implicit tokeRequest =>
// IsAuthenticated { implicit authRequest =>
// val token = tokeRequest.token
// val user = authRequest.user
// }
// }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment