Giter Club home page Giter Club logo

Comments (8)

gcv avatar gcv commented on June 26, 2024

Could you be more specific about what doesn't work? I use cookie sessions, and they work fine.

(def my-app-handler
  (-> #'my-app-routes
      wrap-keyword-params
      wrap-params
      (wrap-session {:cookie-name "my-session"
                     ;; The cookie store key must contain exactly 16 bytes.
                     :store (cookie-store {:key "..."})})))

from appengine-magic.

Folcon avatar Folcon commented on June 26, 2024

Hi gcv,

I'm sorry I haven't responded earlier, I didn't know you had messaged me back.

I've been trying several things. The one I've had the most success with, at least on the development server has been the code I'm posting below:

(ns cashew.dev-session
  (:use ring.middleware.cookies)
  (:import java.util.UUID))

(declare current-session)
(def session-lifetime (* 60 60 1000))
(def *sessions* (atom {}))

(defn session-expired? [s]
  (< (+ (s :timestamp) session-lifetime) (System/currentTimeMillis)))

(defn- read-session [key]
  (assoc (@*sessions* key {}) :timestamp (System/currentTimeMillis)))

(defn- write-session [key data]
  (let [key (or key (str (UUID/randomUUID)))]
    key))

(defn- delete-session [key]
  (swap! *sessions* dissoc key)
  nil)

(defn wrap-session
  [handler]
  (let [cookie-name  "ring-session"
    session-root "/"
    cookie-attrs {:path session-root}]
    (wrap-cookies
     (fn [request]
       (let [sess-key (get-in request [:cookies cookie-name :value])]
     (binding [current-session (atom (read-session sess-key))]
       (let [response (handler request)]
         (when response
           (let [sess @current-session
             sess-key* (if sess
                 (write-session sess-key sess)
                 (if sess-key
                   (delete-session sess-key)))
             cookie   {cookie-name (merge cookie-attrs
                          (response :session-cookie-attrs)
                          {:value sess-key*})}]
         (if (and sess-key* (not= sess-key sess-key*))
           (assoc response :cookies (merge (response :cookies) cookie))
           response)
         ))
         ))))))
  )

(defn session-get
  ([k] (session-get k nil))
  ([k default] (if (vector? k)
                 (get-in @current-session k)
                 (get @current-session k default))))

(defn session-put!
  ([m]
     (swap! current-session (fn [a b] (merge a m)) m))
  ([k v]
     (swap! current-session (fn [a b] (merge a {k b})) v)))

(defn session-pop! [k]
  (let [res (get @current-session k)]
    (swap! current-session (fn [a b] (dissoc a b)) k)
    res))

(defn session-delete-key! [k]
  (swap! current-session (fn [a b] (dissoc a b)) k))

(defn session-destroy! []
  (swap! current-session (constantly nil)))

The problem is when I upload the code to the appengine, it quickly drops the session. I've been looking at gaeshi to handle sessions at the moment, but it's documentation is quite sparse so was hoping I could work out how to manage sessions purely using appengine-magic...

Regards,
Folcon

from appengine-magic.

gcv avatar gcv commented on June 26, 2024

Hold on — is your code trying to maintain the session state on the server? Meaning, is the *sessions* atom supposed to hold the session data in between requests? That would only work within the context of one JVM, and App Engine starts and stops JVMs all the time. You should store all your session data in a cookie.

from appengine-magic.

Folcon avatar Folcon commented on June 26, 2024

I tried doing that, but it doesn't seem to store the values properly. Basically my cookies map kept coming up empty and so did my session, so I'm pretty sure I was doing it wrong. I wanted to get it working with a get/set! type functionality if possible. Mostly because I figure that changing values in sessions/cookies is essentially a side effect anyway so I shouldn't pretend otherwise.

from appengine-magic.

gcv avatar gcv commented on June 26, 2024

Here is a working example:

(ns cv-test-2.core
  (:use compojure.core
        [ring.middleware.keyword-params :only [wrap-keyword-params]]
        [ring.middleware.session :only [wrap-session]]
        [ring.middleware.session.cookie :only [cookie-store]])
  (:require [appengine-magic.core :as ae]))

(defroutes cv-test-2-app-routes
  (GET "/" _
       (fn [{session :session :as req}]
         (let [session (if (or (nil? session) (empty? session))
                           {:counter 0}
                           session)]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :session session
            :body (str "started: " session)})))
  (GET "/inc" _
       (fn [{session :session :as req}]
         (let [new-session (assoc session :counter (inc (get session :counter 0)))]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :session new-session
            :body (str "incremented: " new-session)}))))

(def cv-test-2-app-handler
  (-> #'cv-test-2-app-routes
      wrap-keyword-params
      (wrap-session {:cookie-name "cv-test-2-app-session"
                     ;; The cookie store key must contain exactly 16 bytes.
                     :store (cookie-store {:key "0123456789abcdef"})})))

