0
0
Fork 0
mirror of https://github.com/discourse/discourse.git synced 2026-08-04 10:39:43 +08:00
discourse/lib/theme_settings_group_resolver.rb
Martin Brennan bee1be8599
DEV: Add resolve_group_membership for theme object settings of group type (#41756)
Followup 7e77ce4bd3

We need to automatically resolve group membership into a boolean
for theme object type settings which are of the group type, similar
to what we did in the original commit above for group list type
settings.

This behaves in the same way -- for an object setting schema like this:

```
menu_sections:
  type: objects
  default:
    - name: section 1
      groups:
        - 1
        - 3
  schema:
    name: menu section
    properties:
      name:
        type: string
      groups:
        type: groups
        resolve_group_membership: true
```

We replace `groups` with a boolean `user_in_groups` (groups is just
the property name, it could be foo_bar etc.) and then you can
do this on the client:

```
for (const section of settings.menu_sections) {
  if (section.user_in_groups) {
    // User is in at least one selected group for this section.
  }
}
```

Rather than inspecting the `currentUser.groups`, which only includes
visible groups, not all groups the user is a member of. This allows
for more accurate permission checks for theme settings that are group
based.

Also c.f.
https://meta.discourse.org/t/granular-group-based-permissions-for-anonymous-and-logged-in-users/402273/18?u=martin
2026-07-17 10:19:29 +10:00

34 lines
1.3 KiB
Ruby
Vendored

# frozen_string_literal: true
require_relative "theme_settings_group_resolver/list_setting"
require_relative "theme_settings_group_resolver/object_setting"
# Rewrites theme settings that opted into server-side group membership resolution,
# via the resolve_group_membership property in the theme settings schema.
#
# Example:
# settings_hash: { allowed_groups: "1|2", title: "Welcome" }
# type_info: { allowed_groups: { type: "list", resolve_group_membership: true } }
# output: { user_in_allowed_groups: true, title: "Welcome" }
class ThemeSettingsGroupResolver
RESOLVERS = [ThemeSettingsGroupResolver::ListSetting, ThemeSettingsGroupResolver::ObjectSetting]
def self.resolve(settings_hash:, type_info:, guardian:)
new(settings_hash:, type_info:, guardian:).resolve
end
def initialize(settings_hash:, type_info:, guardian:)
@settings_hash = settings_hash
@type_info = type_info || {}
@guardian = guardian
end
def resolve
@type_info.each_with_object(@settings_hash.dup) do |(setting_name, setting_info), settings|
resolver_class = RESOLVERS.find { |resolver| resolver.applies?(setting_info) }
next if !resolver_class
resolver_class.new(setting_name:, setting_info:, guardian: @guardian).resolve!(settings)
end
end
end