Skip to content

Commit

Permalink
Add :keep-empty option to Lack.Middleware.Session for preventing from…
Browse files Browse the repository at this point in the history
… sending Set-Cookie header until the session is used.
  • Loading branch information
fukamachi committed Sep 26, 2015
1 parent 8d6fe23 commit d4cdb53
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 9 deletions.
23 changes: 15 additions & 8 deletions src/middleware/session.lisp
Expand Up @@ -20,20 +20,27 @@
(defparameter *lack-middleware-session*
(lambda (app &key
(store (make-memory-store))
(state (make-cookie-state)))
(state (make-cookie-state))
(keep-empty t))
(lambda (env)
(let* ((sid (extract-sid state env))
(session (and sid
(fetch-session store sid)))
(sid (or sid
(generate-sid state env))))
(setf (getf env :lack.session)
(or session (make-hash-table :test 'equal)))
(generate-sid state env)))
(new-session-p (not session))
(session (or session (make-hash-table :test 'equal))))
(setf (getf env :lack.session) session)
(setf (getf env :lack.session.options)
(if session
(list :id sid)
(list :id sid :new-session t)))
(finalize store state env (funcall app env)))))
(if new-session-p
(list :id sid :new-session t)
(list :id sid)))
(let ((res (funcall app env)))
(if (and (not keep-empty)
new-session-p
(zerop (hash-table-count session)))
res
(finalize store state env res))))))
"Middleware for session management")

(defun finalize (store state env res)
Expand Down
18 changes: 17 additions & 1 deletion t/middleware/session.lisp
Expand Up @@ -6,7 +6,7 @@
:lack.test))
(in-package :t.lack.middleware.session)

(plan 4)
(plan 5)

(ok (lack.session.state:make-state)
"Base class of session state")
Expand Down Expand Up @@ -103,4 +103,20 @@
"Set-Cookie header exists")
(is body '("hi") "body"))))

(subtest ":keep-empty nil"
(let ((app (builder
(:session :keep-empty nil)
(lambda (env)
(when (string= (getf env :path-info) "/session")
(setf (gethash "user" (getf env :lack.session)) "Eitaro"))
'(200 () ("hi"))))))
(destructuring-bind (status headers body)
(funcall app (generate-env "/"))
(declare (ignore status body))
(is headers nil))
(destructuring-bind (status headers body)
(funcall app (generate-env "/session"))
(declare (ignore status body))
(is-type (getf headers :set-cookie) 'string))))

(finalize)

0 comments on commit d4cdb53

Please sign in to comment.