Change session middleware's default to off

When `:session` key is absent in the route data, the session middleware will not
be attached to the route. To enable the middleware, the user at least need to
use an empty map `{}` for the `:session`, which uses the default options.
This commit is contained in:
Daw-Ran Liou 2019-10-04 10:48:53 -07:00
parent 99efdeea2d
commit a3c64baeba
2 changed files with 23 additions and 9 deletions

View file

@ -31,9 +31,10 @@
| key | description | | key | description |
| -------------|-------------| | -------------|-------------|
| `:session` | A map of options that passes into the [`ring.middleware.session/wrap-session](http://ring-clojure.github.io/ring/ring.middleware.session.html#var-wrap-session) function`." | `:session` | A map of options that passes into the [`ring.middleware.session/wrap-session](http://ring-clojure.github.io/ring/ring.middleware.session.html#var-wrap-session) function`, or an empty map for the default options. The absence of this value will disable the middleware."
{:name :session {:name :session
:spec ::spec :spec ::spec
:compile (fn [{session-opts :session} _] :compile (fn [{session-opts :session} _]
(let [session-opts (merge {:store store} session-opts)] (if session-opts
{:wrap #(session/wrap-session % session-opts)}))}) (let [session-opts (merge {:store store} session-opts)]
{:wrap #(session/wrap-session % session-opts)})))})

View file

@ -11,11 +11,11 @@
[request] [request]
(let [pattern #"ring-session=([-\w]+);Path=/;HttpOnly" (let [pattern #"ring-session=([-\w]+);Path=/;HttpOnly"
parse-fn (partial re-find pattern)] parse-fn (partial re-find pattern)]
(-> request (some-> request
(get-in [:headers "Set-Cookie"]) (get-in [:headers "Set-Cookie"])
first first
parse-fn parse-fn
second))) second)))
(defn handler (defn handler
"The handler that increments the counter." "The handler that increments the counter."
@ -52,7 +52,8 @@
(let [app (ring/ring-handler (let [app (ring/ring-handler
(ring/router (ring/router
["/api" ["/api"
{:middleware [session/session-middleware]} {:middleware [session/session-middleware]
:session {}}
["/ping" handler] ["/ping" handler]
["/pong" handler]])) ["/pong" handler]]))
first-response (app {:request-method :get first-response (app {:request-method :get
@ -65,6 +66,18 @@
(is (= (inc (get-in first-response [:body :counter])) (is (= (inc (get-in first-response [:body :counter]))
(get-in second-response [:body :counter]))))))) (get-in second-response [:body :counter])))))))
(deftest default-session-off-test
(testing "Default session middleware"
(let [app (ring/ring-handler
(ring/router
["/api"
{:middleware [session/session-middleware]}
["/ping" handler]]))
resp (app {:request-method :get
:uri "/api/ping"})]
(testing "off by default"
(is (nil? (get-session-id resp)))))))
(deftest session-spec-test (deftest session-spec-test
(testing "Session spec" (testing "Session spec"
(testing "with invalid session store type" (testing "with invalid session store type"