Skip to content

Commit

Permalink
Implement plug bumping user session last used and timeout timestamps
Browse files Browse the repository at this point in the history
  • Loading branch information
zoldar committed Aug 23, 2024
1 parent b8d4f61 commit 9f6b657
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
25 changes: 25 additions & 0 deletions lib/plausible_web/plugs/user_session_touch.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
defmodule PlausibleWeb.Plugs.UserSessionTouch do
@moduledoc """
Plug for bumping timeout on user session on every dashboard request.
"""

import Plug.Conn

alias PlausibleWeb.UserAuth

def init(opts \\ []) do
opts
end

def call(conn, _opts) do
if user_session = conn.assigns[:current_user_session] do
assign(
conn,
:current_user_session,
UserAuth.touch_user_session(user_session)
)
else
conn
end
end
end
1 change: 1 addition & 0 deletions lib/plausible_web/router.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ defmodule PlausibleWeb.Router do
on_ee(do: nil, else: plug(PlausibleWeb.FirstLaunchPlug, redirect_to: "/register"))
plug PlausibleWeb.SessionTimeoutPlug, timeout_after_seconds: @two_weeks_in_seconds
plug PlausibleWeb.AuthPlug
plug PlausibleWeb.Plugs.UserSessionTouch
plug PlausibleWeb.LastSeenPlug
end

Expand Down
20 changes: 20 additions & 0 deletions lib/plausible_web/user_auth.ex
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,26 @@ defmodule PlausibleWeb.UserAuth do
end
end

@spec touch_user_session(Auth.UserSession.t()) :: Auth.UserSession.t()
def touch_user_session(%{token: nil} = user_session) do
# NOTE: Legacy token sessions can't be touched.
user_session
end

def touch_user_session(user_session) do
%{token: token, timeout_at: timeout_at, last_used_at: last_used_at} =
user_session
|> Auth.UserSession.touch_session()
|> Ecto.Changeset.apply_changes()

Repo.update_all(
from(us in Auth.UserSession, where: us.token == ^token),
set: [timeout_at: timeout_at, last_used_at: last_used_at]
)

Repo.reload!(user_session)
end

@doc """
Sets the `logged_in` cookie share with the static site for determining
whether client is authenticated.
Expand Down

0 comments on commit 9f6b657

Please sign in to comment.