scalasessionplayframeworkactionbuilder

How to set a session in ActionBuilder in scala play 2.6?


The documentation on ActionBuilder contains a pipeline of three nodes: the authentication, adding informations, validating step.

I would like to set session values at the authentication step. I mean the .withSession which comes here Ok(_).withSession(_)

import play.api.mvc._

class UserRequest[A](val username: Option[String], request: Request[A]) extends WrappedRequest[A](request)

class UserAction @Inject()(val parser: BodyParsers.Default)(implicit val executionContext: ExecutionContext)
    extends ActionBuilder[UserRequest, AnyContent] with ActionTransformer[Request, UserRequest] {
    def transform[A](request: Request[A]) = Future.successful {
        new UserRequest(request.session.get("username"), request)
    }
}

Solution

  • You'll need to do action composition to add values to the request session like so:

    object WithSession extends ActionBuilder[Request] {
      def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[Result]) = {
          block(request).map(_.withSession("key" -> "value"))
      }
    }
    

    in your controller:

    def index = WithSession {
      Ok("result")
    }