Drop session

This commit is contained in:
Uku Taht 2020-03-31 15:38:42 +03:00
parent e14001664c
commit 2cf57a795f
4 changed files with 39 additions and 10 deletions

View File

@ -9,19 +9,16 @@ defmodule PlausibleWeb.SessionTimeoutPlug do
timeout_at = get_session(conn, :session_timeout_at) timeout_at = get_session(conn, :session_timeout_at)
user_id = get_session(conn, :current_user_id) user_id = get_session(conn, :current_user_id)
if user_id && timeout_at && now() > timeout_at do cond do
logout_user(conn) user_id && timeout_at && now() > timeout_at ->
else configure_session(conn, drop: true)
put_session(conn, :session_timeout_at, new_session_timeout_at(opts[:timeout_after_seconds])) user_id ->
put_session(conn, :session_timeout_at, new_session_timeout_at(opts[:timeout_after_seconds]))
true ->
conn
end end
end end
defp logout_user(conn) do
conn
|> put_session(:current_user_id, nil) # Leave `device_id` in the session for accurate tracking
|> assign(:session_timeout, true)
end
defp now do defp now do
DateTime.utc_now() |> DateTime.to_unix DateTime.utc_now() |> DateTime.to_unix
end end

View File

@ -0,0 +1,32 @@
defmodule PlausibleWeb.SessionTimeoutPlugTest do
use ExUnit.Case, async: true
use Plug.Test
alias PlausibleWeb.SessionTimeoutPlug
@opts %{timeout_after_seconds: 10}
test "does nothing if user is not logged in" do
conn = conn(:get, "/")
|> init_test_session(%{})
|> SessionTimeoutPlug.call(@opts)
refute get_session(conn, :session_timeout_at)
end
test "sets session timeout if user is logged in" do
conn = conn(:get, "/")
|> init_test_session(%{current_user_id: 1})
|> SessionTimeoutPlug.call(@opts)
timeout = get_session(conn, :session_timeout_at)
now = DateTime.utc_now() |> DateTime.to_unix
assert timeout > now
end
test "logs user out if timeout passed" do
conn = conn(:get, "/")
|> init_test_session(%{current_user_id: 1, session_timeout_at: 1})
|> SessionTimeoutPlug.call(@opts)
assert conn.private[:plug_session_info] == :drop
end
end