Search code examples
sessionclojurering

clearing a session (logging a user out) in clojure-ring


With the impression that simply setting the request-map's :session to nil will cause a logout, my code looks like the following:

(GET "/logout" [ :as request] 
  (if-let [useremail (get-in request [:session :ph-auth-email])]
    (-> (response {:status 200,
                   :body (pr-str "logged out " useremail),
                   :headers {"Content-Type:" "text/html"}})
        (assoc request [:session nil]))))

But I get an error:

java.lang.Thread.run(Thread.java:745)

2015-02-18 09:29:05.134:WARN:oejs.AbstractHttpConnection:/logout

java.lang.Exception: Unrecognized body: {:status 200, :body "\"logged out \" \"sova\"", :headers {"Content-Type:" "text/html"}}

Solution

  • ring.util.response/response expects only the body as parameter since it'll build :status and :headers around it (see here). A map, however, is not a valid body - only strings, files, streams are allowed.

    So, this is what causes the exception; now, on to your question: You can log out a user by setting :session to nil in your response (source) - which reduces your code to:

    (GET "/logout" [:as request] 
      (if-let [useremail (get-in request [:session :ph-auth-email])]
        {:status 200,
         :body (pr-str "logged out " useremail),
         :session nil, ;; !!!
         :headers {"Content-Type" "text/html"}}))