3
votes

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)
    }

}
3

3 Answers

3
votes

You need to include import play.api.mvc.Results._

From the official docs,

The A type is the type of the request body. We can use any Scala type as the request body, for example String, NodeSeq, Array[Byte], JsonValue, or java.io.File, as long as we have a body parser able to process it.

To summarize, an Action[A] uses a BodyParser[A] to retrieve a value of type A from the HTTP request, and to build a Request[A] object that is passed to the action code.

2
votes

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)
        }
    }

}
0
votes

its not redirecting if the the condition is not met

object Authentication extends ActionBuilder[Request] {

def invokeBlock[A](request: Request[A], block: (Request[A]) => Future[SimpleResult]) = {
    if (request.cookies.get("user").isEmpty) {
        Future.successful(Redirect("/expired"))
    } else {
        block(request)
    }
}

}