Reputation: 839
I'd like to add a specific cookie to all requests and results if the cookies does not exist. I understand I could use the withCookies
on the result, but I don't want to check every request in my controller methods and add it to every result. Is there a way to do this?
Upvotes: 1
Views: 826
Reputation: 839
In case someone else stumbles across this trying to use action composition it was easily achieved with a filter.
class MyCookieFilter @Inject() (implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
def apply(nextFilter: RequestHeader => Future[Result])(requestHeader: RequestHeader): Future[Result] = {
nextFilter(requestHeader).map { result =>
requestHeader.cookies.get("myAwesomeCookie") match {
case Some(cookie) => result.withCookies(cookie)
case None => result.withCookies(Cookie("myAwesomeCookie",SecureRandomUtil.generateSecureRandom(255),Some(60*60*24*365)))
}
}
}
}
In this example the filter is in the Controllers package.
In your application.conf file add this line in the play.filters section
enabled += controllers.MyCookieFilter
you would want to change controllers to whatever package you declared your filter in.
Upvotes: 1