Play 2 - Set header on all responses? - scala

I'm aware from Setting HTTP headers in Play 2.0 (scala)? that you can set response headers on a case-by-case basis by doing, for example, Ok("hello").withHeaders(PRAGMA -> "no-cache").
What if you want to set that header, or a few different headers, on responses from all your Actions? You wouldn't want to repeat the withHeaders everywhere. And since this is more like an application-wide configuration, you might not want Action writers to have to use a different syntax to get your headers (e.g. OkWithHeaders(...))
What I have now is a base Controller class that looks like
class ContextController extends Controller {
...
def Ok(h: Html) = Results.Ok(h).withHeaders(PRAGMA -> "no-cache")
}
but that doesn't feel quite right. It feels like there should be more of an AOP-style way of defining the default headers and having them added to each response.

The topic is quite old now, but with Play 2.1 it is even simpler now.
Your Global.scala class should look like this :
import play.api._
import play.api.mvc._
import play.api.http.HeaderNames._
/**
* Global application settings.
*/
object Global extends GlobalSettings {
/**
* Global action composition.
*/
override def doFilter(action: EssentialAction): EssentialAction = EssentialAction { request =>
action.apply(request).map(_.withHeaders(
PRAGMA -> "no-cache"
))
}
}

In your Global.scala, wrap every call in an action:
import play.api._
import play.api.mvc._
import play.api.Play.current
import play.api.http.HeaderNames._
object Global extends GlobalSettings {
def NoCache[A](action: Action[A]): Action[A] = Action(action.parser) { request =>
action(request) match {
case s: SimpleResult[_] => s.withHeaders(PRAGMA -> "no-cache")
case result => result
}
}
override def onRouteRequest(request: RequestHeader): Option[Handler] = {
if (Play.isDev) {
super.onRouteRequest(request).map {
case action: Action[_] => NoCache(action)
case other => other
}
} else {
super.onRouteRequest(request)
}
}
}
In this case, I only call the action in dev mode, which makes most sense for a no-cache instruction.

The easiest way to achieve fine-grained control is in using wrapped actions. In your case it can be something like that:
object HeaderWriter {
def apply(f: Request[AnyContent] => SimpleResult):Action[AnyContent] = {
Action { request =>
f(request).withHeaders(PRAGMA -> "no-cache")
}
}
}
and use it in such manner:
def doAction = HeaderWriter { request =>
... do any stuff your want ...
Ok("Thats it!")
}

There are too ways. You can use action-composition. Then you must declare at every Controller that you want set here the header. Another option is to use the GlobalSettings.
There are similar solutions for java, too.

Related

Scala Play 2.5 Action composition with Deadbolt-2 actions

