Cristian Boariu
Cristian Boariu

Reputation: 9621

Why I receive error for a specific method in Play 2?

I have this method:

def withAuth(f: => User => Request[AnyContent] => Result) = {
    Authentication.isAuthenticated(AuthenticationToken(AuthenticationService.TokenKey)) match {
      case None => Results.Redirect(routes.AuthenticationService.notLoggedIn)
      case Some(user) => Action(request => f(user)(request))
    }
  }

and I use it like:

  def list(locationId: Option[Int]) = withAuth { user =>
    implicit request =>
      val entities = Assets.filter(user, locationId)
      Logger.info("Succesfully returned %d assets to user %s".format(entities.length, user))
      Ok(Json.toJson(entities.map(s => Json.toJson(s))))
  }

As you notice I want to use it like a method which, if the user is not logged in, Redirects him to login page otherwise returns the user from session. The issue is with that Redirect, on runtime Play is complaining with:

Cannot use a method returning Object as an Handler

Does anybody has any clue?

Upvotes: 0

Views: 740

Answers (2)

Cristian Boariu
Cristian Boariu

Reputation: 9621

To avoid the above issues, in the end I did it like:

   def onUnauthorized(request: RequestHeader) = Results.Redirect(routes.AuthenticationService.notLoggedIn)

  /**
   * A very important wrapper method which checks if the user is logged-in: if it is, return the User, otherwise
   * redirect the user to a specific page.
   */
  def withAuthentication(f: => Option[User] => Request[AnyContent] => Result) = {
    Security.Authenticated(userId, onUnauthorized) { user =>
      Action(request => f(Users.findById(Integer.valueOf(user)))(request))
    }
  }

Upvotes: 1

Ivan Meredith
Ivan Meredith

Reputation: 2222

I think the return type of withAuth is not what you think it is. I think you need to wrap your Redirect in an Action.

Upvotes: 0

Related Questions