From b65700a88f6663ea798a11e2fa35046573684fc6 Mon Sep 17 00:00:00 2001 From: Christian Sutter Date: Thu, 23 Jan 2025 12:17:50 +0000 Subject: [PATCH] Create `Current` model as attributes singleton This uses `ActiveSupport::CurrentAttributes` to track the current user across the request. --- app/controllers/concerns/authentication.rb | 11 +++++++++-- app/controllers/recommended_links_controller.rb | 2 +- app/helpers/application_helper.rb | 4 ++-- app/models/current.rb | 3 +++ 4 files changed, 15 insertions(+), 5 deletions(-) create mode 100644 app/models/current.rb diff --git a/app/controllers/concerns/authentication.rb b/app/controllers/concerns/authentication.rb index 584ce457..33f533a7 100644 --- a/app/controllers/concerns/authentication.rb +++ b/app/controllers/concerns/authentication.rb @@ -1,10 +1,17 @@ -# Requires a user to be logged in through GDS SSO for any action. +# Requires a user to be logged in through GDS SSO for any action, and keeps track of the current +# user through `Current`. module Authentication extend ActiveSupport::Concern included do include GDS::SSO::ControllerMethods - before_action :authenticate_user! + before_action :authenticate_user!, :set_current + end + +private + + def set_current + Current.user = current_user end end diff --git a/app/controllers/recommended_links_controller.rb b/app/controllers/recommended_links_controller.rb index 4ccccb99..e479244e 100644 --- a/app/controllers/recommended_links_controller.rb +++ b/app/controllers/recommended_links_controller.rb @@ -59,6 +59,6 @@ def set_recommended_link def recommended_link_params params .expect(recommended_link: %i[link title description keywords comment]) - .merge(user_id: current_user.id) + .merge(user_id: Current.user.id) end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index 7bbeb06f..a9b9137c 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -1,6 +1,6 @@ module ApplicationHelper def navigation_items - return [] unless current_user + return [] unless Current.user [ { @@ -9,7 +9,7 @@ def navigation_items active: controller.controller_name == "recommended_links", }, { - text: current_user.name, + text: Current.user.name, href: Plek.new.external_url_for("signon"), }, { diff --git a/app/models/current.rb b/app/models/current.rb new file mode 100644 index 00000000..73a9744b --- /dev/null +++ b/app/models/current.rb @@ -0,0 +1,3 @@ +class Current < ActiveSupport::CurrentAttributes + attribute :user +end