How to refactor the "IsAuthenticated" method to provide a better api

I have a method IsAuthenticated

that has a complex argument type (I copied it from the play2 zentasks example):

def IsAuthenticated(f: => String => Request[AnyContent] => Result): Action[(Action[AnyContent], AnyContent)] =
  Security.Authenticated(username, onUnauthorized) { userId =>
    Action { implicit request =>
      val email = request.session("user.email")
      f(email)(request)
    }
  }

      

To use it, my action:

def delete(id:String) = IsAuthenticated { email => request =>
   ...
}

      

You can see that I have to declare an event email

if I don't need to use it. I can use instead _

:

def delete(id:String) = IsAuthenticated { _ => _ =>
   ...
}

      

But _ => _ =>

it's still boring.

How can I refactor a method to make it easier to use? e.g. If I don't need email

and request

, I can:

def delete(id:String) = IsAuthenticated {
   ...
}

      

If I just need to request

, I can:

def delete(id:String) = IsAuthenticated { request =>
   ...
}

      

If I need to email

, I declare them all:

def delete(id:String) = IsAuthenticated { email => request =>
   ...
}

      

+3


source to share


1 answer


You can overload IsAuthenticated

to provide the different flavors that you need. For example:

def IsAuthenticated(result: => Result) = IsAuthenticated { _ => _ => result }

      



Then you can use it like this:

def delete(id:String) = IsAuthenticated {
   ...
}

      

+4


source







All Articles