[2.0-scala] Redirecting inside Action Composition

87 views
Skip to first unread message

Alex Xandra Albert Sim

unread,
Jul 7, 2012, 10:23:57 PM7/7/12
to play-fr...@googlegroups.com
Hi,
I'm thinking about making an action composition that will redirect user to a page when they're authorized. How do I do that? Here's my current code:

    def onlyUnauthorized(f: Request[AnyContent] => Result): Action[AnyContent] = {
        Action{ implicit request =>
            if(SecurityHelper.isAuthenticated(request)) {
                Results.Redirect(routes.Application.index)
            } 
            
            f(request)
        }
    }

But it didn't work (I think because the reutrn value is Action[AnyContent] while redirect don't do that. How do I implement thsi if I want to? Thanks before.

Alex Xandra Albert Sim

unread,
Jul 11, 2012, 8:39:36 AM7/11/12
to play-fr...@googlegroups.com
Wow, the pattern matching solution is truly elegant. Thank you very much.

On Monday, 9 July 2012 07:21:37 UTC+7, Jason Ross wrote:
Looks like the problem you're running into is that your code is always returning f(request) because there is no scenario where the Results.Redirect could be returned.  One way to fix would be to add an else block like this:


def onlyUnauthorized(f: Request[AnyContent] => Result): Action[AnyContent] = Action {
    implicit request =>
      if (SecurityHelper.isAuthenticated(request)) {
        Results.Redirect(routes.Application.index)
      } else {
        f(request)
      }
  }

But I think a more elegant way would be to use pattern matching:


def onlyUnauthorized(f: Request[AnyContent] => Result): Action[AnyContent] = Action {
    implicit request => SecurityHelper.isAuthenticated(request) match {
      case true => Results.Redirect(routes.Application.index)
      case _ => f(request)
Reply all
Reply to author
Forward
0 new messages