Search code examples
clojurenullpointerexceptionring

Making sure a var is bound in Clojure


In my middleware I'm checking the values of :session to see if the user is logged in.

It works great if the values of :session are set. Although, I am not sure what the best way to check if :session is bound.

(defn logged-in-verify
  [ring-handler]
  (fn new-ring-handler
    [request]
    ;;verify that the scrypt hash of email and timestamp matches.
    (let [session   (:session request)
          email     (:ph-auth-email session)
          token     (:ph-auth-token session)
          timestamp (:ph-auth-timestamp session)]
      (if (scryptgen/check (str email timestamp) token)
        (do 
          ;; return response from wrapped handler
          (ring-handler request))
        ;; return error response
        {:status 400, :body "Please sign in."}))))

Since I don't check if :session is bound, things using this middleware return a NullPointerException if it's unset. What's the best way to do that?


Solution

  • Use when-let or the similar if-let to check whether you actually have a session or not:

    (defn logged-in-verify
      [ring-handler]
      (fn new-ring-handler
        [request]
        ;;verify that the scrypt hash of email and timestamp matches.
        (if-let [session   (:session request)]
            (let [email     (:ph-auth-email session)
                  token     (:ph-auth-token session)
                  timestamp (:ph-auth-timestamp session)]
              (if (scryptgen/check (str email timestamp) token)
                 ;; return response from wrapped handler
                 (ring-handler request))
                 ;; return error response
                 {:status 400, :body "Please sign in."}))
            ;; do something when there is no session yet
            (generate-new-session-and-redirect))))