I'm working on a vanilla Elixir / Phoenix application and followed the general steps in the Programming Phoenix book to implement a basic sign in & sign out system (see snippets below). However I see no advice in the book or online about how to set up cookie-based Plug sessions to expire after a certain amount of time. What are some approaches to session timeout in Phoenix apps?
Here's some relevant snippets of my bare-bones auth system:
In endpoint.ex
, the app is configured to use a read-only cookie-based session:
plug Plug.Session,
store: :cookie,
key: "_zb_key",
signing_salt: "RANDOM HEX"
I wrote a plug auth.ex
which (among other things) can log in an authenticated user, and can set current_user
based on the session user_id
found in subsequent requests:
def login!(conn, user) do
conn
|> assign(:current_user, user)
|> put_session(:user_id, user.id)
|> configure_session(renew: true)
end
# ... more ...
def load_current_user(conn, _opts) do
cond do
conn.assigns[:current_user] ->
conn # If :current_user was already set, honor it
user_id = get_session(conn, :user_id) ->
user = Zb.Repo.get!(Zb.User, user_id)
assign(conn, :current_user, user)
true ->
conn # No user_id was found; make no changes
end
end
# ... more ...