reitit

Jon Hancock 2024-10-16T08:14:10.581269Z

Anyone have a complete example of using reitit for session cookie? nothing in the reitit docs. I have a working app with reitit and have had so much trouble with middleware and session cookie in particular that I'm considering ditching reitit for compojure.

valtteri 2024-10-16T08:31:51.082849Z

Hey, did you find this issue yet? The issue description contains 3 alternative solutions for using ring.middleware.session/wrap-session https://github.com/metosin/reitit/issues/205 Hope this helps.

jussi 2024-10-16T08:37:07.360989Z

We have a simple session management with ring-reitit. First you need to specify session fn's, like

(defn read-session* [session-key]
  (when session-key
    (db.session/fetch xtdb/node session-key)))

(defn write-session* [session-key data]
  (db.session/write! xtdb/node session-key data))

(defn delete-session* [session-key]
  (when session-key
    (db.session/delete! xtdb/node session-key)))

(deftype Store []
  ; Thin wrapper, so that we don't need to re-eval
  ; store and app when the session functions change
  SessionStore
  (read-session [_store session-key]
    (read-session* session-key))
  (write-session [_store session-key data]
    (write-session* session-key data))
  (delete-session [_store session-key]
    (delete-session* session-key)))

(def store (->Store))
Next, the middleware
"/frontend-api"
      {:middleware [(middleware.multipart/create-multipart-middleware
                     {:store (ring.middleware.multipart-params.byte-array/byte-array-store)})
                    create-version-header-middleware
                    [ring.middleware.session/wrap-session {:store store}]]}
And finally, in some route, authenticate for example, you need to add :session in to the response, eg.
{:status 200
 :headers default-headers
 :body data
 :session (assoc data :id user-id)}
The data assoc'd to session contains our login data and internal user id. Ring will detect the :session and do the needful. The session is then available in the route handlers like this
:handler (fn [{:keys [path-params session]}]

adham 2024-10-16T08:49:49.829379Z

No complete example but I just use the ring.middleware.cookies/wrap-cookies and it just works. I have it inside {:data {:middleware ...}} and requests and responses start having :cookies data.

adham 2024-10-16T08:50:26.799379Z

Unless I'm mixing up cookies and session cookies not knowing the difference 😅

jussi 2024-10-16T08:58:30.176359Z

oh, OP wanted cookies. Darn, I can't read. Oh well, there is one session management solution anyway 🙈

adham 2024-10-16T09:00:03.482199Z

I mean you aren't far off, my session management with the cookies involves a lonely atom mapping :id to :cognito-user-id.

👍🏻 1