(ae/def-appengine-app cv-test-2-app #'cv-test-2-app-handler)

If you want to use side effects to manage your sessions, you can use your idea of using middleware, the binding form, and an atom, but only use the atom's value within the context of a single request. So a request comes in, you set the atom to the value of the current session, allow the user to modify it using a set! function, and finally assert the value of the atom onto the :session of the response.

from appengine-magic.

Folcon avatar Folcon commented on June 26, 2024

Thanks for the quick response, I seem to be getting a lot of class cast errors or the current-session ends up being unbound,

 error: java.lang.ClassCastException: ring.middleware.cookies$wrap_cookies$fn__2866 cannot be cast to clojure.lang.Associative (core.clj:75)

using:

(ns cv-test-2.core
  (:use compojure.core
        [ring.middleware.keyword-params :only [wrap-keyword-params]]
        [ring.middleware.session :only [wrap-session]]
        [ring.middleware.session.cookie :only [cookie-store]]
        [ring.handler.dump])
  (:require [appengine-magic.core :as ae]))

(declare current-session)

(defn wrap-session!
  [handler]
  (binding [current-session (atom (if (empty? (:session handler)) {} (:session handler)))]
    (assoc handler :session @current-session)))

(defn test-page [req]
  {:status 200
   :headers {"Content-Type" "text/plain"}
   :body @current-session})

(defroutes cv-test-2-app-routes
  (GET "/" _
       (fn [{session :session :as req}]
         (let [session (if (or (nil? session) (empty? session))
                           {:counter 0}
                           session)]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :session session
            :body (str "started: " session)})))
  (GET "/inc" _
       (fn [{session :session :as req}]
         (let [new-session (assoc session :counter (inc (get session :counter 0)))]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :session new-session
            :body (str "incremented: " new-session)})))
  (ANY "/dump" request (ring.handler.dump/handle-dump request)
  (ANY "/test" request (test-page request))

(def cv-test-2-app-handler
  (-> #'cv-test-2-app-routes
      wrap-keyword-params
      (wrap-session {:cookie-name "cv-test-2-app-session"
                     ;; The cookie store key must contain exactly 16 bytes.
                     :store (cookie-store {:key "0123456789abcdef"})})
      wrap-session!))

(ae/def-appengine-app cv-test-2-app #'cv-test-2-app-handler)

If I can't end up working this I'll just have to live with functional sessions, though using side-effects would be preferred.

from appengine-magic.

Folcon avatar Folcon commented on June 26, 2024

Ok working through it I've gotten something that works sort of:

(defn wrap-session!
  [handler]
  (fn [request]
    (let [response (handler request)]
      (binding [current-session (:session response);(atom (if (empty? (:session request))
                                        ;{} (:session request)))
                ]
        (assoc response :session current-session)))))

provided that wrap-session! is before wrap-session {:cookie-name ...} it works.

It does work, however if I go to the ring-handler-dump page then it deletes the session... which doesn't happen on the standard functional sessions...

from appengine-magic.

gcv avatar gcv commented on June 26, 2024

Looks like you have the binding in the wrong place. It belongs before the call to the handler. Here's a working example which does what you want.

(ns cv-test-2.core
  (:use compojure.core
        [ring.middleware.keyword-params :only [wrap-keyword-params]]
        [ring.middleware.session :only [wrap-session]]
        [ring.middleware.session.cookie :only [cookie-store]])
  (:require [appengine-magic.core :as ae]))

(declare current-session)

(defn wrap-session! [handler]
  (fn [request]
    (binding [current-session (atom (or (:session request) {}))]
      (let [response (handler request)]
        (assoc response :session @current-session)))))

(defn session-set! [k v]
  (swap! current-session assoc k v))

(defn session-get
  ([k] (get @current-session k))
  ([k default] (get @current-session k default)))

(defroutes cv-test-2-app-routes
  (GET "/" _
       (fn [req]
         (let [counter (session-get :counter 0)]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :body (str "started: " counter)})))
  (GET "/inc" _
       (fn [req]
         (let [counter (do (session-set! :counter (inc (session-get :counter 0)))
                           (session-get :counter))]
           {:status 200
            :headers {"Content-Type" "text/plain"}
            :body (str "incremented: " counter)}))))

(def cv-test-2-app-handler
  (-> #'cv-test-2-app-routes
      wrap-keyword-params
      wrap-session!
      (wrap-session {:cookie-name "cv-test-2-app-session"
                     ;; The cookie store key must contain exactly 16 bytes.
                     :store (cookie-store {:key "0123456789abcdef"})})))

(ae/def-appengine-app cv-test-2-app #'cv-test-2-app-handler)

from appengine-magic.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.