From e3590d4eada9f15c72b3f789370d0b4e2021f54e Mon Sep 17 00:00:00 2001 From: Jeff Wong Date: Tue, 14 Apr 2020 06:32:24 -1000 Subject: [PATCH] FEATURE: add user_session_refreshed trigger (#9412) Trigger an event for plugins to consume when a user session is refreshed. This allows external auth to be notified about account activity, and be able to take action such as use oauth refresh tokens to keep oauth tokens valid. --- lib/auth/default_current_user_provider.rb | 1 + .../default_current_user_provider_spec.rb | 37 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/lib/auth/default_current_user_provider.rb b/lib/auth/default_current_user_provider.rb index fc7f8500260..acd9381771c 100644 --- a/lib/auth/default_current_user_provider.rb +++ b/lib/auth/default_current_user_provider.rb @@ -148,6 +148,7 @@ class Auth::DefaultCurrentUserProvider client_ip: @request.ip, path: @env['REQUEST_PATH']) cookies[TOKEN_COOKIE] = cookie_hash(@user_token.unhashed_auth_token) + DiscourseEvent.trigger(:user_session_refreshed, user) end end end diff --git a/spec/components/auth/default_current_user_provider_spec.rb b/spec/components/auth/default_current_user_provider_spec.rb index 621ece61e09..ab4fa863691 100644 --- a/spec/components/auth/default_current_user_provider_spec.rb +++ b/spec/components/auth/default_current_user_provider_spec.rb @@ -595,6 +595,43 @@ describe Auth::DefaultCurrentUserProvider do end + context "events" do + before do + @refreshes = 0 + + @increase_refreshes = -> (user) { @refreshes += 1 } + DiscourseEvent.on(:user_session_refreshed, &@increase_refreshes) + end + + after do + DiscourseEvent.off(:user_session_refreshed, &@increase_refreshes) + end + + it "fires event when updating last seen" do + user = Fabricate(:user) + @provider = provider('/') + cookies = {} + @provider.log_on_user(user, {}, cookies) + unhashed_token = cookies["_t"][:value] + freeze_time 20.minutes.from_now + provider2 = provider("/", "HTTP_COOKIE" => "_t=#{unhashed_token}") + provider2.refresh_session(user, {}, {}) + expect(@refreshes).to eq(1) + end + + it "does not fire an event when last seen does not update" do + user = Fabricate(:user) + @provider = provider('/') + cookies = {} + @provider.log_on_user(user, {}, cookies) + unhashed_token = cookies["_t"][:value] + freeze_time 2.minutes.from_now + provider2 = provider("/", "HTTP_COOKIE" => "_t=#{unhashed_token}") + provider2.refresh_session(user, {}, {}) + expect(@refreshes).to eq(0) + end + end + context "rate limiting" do before do