From 4ef855e8b2807e8701c68ec6e3ea01cb8ac65d3d Mon Sep 17 00:00:00 2001
From: Rutger Wessels <rwessels@gitlab.com>
Date: Mon, 29 Jul 2024 12:03:30 +0200
Subject: [PATCH] Ensure Current.organization is set in REST API

Changelog: changed
---
 lib/api/api.rb                |  7 +++++++
 spec/requests/api/api_spec.rb | 18 ++++++++++++++++++
 2 files changed, 25 insertions(+)

diff --git a/lib/api/api.rb b/lib/api/api.rb
index e19ebe05f32e..b95912e8badb 100644
--- a/lib/api/api.rb
+++ b/lib/api/api.rb
@@ -90,6 +90,13 @@ def initialize(location_url)
       )
     end
 
+    before do
+      ::Current.organization = Gitlab::Current::Organization.new(
+        params: {},
+        user: @current_user
+      ).organization
+    end
+
     before do
       set_peek_enabled_for_current_request
     end
diff --git a/spec/requests/api/api_spec.rb b/spec/requests/api/api_spec.rb
index a1f551528dbe..018abdeed118 100644
--- a/spec/requests/api/api_spec.rb
+++ b/spec/requests/api/api_spec.rb
@@ -421,4 +421,22 @@
       expect(response).to have_gitlab_http_status(:bad_request)
     end
   end
+
+  describe 'Current Organization' do
+    let_it_be(:current_organization) { create(:organization) }
+
+    before do
+      allow_next_instance_of(Gitlab::Current::Organization) do |instance|
+        allow(instance).to receive(:organization).and_return(current_organization)
+      end
+    end
+
+    it 'sets Current Organization' do
+      # Test for new value of Current.organization won't work because
+      # it will be reset after the request is processed.
+      expect(Current).to receive(:organization=).with(current_organization)
+
+      get api('/groups')
+    end
+  end
 end
-- 
GitLab