Search code examples
sessionclojuremiddlewarering

passing session state in clojure Ring


I'm using a passwordless login system for my website, a user gets an e-mail and clicks the link to authenticate. So far, so good.

How can I create or modify a ring middleware to retain and pass along the updated :session values?

(GET "/login" []
  ; gets a user's email and sends them a link to authenticate.
)

(GET "/login/:key&:email&:timestamp" [key email timestamp :as request]
  ; uses the timestamp, key, and email to verify the key
  ; if it all checks out, then set some session values
  ; e.g.
  (def updatedRequestMap 
   (assoc-in request [:session :supa-secret-smoken-token] "supercool secretval")))

How would I make sure that updatedRequestMap is passed along to future requests?

Thanks (=


Solution

  • Your login handler creates a ring response and assoc the newly updated session in that ring response.

        
    ;; put this in your ns declaration
    ;; (:require [ring.util.response :refer [response]])
    
        (GET "/login/:key&:email&:timestamp" [key email timestamp :as request]
             (let [old-session (:session request)
                   new-session (assoc old-session
                                      :supa-secret-smoken-token 
                                      "supercool secretval")]
               (-> (response "You are now logged in")
                   (assoc :session new-session))))