analytics/test/workers/clean_user_sessions_test.exs
Adrian Gruntkowski 373d4dd665
Implement token-based sessions (#4463)
* Turn `Plausible.Auth.UserSession` into full schema

* Implement token based sessions and use them as default

* Ignore expired user sessions during retrieval from DB

* Implement plug bumping user session last used and timeout timestamps

* Implement Oban worker removing expired user sessions with grace period

* Implement legacy session conversion on touch, when applicable

* Update `UserAuth` moduledoc

* Extend `UserAuth` tests to account for db-backed session tokens

* Update CHANGELOG

* Add tests for `UserSessionTouch` plug

* Add test for `CleanUserSessions` worker

* Add logging of legacy session retrievals

* Use single update permitting stale records  when touching user session

* Don't fetch session and user for external API endpoints (/api/event too)

* Refactor `Users.with_subscription/1` and expose helper query

* Skip fetching session in legacy `SessionTimeoutPlug`

* Rely on user session assign from `AuthContext` in `SentryContext`

* Silence legacy session warnings in `UserSessionTouchTest`

* Rely on session assign from `AuthPlug` in `SuperAdminOnlyPlug`

* Change `UserAuth` to get session, user and last subscription in one go

* Avoid refetching user session in `AuthorizeSiteAccess` plug

* Fix code formatting

* Refactor `UserAuth.get_user_token/1` (h/t @aerosol)

* Remove bogus empty opts from `scope` declarations in router

* Only touch session once an hour and keep `user.last_seen` in sync

* Bring back logging of legacy token use
2024-09-03 11:34:37 +02:00

35 lines
1.1 KiB
Elixir

defmodule Plausible.Workers.CleanUserSessionsTest do
use Plausible.DataCase
alias Plausible.Auth.UserSession
alias Plausible.Workers.CleanUserSessions
test "cleans invitation that is more than timeout_at + grace_period days old" do
grace_cutoff =
NaiveDateTime.utc_now(:second)
|> NaiveDateTime.shift(Duration.negate(UserSession.timeout_duration()))
|> NaiveDateTime.shift(CleanUserSessions.grace_period_duration())
ten_days_after = NaiveDateTime.shift(grace_cutoff, day: 10)
one_day_after = NaiveDateTime.shift(grace_cutoff, day: 1)
one_day_before = NaiveDateTime.shift(grace_cutoff, day: -1)
session_to_clean = insert_session(one_day_before)
session_to_leave1 = insert_session(one_day_after)
session_to_leave2 = insert_session(ten_days_after)
CleanUserSessions.perform(nil)
refute Repo.reload(session_to_clean)
assert Repo.reload(session_to_leave1)
assert Repo.reload(session_to_leave2)
end
defp insert_session(now) do
user = insert(:user)
user
|> UserSession.new_session("Unknown", now)
|> Repo.insert!()
end
end