towerops/lib/towerops_web/plugs/update_session_activity.ex

47 lines
1.3 KiB
Elixir

defmodule ToweropsWeb.Plugs.UpdateSessionActivity do
@moduledoc """
Updates the last_activity_at timestamp for the current browser session on each request.
This plug should be added to the browser pipeline to keep track of when
each session was last used. The activity timestamp is used in the Sessions
tab of User Settings to show when each session was last active.
The update happens in a background task to avoid slowing down requests.
"""
import Plug.Conn
alias Towerops.Accounts
@doc """
Initializes the plug with options (currently unused).
"""
def init(opts), do: opts
@doc """
Updates the last_activity_at timestamp for the current browser session.
Looks up the session by the token stored in the session cookie, then
updates the timestamp in a background task.
"""
def call(conn, _opts) do
token = get_session(conn, :user_token)
if token do
_ = Task.start(fn -> update_session_activity(token) end)
end
conn
end
defp update_session_activity(token) do
case Accounts.get_browser_session_by_token_value(token) do
nil ->
# No browser session found (might be an old session from before this feature)
:ok
session ->
# Update activity timestamp
Accounts.touch_browser_session(session)
end
end
end