Fork me on GitHub
#clojure
<
2024-01-07
>
Ryan Martin05:01:08

I'm trying to implement session auth but for some reason my session cookie is being set automatically when I refresh a page. is this supposed to happen? Also, is the cookie being set automatically by buddy.auth when the :session key is set to a value?

(ns rm.handler
  (:require [reitit.ring :as ring]
            [ring.middleware.defaults :as defaults]
            [ring.middleware.session.cookie :as cookie]
            [ring.util.response :as res]
            [buddy.auth.backends.session :as session]
            [buddy.auth.middleware :as auth-middleware]
            [rm.routes.core :as routes]))

(defn default-middleware [cookie-secret]
  (fn [handler]
    (let [cs    (cookie/cookie-store {:key (.getBytes ^String cookie-secret)})
          name  "rm-session"
          attrs {:max-age (* 60 60 24 7) ; 1 week
                 :http-only true
                 :same-site :lax}]
      (defaults/wrap-defaults handler
                              (-> defaults/site-defaults
                                  (assoc-in [:session :store] cs)
                                  (assoc-in [:session :cookie-name] name)
                                  (assoc-in [:session :cookie-attrs] attrs))))))

(defn handler [db cookie-secret]
  (ring/ring-handler
   (ring/router
    routes/routes
    {:data {:db db
            :middleware [#_auth-middleware]}})
   (ring/routes
    (ring/redirect-trailing-slash-handler)
    (ring/create-resource-handler {:path "/"})
    (ring/create-default-handler
     {:not-found
      (constantly (-> {:status 404 :body "page not found"}
                      (res/content-type "text/html")))
      :method-not-allowed
      (constantly (-> {:status 405 :body "not allowed"}
                      (res/content-type "text/html")))
      :not-acceptable
      (constantly (-> {:status 406 :body "not acceptable"}
                      (res/content-type "text/html")))}))
   {:middleware [(default-middleware cookie-secret)]}))