Skip to content

Explicitly call set_current_organization when a Grape controller needs it

What does this MR do and why?

Setting Current Organization is dependent on Current User. But the current_user method is not returning nil but rendering a Unauthorized HTTP response. So it can't be used in all API calls: for example some API endpoints support other tokens apart from Personal Access Token. Calling current_user while an API has a different authentication method will lead to an HTTP 401 Unauthorized status code.

I tried several options, see a list in the previous MR.

But in the end, I settled for a more explicit approach: Explicitly call set_current_organization if a Grape API controller needs it. All the API controllers that require Current.organization do now have the call to set_current_organization helper method.

There is a risk that developer will forget setting the current organization. To prevent that, an Error will be raised (not in production) with a descriptive error message. This error is disabled for Rails production environment.

[1] pry(main)> pp ::Current.organization
Current::OrganizationNotAssignedError: Assign an organization to Current.organization before calling it.
[2] pry(main)> ::Current.organization = Organizations::Organization.first
=> #<Organizations::Organization:0x0000000150f9f758 id: 1, created_at: Thu, 05 Sep 2024 06:42:35.939165000 UTC +00:00, updated_at: Thu, 05 Sep 2024 06:42:35.939165000 UTC +00:00, name: "Default", path: "default", visibility_level: 20>
[3] pry(main)> pp ::Current.organization
=> #<Organizations::Organization:0x0000000150f9f758 id: 1, created_at: Thu, 05 Sep 2024 06:42:35.939165000 UTC +00:00, updated_at: Thu, 05 Sep 2024 06:42:35.939165000 UTC +00:00, name: "Default", path: "default", visibility_level: 20>

Setting Current.organization=nil is also supported: it still counts as a assigment.

I had to add an exception for Gitlab::CurrentSetting: If Current.organization is not set, it will not read from OrganizationSetting

MR acceptance checklist

Please evaluate this MR against the MR acceptance checklist. It helps you analyze changes to reduce risks in quality, performance, reliability, security, and maintainability.

Related to #482503 (closed)

Edited by Rutger Wessels

Merge request reports

Loading