Skip to content

Commit

Permalink
Read Set-Cookie header options from Session plug's options (#187)
Browse files Browse the repository at this point in the history
  • Loading branch information
sylph01 authored Jan 21, 2022
1 parent 1b358ec commit d1148d2
Showing 1 changed file with 11 additions and 5 deletions.
16 changes: 11 additions & 5 deletions lib/web/plug/session.ex
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,14 @@ defmodule Antikythera.Plug.Session do

alias Antikythera.Conn
alias Antikythera.Session
alias Antikythera.Http

defun load(conn :: v[Conn.t()], opts :: Keyword.t(String.t() | atom)) :: Conn.t() do
@type load_option_t ::
{:key, String.t()} | {:store, atom} | {:set_cookie, Http.SetCookie.options_t()}

defun load(conn :: v[Conn.t()], opts :: v[list(load_option_t)]) :: Conn.t() do
key = opts[:key]
set_cookie_opts = Keyword.get(opts, :set_cookie, %{})
store_name = Keyword.get(opts, :store, :cookie) |> Atom.to_string() |> Macro.camelize()
store_module = Module.safe_concat("Antikythera.Session", store_name)
{session_id, data} = store_module.load(Conn.get_req_cookie(conn, key))
Expand All @@ -34,23 +39,24 @@ defmodule Antikythera.Plug.Session do
}

conn
|> Conn.register_before_send(make_before_send(store_module, key))
|> Conn.register_before_send(make_before_send(store_module, key, set_cookie_opts))
|> Conn.assign(:session, session)
end

defunp make_before_send(store :: module, key :: String.t()) :: (Conn.t() -> Conn.t()) do
defunp make_before_send(store :: module, key :: String.t(), set_cookie_opts :: map) ::
(Conn.t() -> Conn.t()) do
fn %Conn{assigns: %{session: session}} = conn ->
%Session{state: state, id: id, data: data} = session

case state do
:update ->
new_id = store.save(id, data)
Conn.put_resp_cookie(conn, key, new_id)
Conn.put_resp_cookie(conn, key, new_id, set_cookie_opts)

:renew ->
store.delete(id)
new_id = store.save(nil, data)
Conn.put_resp_cookie(conn, key, new_id)
Conn.put_resp_cookie(conn, key, new_id, set_cookie_opts)

:destroy ->
store.delete(id)
Expand Down

0 comments on commit d1148d2

Please sign in to comment.