Question

In the rest part of my lift application I often have code like this:

object UserRest extends RestHelper {
    serve("user" :: Nil prefix {
        case Req("remove-item" :: itemId :: Nil, "json", PostRequest) => {
            User.currentUser.map{ u =>
              //doing some things and returning message
              "Ready, all right."
            }.getOrElse("You must be logged in to perform this operation.")
         }: JValue

        case Req("update-item" :: itemId :: Nil, "json", PostRequest) => {
            User.currentUser.map{ u =>
              //doing some things and returning message
              "Ready, all right."
            }.getOrElse("You must be logged in to perform this operation.")
         }: JValue
    }
}

As you can see for every user operation I have this piece of code:

User.currentUser.map{ u =>
    //...
}.getOrElse("You must be logged in to perform this operation.")

My question is - do I have a way to put this piece of code to one place to avoid repeating it for every request?

Was it helpful?

Solution

You could write a function to handle unboxing objects for you. Something like this should help:

def unbox[A](t:Box[A])(a: A => JValue) = { 
  val msg = "You must be logged in to perform this operation."
  t.map { u => a(u) }.getOrElse(JString(msg)) 
}

Then, you'd just call it like :

unbox(User.current){ u:User => 
   //doing something
   JString("Ready, all right.")
}

OTHER TIPS

If you are just doing this for the purposes of authentication, you should be able to use guarded LiftRules.dispatch calls. Described in Simply Lift and in more detail here.

You may also just be able to use LiftRules.httpAuthProtectedResource(UserRest), but I'm not really sure about that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top