I'm working on a Scala Play application and need many Controller actions disabling caching of the browser by setting parameters in the HTTP headers of the Response. I decided to create a NoCache composite action and since I am also using Deadbolt-2 (and need a Deadbolt-2's AuthenticatedRequest[_]) it looks like this:
package action
import be.objectify.deadbolt.scala.AuthenticatedRequest
import play.api.http.HeaderNames
import play.api.mvc._
import scala.concurrent.Future
import scala.util.Success
case class NoCache[A](action: Action[A]) extends Action[A] with HeaderNames {
def apply(request: AuthenticatedRequest[A]): Future[Result] = {
action(request).andThen {
case Success(result) => result.withHeaders(
(CACHE_CONTROL -> "no-cache, no-store, must-revalidate"),
(PRAGMA -> "no-cache"),
(EXPIRES -> "0")
)
}
}
lazy val parser = action.parser
}
but then it won't compile trying to mix in this Action into my Controller action implementations e.g.
def link = deadbolt.SubjectPresent()() andThen NoCache() { implicit request =>
or
def link = NoCache(deadbolt.SubjectPresent()()) { implicit request =>
but can't see how to compose them ...
I found how to do it for a single action:
def index = NoCache {
deadbolt.WithAuthRequest()() { implicit request =>
Future {
Ok(views.html.index(userService))
}
}
}
However, I still haven't found how to apply NoCache to the entire controller class.

deadbolt2 and implicit request

I'm trying to integrate Deadbolt2 into my play framework 2.4 application.
A have following piece of code in my controller
import be.objectify.deadbolt.scala.{ActionBuilders, AuthenticatedRequest, DeadboltActions}
import be.objectify.deadbolt.scala.cache.HandlerCache
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc.{AnyContent, _}
import modules.user.security.{Authenticator, HandlerKeys, MyDeadboltHandler}
class Login #Inject() (deadbolt: DeadboltActions, handlers: HandlerCache, actionBuilder: ActionBuilders) extends Controller {
//...
def login = deadbolt.SubjectNotPresent() {
Action { implicit request =>
Ok(login(loginForm))
}
}
}
And I got error missing parameter type. I'm following deadbolt examples, which helps me a lot, but I can't figure out how to pass implicit request into action.
My template begins like this:
#(loginForm: Form[LoginForm])(implicit flash: Flash)
Using Action directly without deadbolt.SubjectNotPresent() works well.
One persistent question that keeps coming up is "how do I get the subject in an authorized action?". As of Deadbolt 2.5, the request passed into an action has been replaced with an AuthenticatedRequest which contains an Option[Subject]. As users of 2.4 also want this feature, it has been included in 2.4.4 as a breaking change.
The following examples use SubjectPresent as an example, but the same change applies to all authorization constraints.
When using action builders, in place of
def index = actionBuilder.SubjectPresentAction().defaultHandler() { implicit request
Ok(accessOk())
}
we now have
def index = actionBuilder.SubjectPresentAction().defaultHandler() { authRequest =>
Future {
Ok(accessOk())
}
}
When using action composition, in place of
def index = deadbolt.SubjectPresent() { implicit request
Action {
Ok(accessOk())
}
}
we now have
def someFunctionA = deadbolt.SubjectPresent()() { authRequest =>
Future {
Ok("Content accessible")
}
}
The getSubject() function of the DeadboltHandler trait now takes an AuthenticatedRequest instead of a Request.
override def getSubject[A](request: AuthenticatedRequest[A]): Future[Option[Subject]] =
request.subject match {
case Some(user) => Future {request.subject}
case None => // get from database, identity platform, cache, whatever
}
What this means for your app is
def login = deadbolt.SubjectNotPresent() {
Action { implicit request =>
Ok(login(loginForm))
}
}
becomes
def login = deadbolt.SubjectNotPresent()() { authRequest =>
Future {
Ok(login(loginForm))
}
}

Caching an action in a multi-language website using Play Framework's Cached API

In order to cache actions per label and language for a given number of seconds, I wrote the following helper method (where label, is the name I give to my action):
def cacheResponseFor(label: String, duration: Int)(action: EssentialAction) = {
Cached({r: RequestHeader => (label + getLanguage(r))}, duration){ action }
}
def getLanguage(request: RequestHeader): String = {
request.cookies
.get(helpers.SessionHelpers.LANGUAGE_SESSION)
.map(_.value)
.getOrElse(helpers.LanguageHelpers.FRENCH)
}
But I'm experiencing something weird, when I try to cache an Action for 60s and switch languages in the meantime to English from French for example, I keep getting the French version for 60s then it switches to english.
After investigating, I found that method getLanguage is not called at each call to that action as if the Key gets evaluated only after the caching period ends.
This is not right, I would want this cacheResponseFor to be called everytime I request my page, the language gets evaluated using getLanguage and I get the right cached version, i.e. I should end up with 2 cached actions (one per language).
Am I missing something?
Maybe the problem is in the getLanguage method. Try this, as recommended by the docs:
def getLanguage(request: RequestHeader): String = {
request.acceptLanguages
.map(_.code)
.headOption
.getOrElse(helpers.LanguageHelpers.FRENCH)
}
Also, take a look at Controller.request2lang() method and see if it could be helpful to you.
I do not know what is the issue you are facing but I did a small proof of concept and there is no issue at all.
package controllers
import play.api.cache.Cached
import play.api.mvc.{Action, Controller, EssentialAction, RequestHeader}
object Caches {
import play.api.Play.current
def cacheResponseFor(label: String, duration: Int)(action: EssentialAction) = {
Cached({r: RequestHeader => label + getLanguage(r)}, duration){ action }
}
def getLanguage(request: RequestHeader): String = {
request.cookies
.get("language")
.map(_.value)
.getOrElse("fr")
}
}
class CachedApplication () extends Controller {
import Caches._
def index = cacheResponseFor("homePage", 60) {
Action { implicit req =>
getLanguage(req) match {
case "fr" =>
Ok("Bonjour le monde")
case _ =>
Ok("Hello world")
}
}
}
}

How can I chain my custom actions when using ActionBuilder

Trying to better understand creating custom actions using action builder.
I have a custom action like:
class LogginInRequest[A](val currentUser: User, request: Request[A]) extends WrappedRequest[A](request)
object ActionWithContext extends ActionBuilder[LogginInRequest] {
def invokeBlock[A](request: Request[A], block: (LogginInRequest[A]) => Future[SimpleResult]) = {
val u = /// load User
block(new LogginInRequest(user, request)
}
}
Could I someone create another custom action like the above that inherits from the above one and builds upon it i.e. chain in the action and access the user object
e.g. Say I now create a new section on my website for admins, so I check the user object in this new action for:
user.isAdmin
If isAdmin is false, then I redirect using the Future.successful(Forbidden) call.
So I would create LoggedInAdmin based on LogginInRequest but simply checking for the property isAdmin (this is just an example but I want to know if I can do this).
Is it possible to pass an argument to my custom action that I created using action builder so I can do this?
def someAction(...):= MyCustomActionBuilder(userService) {
// ...
}
i.e. I am passing in a argument to it.
With Play 2.3, action composition using ActionBuilder got a whole lot better. The example below shows how you can define a standard ActionBuilder that creates a wrapped request, and then chain that builder together with an ActionTransformer to create a new wrapped request.
import scala.concurrent.Future
import org.scalatest.{MustMatchers, WordSpec}
import play.api.mvc._
import play.api.test.FakeRequest
import play.api.test.Helpers._
class ChainingTest extends WordSpec with MustMatchers {
class WrappedReq1[A](val str: String, request: Request[A]) extends WrappedRequest[A](request)
object ActionWithReq1 extends ActionBuilder[WrappedReq1] {
def invokeBlock[A](request: Request[A], block: (WrappedReq1[A]) => Future[Result]) = {
block(new WrappedReq1(request.headers("1"), request))
}
}
class WrappedReq2[A](val str1: String, val str2: String, request: Request[A]) extends WrappedRequest[A](request)
val ActionWithReq2 = ActionWithReq1 andThen new ActionTransformer[WrappedReq1, WrappedReq2] {
override protected def transform[A](request: WrappedReq1[A]): Future[WrappedReq2[A]] = {
Future.successful(new WrappedReq2[A](request.str, request.headers("2"), request))
}
}
"chained actions" should {
"work" in {
val request = FakeRequest().withHeaders("1" -> "one", "2" -> "two")
val response = ActionWithReq2 { r => Results.Ok(r.str1 + "-" + r.str2) }(request)
contentAsString(response) must equal("one-two")
}
}
}
There is an ActionTransformer trait for modifying your request wrapper, and an ActionFilter for intercepting certain requests and immediately returning a result.
ScalaActionsComposition describes the traits in more detail.

Authorisation check in controller - Scala/Play

This is a simple example of a controller in Play Framework where every action checks the session - if the user is logged in.
object Application extends Controller {
def index = Action { implicit request =>
if (request.session.isEmpty) {
Redirect("/login")
} else {
Ok(views.html.index("index"))
}
}
def about = Action { implicit request =>
if (request.session.isEmpty) {
Redirect("/login")
} else {
Ok(views.html.index("about"))
}
}
}
I'd like to handle the session checking in the constructor instead of every action method, but I just don't know how? It should look something like this:
object Application extends Controller {
//This is where the constructor would check if session exists
//and if not - redirect to login screen
def index = Action {
Ok(views.html.index("index"))
}
def about = Action {
Ok(views.html.index("about"))
}
}
Is this possible and if so then how?
My stack is Play Framework 2.2.1, Scala 2.10.3, Java 1.8.0-ea 64bit
UPDATE - SOLVED Thanks for all your ideas, solution is now found, see my answer.
You could take advantage of Action Composition to achieve this. From the documentation:
import play.api.mvc._
class AuthenticatedRequest[A](val username: String, request: Request[A]) extend WrappedRequest[A](request)
object Authenticated extends ActionBuilder[AuthenticatedRequest] {
def invokeBlock[A](request: Request[A], block: (AuthenticatedRequest[A]) =>Future[SimpleResult]) = {
request.session.get("username").map { username =>
block(new AuthenticatedRequest(username, request))
} getOrElse {
Future.successful(Forbidden)
}
}
}
And then you could simply do:
def index = Authenticated {
Ok(views.html.index("index"))
}
Alternatively you could set up a filter instead (as #Robin Green suggested) like so:
object AuthFilter extends Filter {
override def apply(next: RequestHeader => Result)(rh: RequestHeader): Result = {
rh.session.get("username").map { user =>
next(rh)
}.getOrElse {
Redirect("/login")
}
}
In Global.scala scala, add
override def doFilter(action: EssentialAction) = AuthFilter(action)
For more on Filters, see the official docs
Solution is to use Action Composition and create a custom action.
Auth.scala:
package core
import play.api.mvc._
import scala.concurrent._
import play.api.mvc.Results._
object AuthAction extends ActionBuilder[Request] {
def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[SimpleResult]) = {
if (request.session.isEmpty) {
//authentication condition not met - redirect to login page
Future.successful(Redirect("/login"))
} else {
//proceed with action as normal
block(request)
}
}
}
Application.scala:
package controllers
import play.api._
import play.api.mvc._
import core._
object Application extends Controller {
def index = AuthAction {
Ok(views.html.index("You are logged in."))
}
}
Take a look at Deadbolt: https://github.com/schaloner/deadbolt-2 . There are exhaustive examples and guides.
Works perfectly in my Play 2 project.
You could use a Filter, which applies to every request in the application. However, then you would need to have some code in that Filter to allow certain URLs to be accessed without a valid session, otherwise then the user would not be able to login in the first place.