Twice_Twice
Twice_Twice

Reputation: 557

Custom middleware that bypasses chain in Compojure

I'm trying to write a custom middleware that checks if user is authenticated by checking existence of :user key in request.

(defn wrap-authenticated [handler]
  (fn [{user :user :as req}]
    (if (nil? user)
      (do 
        (println "unauthorized")
        {:status 401 :body "Unauthorized." :headers {:content-type "text/text"}})
      (handler req))))

(def app
  (wrap-authenticated (wrap-defaults app-routes (assoc site-defaults :security false))))

But when I try to return response hashmap with 401 status, I get the following exception: WARN:oejs.AbstractHttpConnection:/main java.lang.ClassCastException: clojure.lang.Keyword cannot be cast to java.lang.String

Perhaps I don't understand the logic that needed to be implemented inside Compojure middleware. How do I write my middleware that breaks the middleware chain and just returns custom response or redirects to handler?

Upvotes: 2

Views: 215

Answers (1)

MicSokoli
MicSokoli

Reputation: 841

I believe in your case the mistake is in the :headers map, since the keys are expected to be strings and you're using :content-type, which is a keyword. Try this instead:

{"Content-Type" "text/html"}

Upvotes: 7

Related Questions