2

I have an endpoint called /account which provides user info(returns html).

When unauthorised user tries to access this endpoint I need to be able to redirect to login page but in Liberator I found post-redirect so far and it is just for post methods.

I need to redirect get methods as well, how can I achieve this?

Ertuğrul Çetin
  • 5,131
  • 5
  • 37
  • 76

1 Answers1

3

I found a workaround following code does the trick:

(defn account
  []
  (resource :allowed-methods [:get]

            :available-media-types ["text/html"]

            :exists? (fn [_] false)

            :existed? (fn [_] true)

            :moved-temporarily? (fn [ctx] {:location "/redirected-path-or-url"})

            :handle-ok (fn [ctx]
                         [:html ...])

            :handle-exception (fn [_]
                                "Something went wrong")))

Or you can check :authorized? and return login html from :handle-unauthorized but I doubt it about it's a good practice or not.

Ertuğrul Çetin
  • 5,131
  • 5
  • 37
  • 76
  • 3
    Philipp commented on an old blog post of mine where I also struggled with the exact same problem. He wrote: "to force a redirection on a get request you need to return false from :exists? When you think about it, it actually makes sense. Then you can implement :moved-permanently? or :moved-temporarily? and associate the new location in the context at :location". So, your workaround is actually the official way to do this. – schaueho Apr 08 '17 at 09:51
  • 1
    No need to wrap `false` and `true` in a function. You can use the literal values true: `:exists? false` will work. – ordnungswidrig Apr 10 '17 at 07:41