Created
February 10, 2014 13:34
-
-
Save martinburger/8916027 to your computer and use it in GitHub Desktop.
How to wrap Actions (in any order) when using Play's ActionBuilder?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")) | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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