Caballero Caballero - 3 months ago 13
Scala Question

Play/Scala: use Redirect in ActionBuilder

I'm trying to build a simple action to use in Play controller to check if the session is active:

import play.api.mvc._
import scala.concurrent._

object AuthAction extends ActionBuilder[Request] {

def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[SimpleResult]) = {
if (request.session.isEmpty) {
//Need to redirect to login page
Redirect("/login")
} else {
//Session is found, continue Action as normal
block(request)
}
}

}


Problem is, it doesn't recognize
Redirect
. How do I get it to work in this scope? I want to use this action in my controllers where authorisation is required:

object Application extends Controller {

def index = AuthAction {
Ok(views.html.index("You are logged in."))
}

}


These two would be different files.

Side question: what exactly is "A" in
invokeBlock[A]
and
Request[A]
?

I'm on Play 2.2.1, Scala 2.10.3, Java 1.8 64bit

UPDATE: Tried this, it doesn't give any errors any more, but it doesn't work - Redirect seems to be ignored.

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) {
Redirect("/login")
}
block(request)
}

}

Answer

Finally stumbled upon a solution. In this case custom action "AuthAction" will redirect to the login page if the condition (session present) is not met:

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) {
            Future.successful(Redirect("/login"))
        } else {
            block(request)
        }
    }

}
Comments