-
-
Save lee-dohm/f49e3ae098094fd2ae185bc65d31ae63 to your computer and use it in GitHub Desktop.
Elixir / Phoenix Sliding Session Timeout Plug
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# How to use it: | |
# | |
# Plug it at the end of your :browser pipeline in your Phoenix app router.ex | |
# Make sure it is plugged before your session-based authentication and authorization Plugs. | |
# | |
# pipeline :browser do | |
# plug :accepts, ["html"] | |
# plug :fetch_session | |
# plug :fetch_flash | |
# plug :put_secure_browser_headers | |
# plug Auth.SlidingSessionTimeout, timeout_after_seconds: 3600 # <= | |
# end | |
# | |
defmodule Auth.SlidingSessionTimeout do | |
import Plug.Conn | |
def init(opts \\ []) do | |
Keyword.merge([timeout_after_seconds: 3600], opts) | |
end | |
def call(conn, opts) do | |
timeout_at = get_session(conn, :session_timeout_at) | |
if timeout_at && now() > timeout_at do | |
logout_user(conn) | |
else | |
put_session(conn, :session_timeout_at, new_session_timeout_at(opts[:timeout_after_seconds])) | |
end | |
end | |
defp logout_user(conn) do | |
conn | |
|> clear_session() | |
|> configure_session([:renew]) | |
|> assign(:session_timeout, true) | |
end | |
defp now do | |
DateTime.utc_now() |> DateTime.to_unix | |
end | |
defp new_session_timeout_at(timeout_after_seconds) do | |
now() + timeout_after_seconds | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment