Skip to content

A platform for community discussion. Free, open, simple.

FEATURE: Support users in DAccessControl and backend (#41358)

Martin Brennan7ff30d81a326
diff --git a/.skills/discourse-acl-authoring/SKILL.md b/.skills/discourse-acl-authoring/SKILL.md
index 4aaedeb0309..3163a055f82 100644
--- a/.skills/discourse-acl-authoring/SKILL.md
+++ b/.skills/discourse-acl-authoring/SKILL.md
@@ -24,7 +24,7 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis
- Use Guardian ACL helpers or `AclTarget` visibility scopes for checks and target scopes instead of hand-querying ACL tables in controllers.
- Register plugin ACL targets with `DiscoursePluginRegistry.register_acl_target_class` so `Site#access_control` exposes mandatory and banned ACL metadata to the frontend.
- Treat `banned_acl` as a server-enforced restriction. `DAccessControl` hides banned permission choices for UX, but `AccessControlListManager` must still reject submitted banned entries.
-- Do not claim user ACL support is complete. Current authoring and UI flows are group-first; `allowed_user_ids` and user entries exist in lower layers but are not fully wired by `expand_list`, `preload_allowed`, cleanup jobs, or `DAccessControl`.
+- Do not claim user ACL support is complete. Backend support is partially wired for `allowed_user_ids` in expansion, flattening, preloading, lookup helpers, matching scopes, and cleanup jobs, but `DAccessControl` remains group-first and does not yet provide complete user ACL editing.
## Local Anchors
@@ -34,7 +34,7 @@ Use this skill before adding or reviewing ACL-backed resource permissions in Dis
- Guardian helpers: `lib/guardian.rb`
- User ACL cache: `app/models/user.rb`
- Write manager: `app/services/access_control_list_manager.rb`
-- Deleted group cleanup: `app/jobs/regular/cleanup_acls_for_deleted.rb`, `app/models/group.rb`
+- Deleted grantee cleanup: `app/jobs/regular/cleanup_acls_for_deleted.rb`, `app/models/group.rb`, `app/models/user.rb`
- Site metadata: `app/models/site.rb`, `app/serializers/site_serializer.rb`
- Frontend component: `frontend/discourse/app/ui-kit/d-access-control.gjs`
- Core specs: `spec/models/access_control_list_spec.rb`, `spec/models/concerns/acl_target_spec.rb`, `spec/lib/acl/target_spec.rb`, `spec/jobs/regular/cleanup_acls_for_deleted_spec.rb`, `spec/services/access_control_list_manager_spec.rb`, `spec/serializers/site_serializer_spec.rb`, `frontend/discourse/tests/integration/components/d-access-control-test.gjs`
diff --git a/.skills/discourse-acl-authoring/references/backend-model.md b/.skills/discourse-acl-authoring/references/backend-model.md
index d78ab8a3b80..ed4055bc6a1 100644
--- a/.skills/discourse-acl-authoring/references/backend-model.md
+++ b/.skills/discourse-acl-authoring/references/backend-model.md
@@ -11,7 +11,7 @@ Important columns:
- `target_type`, `target_id`: polymorphic target.
- `permission`: freeform string such as `view`, `edit`, `manage`, or target-specific permissions.
- `allowed_group_ids`: bigint array of groups that hold the permission.
-- `allowed_user_ids`: bigint array exists, but current authoring/UI support is incomplete.
+- `allowed_user_ids`: bigint array of users that hold the permission. Backend lookup and persistence support is partial; the main remaining gap is complete `DAccessControl` user editing.
- `owner`: string identifying the owning subsystem, usually `"core"` or a plugin name.
The model has a uniqueness validation and DB index for target + permission. Multiple groups for the same permission collapse into one row.
@@ -23,13 +23,13 @@ The frontend and service params use flattened entries:
```ruby
[
{ type: "group", id: group.id, permission: "view" },
- { type: "group", id: other_group.id, permission: "edit" },
+ { type: "user", id: user.id, permission: "edit" },
]
```
-`AccessControlList.expand_list_for_bulk_insert(list, target, owner)` groups those entries by permission and returns rows suitable for `insert_all!`.
+`AccessControlList.expand_list_for_bulk_insert(list, target, owner)` groups those entries by permission and returns rows suitable for `insert_all!`. It fills both `allowed_group_ids` and `allowed_user_ids`.
-`AccessControlList.where(target: target).flattened_list` returns one entry per group per permission, including group metadata:
+`AccessControlList.where(target: target).flattened_list` returns one entry per group or user per permission. Group entries include group metadata:
```ruby
{
@@ -37,14 +37,15 @@ The frontend and service params use flattened entries:
id: group.id,
permission: "view",
mandatory: false,
- name: group.name,
- full_name: group.full_name,
+ display_name: group.full_name.presence || group.name,
metadata: { auto_group: group.automatic? },
target_id: target.id,
target_type: target.class.polymorphic_name,
}
```
+User entries use `type: :user`, `display_name: user.display_name`, and do not include group metadata.
+
Pass `for_target:` only when every row is for the same target; mixed targets raise `Acl::MixedTargetError`.
## Matching Users and Groups
@@ -58,7 +59,7 @@ Pass `for_target:` only when every row is for the same target; mixed targets rai
`AccessControlList.matching_group(group)` returns ACL rows granted directly to the group or directly to users in that group.
-Use `AccessControlList.preload_allowed` before flattening relations that may include many rows. It batches group lookup and memoizes `allowed_groups_preloaded`; user preloading is still a TODO.
+Use `AccessControlList.preload_allowed` before flattening relations that may include many rows. It batches group and user lookups, then memoizes `allowed_groups_preloaded` and `allowed_users_preloaded`.
## Lookup Objects
@@ -69,9 +70,13 @@ target.permission_acl.group_has_permission?(group, "view")
target.permission_acl.group_has_any_permission?(group.id, %w[edit manage])
target.permission_acl.permission_group_ids("view")
target.permission_acl.group_ids_with_any_permission(%w[view edit manage])
+target.permission_acl.user_has_permission?(user, "view")
+target.permission_acl.user_has_any_permission?(user.id, %w[edit manage])
+target.permission_acl.permission_user_ids("view")
+target.permission_acl.user_ids_with_any_permission(%w[view edit manage])
```
-`permission_group_ids` and `group_ids_with_any_permission` return defensive array copies. Missing permissions return `[]`, not `nil`.
+`permission_group_ids`, `group_ids_with_any_permission`, `permission_user_ids`, and `user_ids_with_any_permission` return defensive array copies. Missing permissions return `[]`, not `nil`.
`AccessControlList#user_acl` builds `Acl::User` for a user:
@@ -178,13 +183,13 @@ Banned entries are consumed by both backend writes and frontend rendering:
- `Site#access_control` exposes banned ACL metadata for registered targets.
- `DAccessControl` filters banned permission options for the matching grantee.
-Keep mandatory and banned ACLs group-based unless user ACL support has been completed end-to-end.
+Keep mandatory and banned ACL metadata group-based unless the target flow has explicit user ACL UI and review coverage. Backend lookups can understand user ACL rows, but shared frontend editing is not complete.
## Stale References
`flattened_list` is defensive around stale data:
- Unknown `target_type` values are logged and skipped when no `for_target:` is provided.
-- Deleted groups are skipped instead of raising while flattening.
+- Deleted groups and users are skipped instead of raising while flattening.
-This is a read-path fallback, not a substitute for validation. Validate group ids at the service/contract boundary, and rely on `Jobs::CleanupAclsForDeleted` to remove deleted group ids from persisted ACL rows.
+This is a read-path fallback, not a substitute for validation. Validate group and user ids at the service/contract boundary, and rely on `Jobs::CleanupAclsForDeleted` to remove deleted grantee ids from persisted ACL rows.
diff --git a/.skills/discourse-acl-authoring/references/frontend-d-access-control.md b/.skills/discourse-acl-authoring/references/frontend-d-access-control.md
index d3c598fea2e..d3f13124e40 100644
--- a/.skills/discourse-acl-authoring/references/frontend-d-access-control.md
+++ b/.skills/discourse-acl-authoring/references/frontend-d-access-control.md
@@ -25,7 +25,7 @@ Basic usage:
Arguments:
- `@groups`: group records available for selection. Each group should have `id`, `name`, `full_name`, and `automatic`.
-- `@acl`: flattened ACL entries from the backend or form state.
+- `@acl`: flattened ACL entries from the backend or form state. The backend can emit group and user entries, and this component can add groups from the preloaded `@groups` list plus user/group search results from the ACL grantee search endpoint.
- `@onChange`: called with the next flattened ACL array when the user adds/removes/changes a row.
- `@aclTarget`: optional key used to load mandatory ACL entries from `site.access_control.mandatory_acl` and banned entries from `site.access_control.banned_acl`.
- `@transformPermissionOptions`: optional callback to customize default permission labels/descriptions or add target-specific permissions.
@@ -89,10 +89,14 @@ Target-specific options added via `@transformPermissionOptions` can still be ban
- The remove action remains available unless the row is mandatory.
- Newly added regular groups default to `edit`.
- Read-only default auto groups (`anonymous_users`, `everyone`, `trust_level_0`) default to `view`.
-- Already selected groups are removed from the add-group chooser.
+- Already selected grantees are removed from the add-group chooser's preloaded and remote results.
+- The add control uses `EmailGroupUserChooser` through a DAccessControl-specific wrapper. Preloaded group results preserve numeric group IDs in the ACL payload while displaying group names.
+- Typed add-control searches call `/access-control/grantees/search`, which returns `{ users: [...], groups: [...] }` scoped to the current user's visible users/groups.
+- User rows added from search keep `username`, `name`, and `avatar_template` on the ACL entry so the rendered row can pass them through `rowAsUser` to `dAvatar`.
+- Group rows added from preloaded or remote results keep `name`, `flair_url`, `flair_bg_color`, and `flair_color` on the ACL entry so the rendered row can pass them to `DAvatarFlair`; groups without `flair_url` render the generic `user-group` icon.
- Row DOM metadata uses `data-row-type` and `data-row-id`; tests should not rely on the old `data-group-id` attribute.
-The component remains group-first. It can display entries derived from mandatory ACL metadata for groups, but it does not provide user picking or complete user ACL editing.
+The component is still group-first for preloaded data and mandatory ACL injection. Backend ACL rows can include `type: :user` entries and lookup helpers understand them, but mandatory user ACL display still needs explicit UI support if a target defines user mandatory entries.
## FormKit Integration
diff --git a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md
index c8f3f3f923c..fb8a67ae16d 100644
--- a/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md
+++ b/.skills/discourse-acl-authoring/references/manager-and-plugin-integration.md
@@ -117,11 +117,9 @@ end
Use `TargetClass.with_acl_permission(guardian, permission)` or `TargetClass.with_any_acl_permissions(guardian, permissions)` for index scopes where the user should see targets reachable through ACLs. Use `guardian.target_ids_with_any_acl_permissions(TargetClass, permissions)` only when the id array is the cleaner interface for a custom query.
-## Deleted Group Cleanup
+## Deleted Grantee Cleanup
-`Group#clear_acls` enqueues `Jobs::CleanupAclsForDeleted` after a group is destroyed. The job removes the deleted group id from `allowed_group_ids`, updates `updated_at`, and deletes ACL rows with no remaining `allowed_group_ids` or `allowed_user_ids`.
-
-User cleanup is not complete yet. Do not document deleted-user ACL cleanup as supported until the job handles `user_id`.
+`Group#clear_acls` and `User#clear_acls` enqueue `Jobs::CleanupAclsForDeleted` after a grantee is destroyed. The job removes the deleted group id from `allowed_group_ids` and/or the deleted user id from `allowed_user_ids`, updates `updated_at`, and deletes ACL rows only when both arrays are empty.
## Migrations
@@ -134,7 +132,7 @@ When migrating legacy permission columns into ACLs:
## Current Limitations
-- `AccessControlList.expand_list_for_bulk_insert` is group-first. It does not fully handle `{ type: "user" }` authoring yet.
-- `preload_allowed`, `expand_list`, cleanup, and `DAccessControl` are still group-first even though lower-level matching scopes understand `allowed_user_ids`.
-- `flattened_list` skips missing groups and unknown target classes defensively. Validate group IDs at the service/contract boundary where user input enters; do not rely on read-path skipping as data hygiene.
+- `AccessControlList.expand_list_for_bulk_insert`, `flattened_list`, `preload_allowed`, lookup objects, matching scopes, and cleanup jobs now handle both group and user ACL rows.
+- `DAccessControl` remains group-first: it does not yet provide user picking or complete user ACL editing, even though backend rows can contain `allowed_user_ids`.
+- `flattened_list` skips missing groups, missing users, and unknown target classes defensively. Validate group and user IDs at the service/contract boundary where user input enters; do not rely on read-path skipping as data hygiene.
- The manager has caller-side authorization. Future core work may add a target policy hook; until then, do not expose it directly to untrusted callers.
diff --git a/.skills/discourse-acl-authoring/references/testing-and-review.md b/.skills/discourse-acl-authoring/references/testing-and-review.md
index 7afe6cc7950..e638b4d1188 100644
--- a/.skills/discourse-acl-authoring/references/testing-and-review.md
+++ b/.skills/discourse-acl-authoring/references/testing-and-review.md
@@ -32,13 +32,17 @@ For cleanup behavior:
- Destroying a group enqueues `:cleanup_acls_for_deleted`.
- `Jobs::CleanupAclsForDeleted` removes the group id from ACL rows.
+- Destroying a user enqueues `:cleanup_acls_for_deleted`.
+- `Jobs::CleanupAclsForDeleted` removes the user id from ACL rows.
- ACL rows with no remaining group or user ids are deleted.
- ACL rows that still have user ids are preserved.
+- ACL rows that still have group ids are preserved.
For lookup objects:
- `Acl::Target#permission_group_ids` returns `[]` for missing permissions and a defensive copy for present permissions.
- `Acl::Target#group_ids_with_any_permission` replaces the older `multi_permission_group_ids` name.
+- `Acl::Target#permission_user_ids` and `#user_ids_with_any_permission` return `[]` for missing permissions and defensive array copies for present permissions.
- `Acl::User#target_ids_with_permission` and `#target_ids_with_any_permissions` return defensive array copies.
For migration specs:
@@ -73,7 +77,7 @@ Ask these questions during code review:
- Does the UI `@aclTarget` string match the target's `acl_target_key`?
- Is ACL serialization limited to users who can manage the specific target?
- Are list/index queries using `Target.with_acl_permission`, `Target.with_any_acl_permissions`, `guardian.target_ids_with_acl_permission`, or `target_ids_with_any_acl_permissions` instead of ad hoc SQL?
-- Are group IDs validated before persistence when they come from params?
+- Are group and user IDs validated before persistence when they come from params?
- Are plugin target classes registered with `DiscoursePluginRegistry.register_acl_target_class`?
- Do tests cover anonymous users and pseudo-group semantics if `anonymous_users`, `logged_in_users`, or `everyone` can appear in ACLs?
- Do tests cover stale group rows or missing plugin target classes if the code serializes ACLs that may outlive their original target or group?
@@ -81,8 +85,9 @@ Ask these questions during code review:
## Known Sharp Edges
- `AccessControlListManager` currently assumes caller-side authorization.
-- Group support is complete enough for current UI; user ACL support is not.
+- Backend user ACL support is partial: expansion, flattening, preloading, lookup helpers, matching scopes, and cleanup jobs handle `allowed_user_ids`, but shared UI authoring is not complete.
+- `DAccessControl` remains group-first and does not provide complete user ACL editing yet.
- `DAccessControl` injects mandatory rows for display but does not notify the parent on render.
- `DAccessControl` filters banned permission options for UX, but hidden options are not authorization. The manager policy is the enforcement point.
- Mandatory ACLs from site settings need extra care in migrations because raw stored settings may omit `mandatory_values`.
-- `flattened_list` skips stale group IDs and unknown target classes, so a missing row can disappear from serialized ACL output while cleanup or validation catches up.
+- `flattened_list` skips stale group IDs, stale user IDs, and unknown target classes, so a missing row can disappear from serialized ACL output while cleanup or validation catches up.
diff --git a/app/assets/stylesheets/common/components/d-access-control.scss b/app/assets/stylesheets/common/components/d-access-control.scss
index f681beaae9f..86255937fe6 100644
--- a/app/assets/stylesheets/common/components/d-access-control.scss
+++ b/app/assets/stylesheets/common/components/d-access-control.scss
@@ -1,4 +1,5 @@
.d-access-control {
+ --d-access-control-prefix-width: var(--space-6);
display: flex;
flex-direction: column;
gap: var(--space-2);
@@ -8,10 +9,15 @@
width: 100%;
}
+ &__chooser .select-kit-header {
+ font-weight: 400;
+ }
+
&__rows {
display: flex;
flex-direction: column;
- gap: var(--space-1);
+ border: 1px solid var(--content-border-color);
+ border-radius: var(--d-border-radius);
}
&__row {
@@ -19,15 +25,15 @@
align-items: center;
justify-content: space-between;
gap: var(--space-2);
- padding: var(--space-1) var(--space-2);
border-bottom: 1px solid var(--content-border-color);
+ padding: var(--space-1) var(--space-2);
- &.--mandatory {
- color: var(--d-input-text-color--disabled);
+ &:last-child {
+ border-bottom: none;
}
}
- &__group-name {
+ &__item {
flex: 1 1 auto;
min-width: 0;
overflow: hidden;
@@ -35,27 +41,67 @@
white-space: nowrap;
display: flex;
align-items: center;
+ gap: var(--space-1);
+ }
- svg.d-icon {
- margin-right: var(--space-1);
- }
+ &__row.--group .d-access-control__item-icon {
+ border-radius: 999px;
+ background-color: var(--primary-100);
+ width: var(--d-access-control-prefix-width);
+ height: var(--d-access-control-prefix-width);
+ display: flex;
+ align-items: center;
+ justify-content: center;
}
- &__permission {
- flex: 0 0 auto;
- width: auto;
+ &__row.--group .d-access-control__item-icon svg {
+ width: var(--space-3);
+ height: var(--space-3);
}
- &__permission-divider {
- border-top: 1px solid var(--content-border-color);
+ &__tooltip {
+ font-size: var(--font-down-3);
+ background: var(--primary-100);
+ padding: var(--space-half) var(--space-1);
+ border-radius: var(--d-border-radius);
+ color: var(--d-input-text-color--disabled);
}
- &__permission-remove {
- .texts span {
- color: var(--danger) !important;
+ &__permission.btn-default {
+ border: none;
+
+ &:hover {
+ border: none;
}
}
+ &__permission-menu-content {
+ z-index: z("modal", "dropdown");
+ }
+
+ &__permission-option.--remove .d-access-control__permission-label {
+ color: var(--danger);
+ }
+
+ &__permission-texts {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ line-height: var(--line-height-medium);
+ }
+
+ &__permission-label {
+ font-weight: bold;
+ color: var(--primary);
+ }
+
+ &__permission-description {
+ font-size: var(--font-down-1);
+ color: var(--primary-medium);
+ white-space: normal;
+ text-align: start;
+ }
+
&__add {
width: 100%;
}
diff --git a/app/assets/stylesheets/common/select-kit/email-group-user-chooser.scss b/app/assets/stylesheets/common/select-kit/email-group-user-chooser.scss
index a3d4ce41e02..a2f30e0a984 100644
--- a/app/assets/stylesheets/common/select-kit/email-group-user-chooser.scss
+++ b/app/assets/stylesheets/common/select-kit/email-group-user-chooser.scss
@@ -22,11 +22,57 @@
@include ellipsis;
}
+ .email-group-user-chooser--user {
+ &.--username-first {
+ .identifier {
+ color: var(--primary);
+ white-space: nowrap;
+ line-height: var(--line-height-medium);
+ margin-right: 0.5em;
+ }
+
+ .name {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+
+ @include ellipsis;
+ }
+ }
+
+ &.--name-first {
+ .name {
+ color: var(--primary);
+ white-space: nowrap;
+ line-height: var(--line-height-medium);
+ margin-right: 0.5em;
+ }
+
+ .identifier {
+ color: var(--primary-high);
+ font-size: var(--font-down-1);
+
+ @include ellipsis;
+ }
+ }
+ }
+
.avatar,
.d-icon {
margin-left: 0;
margin-right: 0.5em;
}
+
+ .email-group-user-chooser--group {
+ &.--full-name-only {
+ .name {
+ color: var(--primary);
+ white-space: nowrap;
+ line-height: var(--line-height-medium);
+ font-size: var(--font-down-0);
+ margin-right: 0.5em;
+ }
+ }
+ }
}
.select-kit-header {
diff --git a/app/controllers/access_control_lists_controller.rb b/app/controllers/access_control_lists_controller.rb
new file mode 100644
index 00000000000..2c2d2bf6290
--- /dev/null
+++ b/app/controllers/access_control_lists_controller.rb
@@ -0,0 +1,35 @@
+# frozen_string_literal: true
+
+class AccessControlListsController < ApplicationController
+ requires_login
+
+ SEARCH_GRANTEES_LIMIT = AccessControlList::SearchGrantees::MAX_RESULTS
+
+ # Used to search for _potential_ users and groups to grant access
+ # to a target for an ACL. Exposes same info as public /u and
+ # /g endpoints, hides groups not visible to the current user.
+ def search_grantees
+ limit = fetch_limit_from_params(default: SEARCH_GRANTEES_LIMIT, max: SEARCH_GRANTEES_LIMIT)
+
+ AccessControlList::SearchGrantees.call(
+ service_params.deep_merge(params: { term: params[:term], limit: }),
+ ) do
+ on_success do |users:, groups:|
+ render json: { users: serialize_users(users), groups: serialize_groups(groups) }
+ end
+
+ on_failed_contract { |contract| render_json_error(contract.errors.full_messages) }
+ on_failure { render_json_error(I18n.t("generic_error")) }
+ end
+ end
+
+ private
+
+ def serialize_users(users)
+ ActiveModel::ArraySerializer.new(users, each_serializer: FoundUserSerializer).as_json
+ end
+
+ def serialize_groups(groups)
+ ActiveModel::ArraySerializer.new(groups, each_serializer: FoundGroupSerializer).as_json
+ end
+end
diff --git a/app/jobs/regular/cleanup_acls_for_deleted.rb b/app/jobs/regular/cleanup_acls_for_deleted.rb
index c720ad5dfe8..69effa3d627 100644
--- a/app/jobs/regular/cleanup_acls_for_deleted.rb
+++ b/app/jobs/regular/cleanup_acls_for_deleted.rb
@@ -4,10 +4,7 @@ module Jobs
class CleanupAclsForDeleted < ::Jobs::Base
def execute(args)
group_id = args[:group_id]
-
- # TODO (martin) Handle users in a followup PR
user_id = args[:user_id]
-
return if group_id.blank? && user_id.blank?
if group_id.present?
@@ -20,10 +17,20 @@ module Jobs
)
end
- AccessControlList
- .where("allowed_group_ids = '{}'::bigint[]")
- .where("allowed_user_ids = '{}'::bigint[]")
- .delete_all
+ if user_id.present?
+ AccessControlList.where("allowed_user_ids @> ARRAY[?]::bigint[]", user_id).update_all(
+ [
+ "allowed_user_ids = array_remove(allowed_user_ids, ?), updated_at = ?",
+ user_id,
+ Time.zone.now,
+ ],
+ )
+ end
+
+ # Delete all ACLs that have no grantees left
+ AccessControlList.where(
+ "allowed_group_ids = '{}'::bigint[] AND allowed_user_ids = '{}'::bigint[]",
+ ).delete_all
end
end
end
diff --git a/app/models/access_control_list.rb b/app/models/access_control_list.rb
index 1c2cb4c3544..8f08f42ff12 100644
--- a/app/models/access_control_list.rb
+++ b/app/models/access_control_list.rb
@@ -136,19 +136,22 @@ class AccessControlList < ActiveRecord::Base
permissions_expanded =
list.each_with_object({}) do |entry, permissions|
permissions[entry[:permission]] ||= {}
- # TODO (martin) Handle allowed_user_ids here too in a followup PR when we allow adding them in the UI.
permissions[entry[:permission]][:allowed_group_ids] ||= []
+ permissions[entry[:permission]][:allowed_user_ids] ||= []
if entry[:type].to_sym == :group
permissions[entry[:permission]][:allowed_group_ids] << entry[:id]
- # TODO (martin) Handle allowed_user_ids here too in a followup PR when we allow adding them in the UI.
+ end
+
+ if entry[:type].to_sym == :user
+ permissions[entry[:permission]][:allowed_user_ids] << entry[:id]
end
end
permissions_expanded.map do |permission_name, permission|
{
permission: permission_name,
- # TODO (martin) Handle allowed_user_ids here too in a followup PR when we allow adding them in the UI.
+ allowed_user_ids: permission[:allowed_user_ids],
allowed_group_ids: permission[:allowed_group_ids],
target_type: target.class.polymorphic_name,
target_id: target.id,
@@ -188,19 +191,54 @@ class AccessControlList < ActiveRecord::Base
acls = to_a
groups_by_id = Group.where(id: acls.flat_map(&:allowed_group_ids).uniq).index_by(&:id)
-
- # TODO (martin) Handle users here too in a followup PR
- # users_by_id = User.where(id: acls.flat_map(&:allowed_user_ids).uniq).index_by(&:id)
+ users_by_id = User.where(id: acls.flat_map(&:allowed_user_ids).uniq).index_by(&:id)
acls.each do |acl|
acl.allowed_groups_preloaded ||= acl.allowed_group_ids.filter_map { |id| groups_by_id[id] }
-
- # TODO (martin) Handle users here too in a followup PR
+ acl.allowed_users_preloaded ||= acl.allowed_user_ids.filter_map { |id| users_by_id[id] }
end
self
end
+ def build_acl_entry(access_control_list, target_klass, type, id, allowed_object, for_target)
+ mandatory =
+ target_klass.acl_is_mandatory?({ type:, id:, permission: access_control_list.permission })
+
+ list_entry = {
+ type:,
+ id:,
+ mandatory:,
+ permission: access_control_list.permission,
+ display_name: build_display_name(type, allowed_object),
+ }
+
+ if type == :user
+ list_entry[:avatar_template] = allowed_object.avatar_template
+ list_entry[:username] = allowed_object.username
+ end
+
+ list_entry[:metadata] = { auto_group: allowed_object.automatic? } if type == :group
+
+ if for_target.present?
+ list_entry[:target_id] = for_target.id
+ list_entry[:target_type] = target_klass.polymorphic_name
+ else
+ list_entry[:target_id] = access_control_list.target_id
+ list_entry[:target_type] = target_klass.polymorphic_name
+ end
+
+ list_entry
+ end
+
+ def build_display_name(type, allowed_object)
+ if type == :group
+ allowed_object.full_name.presence || allowed_object.name
+ else
+ allowed_object.display_name
+ end
+ end
+
# Used to display a list of user/group -> permission mappings
# in the UI, and also to construct the TargetAcl and UserAcl
# objects used for permission checks in Ruby.
@@ -209,14 +247,10 @@ class AccessControlList < ActiveRecord::Base
# an array of hashes in this format:
#
# {
- # type: :group,
+ # type: :group/:user,
# id: 3,
# permission: "edit",
- # name: "Group Name", # only for groups
- # full_name: "Full Group Name", # only for groups
- # metadata: {
- # auto_group: true/false, # only for groups
- # },
+ # display_name: "Group Name",
# target_id: 123, # only if for_target is not provided
# target_type: "Category" # only if for_target is not provided
# }
@@ -257,35 +291,36 @@ class AccessControlList < ActiveRecord::Base
next if allowed_group.nil?
- mandatory =
- target_klass.acl_is_mandatory?(
- { type: :group, id: group_id, permission: access_control_list.permission },
+ list_entry =
+ build_acl_entry(
+ access_control_list,
+ target_klass,
+ :group,
+ group_id,
+ allowed_group,
+ for_target,
)
- list_entry = {
- type: :group,
- id: group_id,
- mandatory:,
- permission: access_control_list.permission,
- display_name: allowed_group.full_name.presence || allowed_group.name,
- metadata: {
- auto_group: allowed_group.automatic?,
- },
- }
-
- if for_target.present?
- list_entry[:target_id] = for_target.id
- list_entry[:target_type] = target_klass.polymorphic_name
- else
- list_entry[:target_id] = access_control_list.target_id
- list_entry[:target_type] = target_klass.polymorphic_name
- end
-
flattened_list << list_entry
end
- # TODO (martin) Properly handle users in a followup PR when we allow adding
- # them in the UI.
+ access_control_list.allowed_user_ids.each do |user_id|
+ allowed_user = access_control_list.allowed_users_preloaded.find { |au| au.id == user_id }
+
+ next if allowed_user.nil?
+
+ list_entry =
+ build_acl_entry(
+ access_control_list,
+ target_klass,
+ :user,
+ user_id,
+ allowed_user,
+ for_target,
+ )
+
+ flattened_list << list_entry
+ end
end
flattened_list
diff --git a/app/models/group.rb b/app/models/group.rb
index 140ea4cb30b..405b529d27a 100644
--- a/app/models/group.rb
+++ b/app/models/group.rb
@@ -89,7 +89,6 @@ class Group < ActiveRecord::Base
SvgSprite.expire_cache
end
- # TODO (martin) Also do this for User when following up access_control_list
def clear_acls
Jobs.enqueue(:cleanup_acls_for_deleted, group_id: id)
end
diff --git a/app/models/user.rb b/app/models/user.rb
index b9681050ce1..35d5601dd59 100644
--- a/app/models/user.rb
+++ b/app/models/user.rb
@@ -194,6 +194,12 @@ class User < ActiveRecord::Base
after_update :trigger_user_automatic_group_refresh, if: :saved_change_to_staged?
after_update :change_display_name, if: :saved_change_to_name?
+ after_destroy :clear_acls
+
+ def clear_acls
+ Jobs.enqueue(:cleanup_acls_for_deleted, user_id: id)
+ end
+
after_save :expire_tokens_if_password_changed
after_save :clear_global_notice_if_needed
after_save :refresh_avatar
diff --git a/app/models/user_search.rb b/app/models/user_search.rb
index 1cb3f4a6083..ed0378307e3 100644
--- a/app/models/user_search.rb
+++ b/app/models/user_search.rb
@@ -23,10 +23,10 @@ class UserSearch
@topic = Topic.find(@topic_id) if @topic_id
@category = Category.find(@category_id) if @category_id
- @guardian = Guardian.new(@searching_user)
- @groups&.each { |group| @guardian.ensure_can_see_group_and_members!(group) }
- @guardian.ensure_can_see_category!(@category) if @category
- @guardian.ensure_can_see_topic!(@topic) if @topic
+ guardian = @searching_user&.guardian || Guardian.new
+ @groups&.each { |group| guardian.ensure_can_see_group_and_members!(group) }
+ guardian.ensure_can_see_category!(@category) if @category
+ guardian.ensure_can_see_topic!(@topic) if @topic
end
def scoped_users
diff --git a/app/serializers/found_group_serializer.rb b/app/serializers/found_group_serializer.rb
new file mode 100644
index 00000000000..ea7129bb311
--- /dev/null
+++ b/app/serializers/found_group_serializer.rb
@@ -0,0 +1,14 @@
+# frozen_string_literal: true
+
+class FoundGroupSerializer < ApplicationSerializer
+ attributes :id, :automatic, :name, :full_name, :display_name
+
+ def display_name
+ if object.automatic
+ auto_group_name = Group::AUTO_GROUP_IDS[object.id]
+ I18n.t("groups.default_full_names.#{auto_group_name}")
+ else
+ object.full_name || object.name
+ end
+ end
+end
diff --git a/app/serializers/site_serializer.rb b/app/serializers/site_serializer.rb
index af032d13adb..ac407941b6a 100644
--- a/app/serializers/site_serializer.rb
+++ b/app/serializers/site_serializer.rb
@@ -146,6 +146,7 @@ class SiteSerializer < ApplicationSerializer
id: g.id,
name: g.name,
full_name: g.full_name.presence || g.name,
+ display_name: g.full_name.presence || g.name,
flair_url: g.flair_url,
flair_bg_color: g.flair_bg_color,
flair_color: g.flair_color,
diff --git a/app/services/access_control_list/search_grantees.rb b/app/services/access_control_list/search_grantees.rb
new file mode 100644
index 00000000000..f1dd0d89650
--- /dev/null
+++ b/app/services/access_control_list/search_grantees.rb
@@ -0,0 +1,56 @@
+# frozen_string_literal: true
+
+class AccessControlList::SearchGrantees
+ include Service::Base
+
+ MAX_RESULTS = 50
+
+ params do
+ attribute :term, :string
+ attribute :limit, :integer
+
+ validates :limit,
+ presence: true,
+ numericality: {
+ only_integer: true,
+ greater_than: 0,
+ less_than_or_equal_to: AccessControlList::SearchGrantees::MAX_RESULTS,
+ }
+ end
+
+ model :search_term, optional: true
+ model :visible_groups, optional: true
+ model :users, optional: true
+ model :groups, optional: true
+
+ private
+
+ def fetch_search_term(params:)
+ params.term.to_s.strip.presence
+ end
+
+ def fetch_visible_groups(guardian:)
+ Group.visible_groups(
+ guardian.user,
+ "groups.name ASC",
+ include_everyone: !SiteSetting.granular_anonymous_and_logged_in_groups_permissions,
+ include_pseudogroups: SiteSetting.granular_anonymous_and_logged_in_groups_permissions,
+ )
+ end
+
+ def fetch_users(search_term:, params:, guardian:)
+ if search_term.present?
+ UserSearch.new(search_term, searching_user: guardian.user, limit: params.limit).search
+ else
+ []
+ end
+ end
+
+ def fetch_groups(search_term:, visible_groups:, params:)
+ if search_term.present?
+ Group.search_groups(search_term, groups: visible_groups, sort: :auto).limit(params.limit)
+ else
+ []
+ end
+ end
+end
diff --git a/config/locales/client.en.yml b/config/locales/client.en.yml
index 4a73821ff14..8b2ef594629 100644
--- a/config/locales/client.en.yml
+++ b/config/locales/client.en.yml
@@ -55,9 +55,10 @@ en:
access_permission_viewer: "Viewer"
access_permission_viewer_description: "Can view content for this entity"
access_permission_remove: "Remove"
- access_permission_remove_description: "Remove permission for this group"
- add_group: "Add group"
- mandatory_acl_tooltip: "This permission is mandatory for this entity and cannot be removed"
+ access_permission_remove_description: "Remove permission for this grantee"
+ add_group: "Add user or group"
+ mandatory_acl_tooltip: "This permission is mandatory for %{name} and cannot be removed"
+ mandatory: "Mandatory"
carousel:
go_to_slide: "Go to slide %{index}"
previous: "Previous slide"
diff --git a/config/routes.rb b/config/routes.rb
index a645c1b8254..7ed3245a3f6 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -623,6 +623,7 @@ Discourse::Application.routes.draw do
get "directory-columns" => "directory_columns#index", :format => :json
get "edit-directory-columns" => "edit_directory_columns#index", :format => :json
put "edit-directory-columns" => "edit_directory_columns#update", :format => :json
+ get "access-control/grantees/search" => "access_control_lists#search_grantees"
%w[users u].each_with_index do |root_path, index|
get "#{root_path}" => "users#index", :constraints => { format: "html" }
diff --git a/frontend/discourse/app/ui-kit/d-access-control-grantee-chooser.gjs b/frontend/discourse/app/ui-kit/d-access-control-grantee-chooser.gjs
new file mode 100644
index 00000000000..c7d79b6ad78
--- /dev/null
+++ b/frontend/discourse/app/ui-kit/d-access-control-grantee-chooser.gjs
@@ -0,0 +1,101 @@
+import { ajax } from "discourse/lib/ajax";
+import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
+import { selectKitOptions } from "discourse/select-kit/components/select-kit";
+
+const ACCESS_CONTROL_GRANTEE_SEARCH_URL = "/access-control/grantees/search";
+
+export function granteeValue(type, id) {
+ return `${type}:${id}`;
+}
+
+export function groupGranteeResult(group) {
+ return {
+ value: granteeValue("group", group.id),
+ id: group.name,
+ aclId: group.id,
+ aclType: "group",
+ name: group.name,
+ full_name: group.full_name,
+ display_name: group.display_name,
+ automatic: group.automatic,
+ isGroup: true,
+ };
+}
+
+function userGranteeResult(user) {
+ const sortName = user.name || user.display_name || user.username;
+
+ return {
+ value: granteeValue("user", user.id),
+ id: user.username,
+ aclId: user.id,
+ aclType: "user",
+ name: user.name,
+ sort_name: sortName,
+ username: user.username,
+ showUserStatus: false,
+ avatar_template: user.avatar_template,
+ isUser: true,
+ };
+}
+
+/**
+ * excludedGrantees: an array of grantee values (in format type:id) that should be excluded from the search results,
+ * since they have already been selected. These are passed from DAccessControl.
+ *
+ * onlyShowGroupFullName: for DAccessControl, it's ugly/unnecessary to show the group short_name_with_underscores, we only
+ * want to show the group full name.
+ *
+ * prioritizeUserNameOrdering: for DAccessControl, we want to respect the prioritize_username_in_ux site setting and
+ * show the name before the username in the search results depending on the setting.
+ */
+@selectKitOptions({
+ excludedGrantees: undefined,
+ onlyShowGroupFullName: true,
+ prioritizeUserNameOrdering: true,
+})
+export default class DAccessControlGranteeChooser extends EmailGroupUserChooser {
+ valueProperty = "value";
+
+ async search(filter = "") {
+ if (!filter) {
+ return Promise.resolve(
+ this.selectKit.options.customSearchOptions?.defaultSearchResults || []
+ );
+ }
+
+ try {
+ const results = await ajax(ACCESS_CONTROL_GRANTEE_SEARCH_URL, {
+ data: {
+ term: filter,
+ acl_target: this.selectKit.options.aclTarget,
+ },
+ });
+ const results_2 = this.normalizeGranteeResults(results);
+ return this.excludeSelectedGrantees(results_2);
+ } catch {
+ return [];
+ }
+ }
+
+ normalizeGranteeResults(results) {
+ if (!results) {
+ return [];
+ }
+
+ return [
+ ...(results.groups || []).map(groupGranteeResult),
+ ...(results.users || []).map(userGranteeResult),
+ ];
+ }
+
+ excludeSelectedGrantees(results) {
+ const excludedGrantees = this.selectKit.options.excludedGrantees || [];
+
+ if (!excludedGrantees.length) {
+ return results;
+ }
+
+ return results.filter((result) => !excludedGrantees.includes(result.value));
+ }
+}
diff --git a/frontend/discourse/app/ui-kit/d-access-control.gjs b/frontend/discourse/app/ui-kit/d-access-control.gjs
index 45355eab389..19bfb8e729f 100644
--- a/frontend/discourse/app/ui-kit/d-access-control.gjs
+++ b/frontend/discourse/app/ui-kit/d-access-control.gjs
@@ -1,16 +1,23 @@
import Component from "@glimmer/component";
-import { cached, tracked } from "@glimmer/tracking";
+import { cached } from "@glimmer/tracking";
import { fn, hash } from "@ember/helper";
import { action } from "@ember/object";
import { service } from "@ember/service";
+import DMenu from "discourse/float-kit/components/d-menu";
import DTooltip from "discourse/float-kit/components/d-tooltip";
import { AUTO_GROUPS } from "discourse/lib/constants";
-import ComboBox from "discourse/select-kit/components/combo-box";
-import DropdownSelectBox from "discourse/select-kit/components/dropdown-select-box";
+import { prioritizeNameFallback } from "discourse/lib/settings";
+import { eq } from "discourse/truth-helpers";
import DButton from "discourse/ui-kit/d-button";
+import DDropdownMenu from "discourse/ui-kit/d-dropdown-menu";
+import dAvatar from "discourse/ui-kit/helpers/d-avatar";
import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
import { i18n } from "discourse-i18n";
+import DAccessControlGranteeChooser, {
+ granteeValue,
+ groupGranteeResult,
+} from "./d-access-control-grantee-chooser";
const EDIT_PERMISSION = "edit";
const READ_ONLY_PERMISSION = "view";
@@ -19,6 +26,10 @@ const READ_ONLY_DEFAULT_AUTO_GROUPS = [
AUTO_GROUPS.everyone.id,
AUTO_GROUPS.trust_level_0.id,
];
+const ROW_TYPE_SORT_ORDER = {
+ group: 0,
+ user: 1,
+};
const REMOVE_ACTION = {
id: "remove",
name: i18n("access_control.manage.access_permission_remove"),
@@ -48,11 +59,27 @@ function defaultPermissions() {
];
}
+function rowTypeSortOrder(type) {
+ return ROW_TYPE_SORT_ORDER[type] ?? 2;
+}
+
+const AccessControlPermissionTrigger = <template>
+ <button
+ type="button"
+ class="btn btn-default d-access-control__permission"
+ disabled={{@disabled}}
+ ...attributes
+ >
+ <span class="d-button-label">
+ {{@label}}
+ </span>
+ {{dIcon "angle-down"}}
+ </button>
+</template>;
+
export default class DAccessControl extends Component {
@service site;
- @tracked addingGroup = false;
-
constructor() {
super(...arguments);
this.permissionOptions = this.buildPermissionOptions();
@@ -75,34 +102,7 @@ export default class DAccessControl extends Component {
this.args.transformPermissionOptions?.(defaultPermissions()) ||
defaultPermissions();
- return [
- ...permissions.sort((a, b) => a.level - b.level),
- {
- ...REMOVE_ACTION,
- classNames:
- "d-access-control__permission-divider d-access-control__permission-remove",
- },
- ];
- }
-
- get availableGroups() {
- const taken = new Set(this.selectedGroupIds);
- return (this.args.groups || [])
- .filter((group) => !taken.has(group.id))
- .sort((a, b) => {
- if (a.automatic !== b.automatic) {
- return a.automatic ? -1 : 1;
- }
-
- return (a.full_name || a.name).localeCompare(b.full_name || b.name);
- });
- }
-
- // TODO (martin) Handle user type ACLs here in next PR
- get selectedGroupIds() {
- return this.acl
- .filter((entry) => entry.type === "group")
- .map((entry) => entry.id);
+ return [...permissions.sort((a, b) => a.level - b.level), REMOVE_ACTION];
}
/**
@@ -146,111 +146,188 @@ export default class DAccessControl extends Component {
}
const mandatoryEntryKeys = new Set(
- this.mandatoryAcl.map((entry) => `${entry.type}-${entry.id}`)
+ this.mandatoryAcl.map((entry) => granteeValue(entry.type, entry.id))
);
- const acl = (this.args.acl || []).filter(
- (entry) => !mandatoryEntryKeys.has(`${entry.type}-${entry.id}`)
+
+ // The passed in ACL (if any) without the mandatory entries, which are
+ // added back in below.
+ const resolvedAcl = (this.args.acl || []).filter(
+ (entry) => !mandatoryEntryKeys.has(granteeValue(entry.type, entry.id))
);
- // TODO (martin) Handle user type ACLs here in next PR
this.mandatoryAcl.forEach((entry) => {
- if (entry.type !== "group") {
- return;
- }
-
- const group = (this.args.groups || []).find((g) => g.id === entry.id);
- if (group) {
- acl.push({
- type: "group",
- id: entry.id,
- display_name: group.full_name || group.name,
- permission: entry.permission,
- metadata: {
- auto_group: group.automatic,
- },
- mandatory: true,
- });
+ // NOTE (martin) This is groups only for now...not sure we will need mandatory
+ // user ACLs, but we can figure that out later.
+ if (entry.type === "group") {
+ const group = (this.args.groups || []).find((g) => g.id === entry.id);
+ if (group) {
+ resolvedAcl.push({
+ type: "group",
+ id: entry.id,
+ name: group.name,
+ display_name: group.full_name || group.name,
+ permission: entry.permission,
+ metadata: {
+ auto_group: group.automatic,
+ },
+ mandatory: true,
+ });
+ }
}
});
- return acl;
+ return resolvedAcl;
}
// TODO (martin) How are we going to deal with users that have the Owner permission
// here if we don't want to expose that in the UI?
get rows() {
- return this.acl
- .map((entry) => ({
- key: `${entry.type}-${entry.id}-${entry.permission}`,
- id: entry.id,
- permission: entry.permission,
- display_name: entry.display_name,
- type: entry.type,
- mandatory: entry.mandatory,
- }))
+ const mappedAcl = this.acl.map((entry) => ({
+ key: `${granteeValue(entry.type, entry.id)}:${entry.permission}`,
+ id: entry.id,
+ permission: entry.permission,
+ display_name: entry.display_name,
+ sort_name: entry.sort_name || entry.name || entry.display_name,
+ username: entry.username,
+ name: entry.name,
+ avatar_template: entry.avatar_template,
+ type: entry.type,
+ mandatory: Boolean(entry.mandatory),
+ }));
+
+ return mappedAcl.sort((a, b) => {
+ if (a.mandatory !== b.mandatory) {
+ return a.mandatory ? -1 : 1;
+ }
+
+ const nameSort = (a.sort_name || "").localeCompare(b.sort_name || "");
+
+ if (a.mandatory && b.mandatory) {
+ return nameSort;
+ }
+
+ if (a.type !== b.type) {
+ return rowTypeSortOrder(a.type) - rowTypeSortOrder(b.type);
+ }
+
+ return nameSort;
+ });
+ }
+
+ /**
+ * The default available grantees which are shown in the preloaded
+ * search results for DAccessControlGranteeChooser. This is used to show
+ * the available groups which can be added to the ACL, with users
+ * gated behind an async search request.
+ */
+ get defaultAvailableGrantees() {
+ return this.availableGroups.map(groupGranteeResult);
+ }
+
+ get availableGroups() {
+ const takenGroupIds = new Set(
+ this.acl
+ .filter((entry) => entry.type === "group")
+ .map((entry) => entry.id)
+ );
+
+ return (this.args.groups || [])
+ .filter((group) => !takenGroupIds.has(group.id))
.sort((a, b) => {
- if (a.mandatory !== b.mandatory) {
- return a.mandatory ? -1 : 1;
+ if (a.automatic !== b.automatic) {
+ return a.automatic ? -1 : 1;
}
- return (a.display_name || "").localeCompare(b.display_name || "");
+ return (a.full_name || a.name).localeCompare(b.full_name || b.name);
});
}
- @action
- startAdding() {
- this.addingGroup = true;
+ /**
+ * Grantees which should not show in the search results for
+ * DAccessControlGranteeChooser. This is used to prevent users from adding the
+ * same grantee (a user or group) multiple times.
+ */
+ get excludedGrantees() {
+ return this.acl.map((entry) => granteeValue(entry.type, entry.id));
}
+ /**
+ * Fired when a grantee is chosen from the DAccessControlGranteeChooser
+ * search results.
+ */
@action
- onGroupChosen(groupId) {
- if (groupId == null) {
- this.addingGroup = false;
- return;
- }
+ onGranteeChosen(_value, selectedGrantees) {
+ const selectedGrantee = selectedGrantees?.[0];
- const selectedGroup = (this.args.groups || []).find(
- (group) => group.id === groupId
- );
+ const isReadOnlyDefaultGroup =
+ selectedGrantee.aclType === "group" &&
+ READ_ONLY_DEFAULT_AUTO_GROUPS.includes(selectedGrantee.aclId);
const newPermission = {
- id: selectedGroup.id,
- display_name: selectedGroup.full_name || selectedGroup.name,
- type: "group",
- permission: READ_ONLY_DEFAULT_AUTO_GROUPS.includes(selectedGroup.id)
+ id: selectedGrantee.aclId,
+ type: selectedGrantee.aclType,
+ permission: isReadOnlyDefaultGroup
? READ_ONLY_PERMISSION
: EDIT_PERMISSION,
- metadata: {
- auto_group: selectedGroup.automatic,
- },
};
+ if (selectedGrantee.aclType === "group") {
+ newPermission.name = selectedGrantee.id;
+ newPermission.display_name =
+ selectedGrantee.full_name || selectedGrantee.id;
+ newPermission.metadata = {
+ auto_group: selectedGrantee.automatic,
+ };
+ }
+
+ if (selectedGrantee.aclType === "user") {
+ const sortName =
+ selectedGrantee.sort_name ||
+ selectedGrantee.name ||
+ selectedGrantee.display_name ||
+ selectedGrantee.username;
+
+ newPermission.username = selectedGrantee.username;
+ newPermission.name = selectedGrantee.name;
+ newPermission.sort_name = sortName;
+ newPermission.display_name = prioritizeNameFallback(
+ selectedGrantee.name,
+ selectedGrantee.username
+ );
+ newPermission.avatar_template = selectedGrantee.avatar_template;
+ }
+
const next = [...this.acl, newPermission];
this.args.onChange(next);
- this.addingGroup = false;
}
- // TODO (martin) Handle user type ACLs here in next PR
@action
- onPermissionChange(groupId, permission) {
+ onRowPermissionChange(close, granteeType, granteeId, permission) {
+ close?.();
+
if (permission === REMOVE_ACTION.id) {
this.args.onChange(
this.acl.filter(
- (entry) => !(entry.type === "group" && entry.id === groupId)
+ (entry) => !(entry.type === granteeType && entry.id === granteeId)
)
);
return;
}
const next = this.acl.map((entry) =>
- entry.type === "group" && entry.id === groupId
+ entry.type === granteeType && entry.id === granteeId
? { ...entry, permission }
: entry
);
+
this.args.onChange(next);
}
+ /**
+ * Certain ACL permissions are banned so we need to filter these out
+ * based on grantee type and the available permissions for a row.
+ */
@action
excludeBannedPermissions(permissions, grantee) {
if (!this.bannedAcl.length) {
@@ -267,75 +344,134 @@ export default class DAccessControl extends Component {
});
}
+ @action
+ permissionLabel(permissionId) {
+ return this.permissionOptions.find((option) => option.id === permissionId)
+ .name;
+ }
+
// TODO (martin) How are we going to deal with users that have the Owner permission
// here if we don't want to expose that in the UI?
<template>
<div class="d-access-control">
+ <DAccessControlGranteeChooser
+ class="d-access-control__chooser"
+ @value={{null}}
+ @onChange={{this.onGranteeChosen}}
+ @labelProperty="name"
+ @filterPlaceholder="access_control.manage.add_group"
+ @options={{hash
+ aclTarget=@aclTarget
+ customSearchOptions=(hash
+ defaultSearchResults=this.defaultAvailableGrantees
+ )
+ excludedGrantees=this.excludedGrantees
+ filterable=true
+ includeGroups=true
+ maximum=1
+ none="access_control.manage.add_group"
+ }}
+ />
{{#if this.rows.length}}
<div class="d-access-control__rows">
{{#each this.rows key="key" as |row|}}
<div
class={{dConcatClass
"d-access-control__row"
+ (if (eq row.type "user") "--user" "--group")
(if row.mandatory "--mandatory")
}}
data-row-type={{row.type}}
data-row-id={{row.id}}
>
- <span class="d-access-control__group-name">{{#if row.mandatory}}
- <DTooltip
- @content={{i18n
- "access_control.manage.mandatory_acl_tooltip"
- }}
- >
- <:trigger>
- {{dIcon "lock"}}
- </:trigger>
- </DTooltip>
- {{/if}}
- {{row.display_name}}
+ <span class="d-access-control__item">
+ <span class="d-access-control__item-icon">
+ {{#if (eq row.type "user")}}
+ {{dAvatar row imageSize="small"}}
+ {{/if}}
+ {{#if (eq row.type "group")}}
+ {{dIcon "user-group"}}
+ {{/if}}
+ </span>
+ <span class="d-access-control__item-name">
+ {{row.display_name}}
+ {{#if row.mandatory}}
+ <DTooltip
+ @content={{i18n
+ "access_control.manage.mandatory_acl_tooltip"
+ name=row.display_name
+ }}
+ >
+ <:trigger>
+ <span class="d-access-control__tooltip">{{dIcon "lock"}}
+ {{i18n "access_control.manage.mandatory"}}
+ </span>
+ </:trigger>
+ </DTooltip>
+ {{/if}}
+ </span>
</span>
- <DropdownSelectBox
- class="d-access-control__permission"
- @value={{row.permission}}
- @content={{this.excludeBannedPermissions
- this.permissionOptions
- row
- }}
- @onChange={{fn this.onPermissionChange row.id}}
- @options={{hash
- showCaret=true
- showFullTitle=true
+ <DMenu
+ @identifier="d-access-control__permission-menu"
+ @modalForMobile={{true}}
+ @autofocus={{false}}
+ @triggerComponent={{component
+ AccessControlPermissionTrigger
+ label=(this.permissionLabel row.permission)
disabled=row.mandatory
}}
- />
+ data-permission={{row.permission}}
+ >
+ <:content as |args|>
+ <DDropdownMenu as |dropdown|>
+ {{#each
+ (this.excludeBannedPermissions this.permissionOptions row)
+ key="id"
+ as |option|
+ }}
+ {{#if (eq option.id "remove")}}
+ <dropdown.divider />
+ {{/if}}
+ <dropdown.item>
+ <DButton
+ class={{dConcatClass
+ "d-access-control__permission-option"
+ "--with-description"
+ (if (eq option.id "remove") "--remove")
+ (if (eq option.id row.permission) "-selected")
+ }}
+ data-permission-id={{option.id}}
+ @action={{fn
+ this.onRowPermissionChange
+ args.close
+ row.type
+ row.id
+ option.id
+ }}
+ >
+ <div class="d-access-control__permission-texts">
+ <span class="d-access-control__permission-label">
+ {{option.name}}
+ </span>
+ {{#if option.description}}
+ <span
+ class="d-access-control__permission-description"
+ >
+ {{option.description}}
+ </span>
+ {{/if}}
+ </div>
+ </DButton>
+ </dropdown.item>
+ {{/each}}
+ </DDropdownMenu>
+ </:content>
+ </DMenu>
</div>
{{/each}}
</div>
{{/if}}
-
- {{#if this.addingGroup}}
- <ComboBox
- class="d-access-control__chooser"
- @value={{null}}
- @content={{this.availableGroups}}
- @onChange={{this.onGroupChosen}}
- @labelProperty="full_name"
- @options={{hash
- none="access_control.manage.add_group"
- expandedOnInsert=true
- filterable=true
- }}
- />
- {{else}}
- <DButton
- class="d-access-control__add btn-default"
- @icon="plus"
- @label="access_control.manage.add_group"
- @action={{this.startAdding}}
- />
- {{/if}}
</div>
</template>
}
diff --git a/frontend/discourse/select-kit/components/email-group-user-chooser-row.gjs b/frontend/discourse/select-kit/components/email-group-user-chooser-row.gjs
index ff3e4ba079c..dffab015880 100644
--- a/frontend/discourse/select-kit/components/email-group-user-chooser-row.gjs
+++ b/frontend/discourse/select-kit/components/email-group-user-chooser-row.gjs
@@ -2,19 +2,45 @@ import { classNames } from "@ember-decorators/component";
import decorateUsernameSelector from "discourse/helpers/decorate-username-selector";
import formatUsername from "discourse/helpers/format-username";
import SelectKitRowComponent from "discourse/select-kit/components/select-kit/select-kit-row";
-import { and } from "discourse/truth-helpers";
+import { and, eq } from "discourse/truth-helpers";
import DUserStatusMessage from "discourse/ui-kit/d-user-status-message";
import dAvatar from "discourse/ui-kit/helpers/d-avatar";
+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";
import dIcon from "discourse/ui-kit/helpers/d-icon";
@classNames("email-group-user-chooser-row")
export default class EmailGroupUserChooserRow extends SelectKitRowComponent {
+ get userNameOrdering() {
+ if (
+ !this.selectKit.options.prioritizeUserNameOrdering ||
+ this.siteSettings.prioritize_username_in_ux
+ ) {
+ return "usernameFirst";
+ }
+
+ return "nameFirst";
+ }
+
<template>
{{#if this.item.isUser}}
{{dAvatar this.item imageSize="tiny"}}
- <div>
- <span class="identifier">{{formatUsername this.item.id}}</span>
- <span class="name">{{this.item.name}}</span>
+ <div
+ class={{dConcatClass
+ "email-group-user-chooser--user"
+ (if
+ (eq this.userNameOrdering "usernameFirst")
+ "--username-first"
+ "--name-first"
+ )
+ }}
+ >
+ {{#if (eq this.userNameOrdering "usernameFirst")}}
+ <span class="identifier">{{formatUsername this.item.id}}</span>
+ <span class="name">{{this.item.name}}</span>
+ {{else}}
+ <span class="name">{{this.item.name}}</span>
+ <span class="identifier">{{formatUsername this.item.id}}</span>
+ {{/if}}
</div>
{{#if (and this.item.showUserStatus this.item.status)}}
<DUserStatusMessage
@@ -25,9 +51,26 @@ export default class EmailGroupUserChooserRow extends SelectKitRowComponent {
{{decorateUsernameSelector this.item.id}}
{{else if this.item.isGroup}}
{{dIcon "users"}}
- <div>
- <span class="identifier">{{this.item.id}}</span>
- <span class="name">{{this.item.full_name}}</span>
+ <div
+ class={{dConcatClass
+ "email-group-user-chooser--group"
+ (if this.selectKit.options.onlyShowGroupFullName "--full-name-only")
+ }}
+ >
+ {{#unless this.selectKit.options.onlyShowGroupFullName}}
+ <span class="identifier">{{this.item.id}}</span>
+ {{/unless}}
+ <span class="name">
+ {{#if this.selectKit.options.onlyShowGroupFullName}}
+ {{#if this.item.full_name}}
+ {{this.item.full_name}}
+ {{else}}
+ {{this.item.name}}
+ {{/if}}
+ {{else}}
+ {{this.item.name}}
+ {{/if}}
+ </span>
</div>
{{else}}
{{dIcon "envelope"}}
diff --git a/frontend/discourse/select-kit/components/email-group-user-chooser.js b/frontend/discourse/select-kit/components/email-group-user-chooser.js
index 20db0dd6d04..4f2a196f723 100644
--- a/frontend/discourse/select-kit/components/email-group-user-chooser.js
+++ b/frontend/discourse/select-kit/components/email-group-user-chooser.js
@@ -13,6 +13,8 @@ import EmailGroupUserChooserRow from "./email-group-user-chooser-row";
filterComponent: EmailGroupUserChooserFilter,
fullWidthWrap: false,
autoWrap: false,
+ onlyShowGroupFullName: false,
+ prioritizeUserNameOrdering: false,
})
@pluginApiIdentifiers(["email-group-user-chooser"])
export default class EmailGroupUserChooser extends UserChooserComponent {
@@ -45,7 +47,7 @@ export default class EmailGroupUserChooser extends UserChooserComponent {
}
} else if (item.name) {
reconstructed.id = item.name;
- reconstructed.name = item.full_name;
+ reconstructed.name = item.full_name || item.name;
reconstructed.isGroup = true;
}
return { ...item, ...reconstructed };
diff --git a/frontend/discourse/tests/integration/components/d-access-control-test.gjs b/frontend/discourse/tests/integration/components/d-access-control-test.gjs
index 7dd9c3ac1f4..22e016a4419 100644
--- a/frontend/discourse/tests/integration/components/d-access-control-test.gjs
+++ b/frontend/discourse/tests/integration/components/d-access-control-test.gjs
@@ -1,8 +1,9 @@
import { tracked } from "@glimmer/tracking";
-import { click, render } from "@ember/test-helpers";
+import { click, findAll, render } from "@ember/test-helpers";
import { module, test } from "qunit";
import { AUTO_GROUPS } from "discourse/lib/constants";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
+import pretender, { response } from "discourse/tests/helpers/create-pretender";
import selectKit from "discourse/tests/helpers/select-kit-helper";
import DAccessControl from "discourse/ui-kit/d-access-control";
import { i18n } from "discourse-i18n";
@@ -10,7 +11,12 @@ import { i18n } from "discourse-i18n";
// A non-automatic group, plus the "logged_in_users" auto group (id: 5) which is one of
// the groups that defaults to view-only access when added.
const GROUPS = [
- { id: 42, name: "team_a", full_name: "Team A", automatic: false },
+ {
+ id: 42,
+ name: "team_a",
+ full_name: "Team A",
+ automatic: false,
+ },
{
id: AUTO_GROUPS.logged_in_users.id,
name: "logged_in_users",
@@ -39,10 +45,43 @@ function controlledState(initialAcl = []) {
})();
}
+function permissionOptionSelector(permission) {
+ return `.d-access-control__permission-option[data-permission-id="${permission}"]`;
+}
+
+async function expandPermissionMenu(rowSelector = ".d-access-control__row") {
+ await click(`${rowSelector} .d-access-control__permission`);
+}
+
+async function selectPermission(permission, rowSelector) {
+ await expandPermissionMenu(rowSelector);
+ await click(permissionOptionSelector(permission));
+}
+
+function permissionOptionLabel(permission) {
+ return `${permissionOptionSelector(permission)} .d-access-control__permission-label`;
+}
+
+function permissionOptionDescription(permission) {
+ return `${permissionOptionSelector(
+ permission
+ )} .d-access-control__permission-description`;
+}
+
+function rowNames() {
+ return findAll(".d-access-control__item-name").map((row) =>
+ [...row.childNodes]
+ .find(
+ (node) => node.nodeType === Node.TEXT_NODE && node.textContent.trim()
+ )
+ .textContent.trim()
+ );
+}
+
module("Integration | Component | DAccessControl", function (hooks) {
setupRenderingTest(hooks);
- test("adds a group with the default permission via the availableGroups ComboBox", async function (assert) {
+ test("adds a group with the default permission via the preloaded grantee chooser", async function (assert) {
const state = controlledState();
await render(
@@ -59,17 +98,14 @@ module("Integration | Component | DAccessControl", function (hooks) {
.dom(".d-access-control__row")
.doesNotExist("starts with no acl rows");
- await click(".d-access-control__add");
-
const chooser = selectKit(".d-access-control__chooser");
await chooser.expand();
- await chooser.expand();
assert
- .dom(".d-access-control__chooser .select-kit-row[data-value='42']")
+ .dom(".d-access-control__chooser .select-kit-row[data-value='group:42']")
.exists("availableGroups are listed in the chooser");
- await chooser.selectRowByValue(42);
+ await chooser.selectRowByValue("group:42");
assert.strictEqual(
state.onChangeCalls.length,
@@ -92,8 +128,11 @@ module("Integration | Component | DAccessControl", function (hooks) {
);
assert
- .dom(".d-access-control__row .d-access-control__group-name")
+ .dom(".d-access-control__row .d-access-control__item-name")
.hasText("Team A", "renders the newly added group row");
+ assert
+ .dom(".d-access-control__row .d-icon-user-group")
+ .exists("renders the generic group icon");
});
test("a read-only default group is added with the view permission", async function (assert) {
@@ -109,12 +148,9 @@ module("Integration | Component | DAccessControl", function (hooks) {
</template>
);
- await click(".d-access-control__add");
-
const chooser = selectKit(".d-access-control__chooser");
await chooser.expand();
- await chooser.expand();
- await chooser.selectRowByValue(AUTO_GROUPS.trust_level_0.id);
+ await chooser.selectRowByValue(`group:${AUTO_GROUPS.trust_level_0.id}`);
const [added] = state.onChangeCalls[0];
assert.strictEqual(
@@ -122,6 +158,170 @@ module("Integration | Component | DAccessControl", function (hooks) {
"view",
"applies the default view permission for a read-only default group"
);
+ assert
+ .dom(".d-access-control__row .d-icon-user-group")
+ .exists("renders the generic group icon when the group has no flair");
+ });
+
+ test("searches grantees using the access control search endpoint", async function (assert) {
+ pretender.get("/access-control/grantees/search", (request) => {
+ assert.strictEqual(
+ request.queryParams.term,
+ "ada",
+ "passes the filter term to the search endpoint"
+ );
+
+ return response({
+ users: [
+ {
+ id: 7,
+ username: "ada",
+ name: "Ada Lovelace",
+ avatar_template: "/letter_avatar_proxy/v4/letter/a/{size}.png",
+ },
+ ],
+ groups: [],
+ });
+ });
+
+ const state = controlledState();
+
+ await render(
+ <template>
+ <DAccessControl
+ @groups={{GROUPS}}
+ @acl={{state.acl}}
+ @aclTarget="TestTarget"
+ @onChange={{state.onChange}}
+ />
+ </template>
+ );
+
+ const chooser = selectKit(".d-access-control__chooser");
+ await chooser.expand();
+ await chooser.fillInFilter("ada");
+ await chooser.selectRowByValue("user:7");
+
+ const [added] = state.onChangeCalls[0];
+ assert.strictEqual(added.id, 7, "adds the chosen user");
+ assert.strictEqual(added.type, "user", "marks the entry as a user");
+ assert.strictEqual(
+ added.display_name,
+ "ada",
+ "sets the display name from the site setting fallback"
+ );
+ assert.strictEqual(
+ added.username,
+ "ada",
+ "keeps the username for avatar rendering"
+ );
+ assert.strictEqual(
+ added.name,
+ "Ada Lovelace",
+ "keeps the name for avatar rendering"
+ );
+ assert.strictEqual(
+ added.avatar_template,
+ "/letter_avatar_proxy/v4/letter/a/{size}.png",
+ "keeps the avatar template for avatar rendering"
+ );
+ assert.strictEqual(
+ added.permission,
+ "edit",
+ "applies the default edit permission for a user"
+ );
+ });
+
+ test("sorts newly selected users by name while respecting the display name setting", async function (assert) {
+ const displayNameOnPosts = this.siteSettings.display_name_on_posts;
+ const prioritizeUsernameInUx = this.siteSettings.prioritize_username_in_ux;
+ this.siteSettings.display_name_on_posts = false;
+ this.siteSettings.prioritize_username_in_ux = true;
+
+ pretender.get("/access-control/grantees/search", () => {
+ return response({
+ users: [
+ {
+ id: 7,
+ username: "edgar",
+ name: "Edgar Allan Poe",
+ avatar_template: "/letter_avatar_proxy/v4/letter/e/{size}.png",
+ },
+ ],
+ groups: [],
+ });
+ });
+
+ try {
+ const state = controlledState([
+ {
+ type: "group",
+ id: 999,
+ permission: "edit",
+ display_name: "Staff",
+ mandatory: false,
+ },
+ {
+ type: "user",
+ id: 2,
+ permission: "edit",
+ display_name: "Aaron User",
+ mandatory: false,
+ },
+ {
+ type: "user",
+ id: 3,
+ permission: "edit",
+ display_name: "Marco Bianchi",
+ mandatory: false,
+ },
+ {
+ type: "user",
+ id: 4,
+ permission: "edit",
+ display_name: "Zoe User",
+ mandatory: false,
+ },
+ ]);
+
+ await render(
+ <template>
+ <DAccessControl
+ @groups={{GROUPS}}
+ @acl={{state.acl}}
+ @aclTarget="TestTarget"
+ @onChange={{state.onChange}}
+ />
+ </template>
+ );
+
+ const chooser = selectKit(".d-access-control__chooser");
+ await chooser.expand();
+ await chooser.fillInFilter("edgar");
+ await chooser.selectRowByValue("user:7");
+
+ const added = state.onChangeCalls[0].find(
+ (entry) => entry.type === "user" && entry.id === 7
+ );
+ assert.strictEqual(
+ added.display_name,
+ "edgar",
+ "uses the username as the display name when names are not prioritized"
+ );
+ assert.strictEqual(
+ added.sort_name,
+ "Edgar Allan Poe",
+ "keeps the user's name as the sort key"
+ );
+ assert.deepEqual(
+ rowNames(),
+ ["Staff", "Aaron User", "edgar", "Marco Bianchi", "Zoe User"],
+ "inserts the selected user according to the user's name"
+ );
+ } finally {
+ this.siteSettings.display_name_on_posts = displayNameOnPosts;
+ this.siteSettings.prioritize_username_in_ux = prioritizeUsernameInUx;
+ }
});
test("transformPermissionOptions can change descriptions and add options", async function (assert) {
@@ -140,7 +340,12 @@ module("Integration | Component | DAccessControl", function (hooks) {
? { ...permission, description: "Custom view description" }
: permission
),
- { id: "juggler", level: 3, name: "Juggler", description: "Full control" },
+ {
+ id: "juggler",
+ level: 3,
+ name: "Juggler",
+ description: "Full control",
+ },
];
await render(
@@ -154,24 +359,21 @@ module("Integration | Component | DAccessControl", function (hooks) {
</template>
);
- const permission = selectKit(".d-access-control__permission");
- await permission.expand();
+ await expandPermissionMenu();
- assert.strictEqual(
- permission.rowByValue("view").description(),
- "Custom view description",
- "uses the transformed description for an existing option"
- );
+ assert
+ .dom(permissionOptionDescription("view"))
+ .hasText(
+ "Custom view description",
+ "uses the transformed description for an existing option"
+ );
- assert.true(
- permission.rowByValue("juggler").exists(),
- "renders the added permission option"
- );
- assert.strictEqual(
- permission.rowByValue("juggler").label(),
- "Juggler",
- "the added option keeps its name"
- );
+ assert
+ .dom(permissionOptionSelector("juggler"))
+ .exists("renders the added permission option");
+ assert
+ .dom(permissionOptionLabel("juggler"))
+ .hasText("Juggler", "the added option keeps its name");
});
test("loads multiple existing acl groups with their permissions", async function (assert) {
@@ -207,22 +409,24 @@ module("Integration | Component | DAccessControl", function (hooks) {
const rows = [...document.querySelectorAll(".d-access-control__row")];
assert
- .dom(".d-access-control__group-name", rows[0])
+ .dom(".d-access-control__item-name", rows[0])
.hasText("Another Group", "renders the first group name");
- assert.strictEqual(
- rows[0].querySelector(".select-kit-header").dataset.value,
- "edit",
- "loads the first group's permission"
- );
+ assert
+ .dom(".d-access-control__permission", rows[0])
+ .hasText(
+ i18n("access_control.manage.access_permission_editor"),
+ "loads the first group's permission"
+ );
assert
- .dom(".d-access-control__group-name", rows[1])
+ .dom(".d-access-control__item-name", rows[1])
.hasText("Some Group", "renders the second group name");
- assert.strictEqual(
- rows[1].querySelector(".select-kit-header").dataset.value,
- "view",
- "loads the second group's permission"
- );
+ assert
+ .dom(".d-access-control__permission", rows[1])
+ .hasText(
+ i18n("access_control.manage.access_permission_viewer"),
+ "loads the second group's permission"
+ );
});
test("the Remove option removes the acl row", async function (assert) {
@@ -253,16 +457,13 @@ module("Integration | Component | DAccessControl", function (hooks) {
assert.dom(".d-access-control__row").exists({ count: 2 });
- // selectKit() targets the first matching dropdown, i.e. the "Some Group" row.
- const permission = selectKit(".d-access-control__permission");
- await permission.expand();
- await permission.selectRowByValue("remove");
+ await selectPermission("remove");
assert
.dom(".d-access-control__row")
.exists({ count: 1 }, "removes the row whose permission was removed");
assert
- .dom(".d-access-control__group-name")
+ .dom(".d-access-control__item-name")
.hasText("Some Group", "keeps the remaining row");
});
@@ -286,9 +487,7 @@ module("Integration | Component | DAccessControl", function (hooks) {
</template>
);
- const permission = selectKit(".d-access-control__permission");
- await permission.expand();
- await permission.selectRowByValue("edit");
+ await selectPermission("edit");
assert.strictEqual(
state.onChangeCalls.length,
@@ -322,19 +521,20 @@ module("Integration | Component | DAccessControl", function (hooks) {
</template>
);
- const permission = selectKit(".d-access-control__permission");
- await permission.expand();
+ await expandPermissionMenu();
- assert.strictEqual(
- permission.rowByValue("view").label(),
- i18n("access_control.manage.access_permission_viewer"),
- "renders the default viewer option"
- );
- assert.strictEqual(
- permission.rowByValue("edit").label(),
- i18n("access_control.manage.access_permission_editor"),
- "renders the default editor option"
- );
+ assert
+ .dom(permissionOptionLabel("view"))
+ .hasText(
+ i18n("access_control.manage.access_permission_viewer"),
+ "renders the default viewer option"
+ );
+ assert
+ .dom(permissionOptionLabel("edit"))
+ .hasText(
+ i18n("access_control.manage.access_permission_editor"),
+ "renders the default editor option"
+ );
});
test("filters banned permissions for the matching grantee", async function (assert) {
@@ -358,7 +558,12 @@ module("Integration | Component | DAccessControl", function (hooks) {
const transformPermissionOptions = (permissions) => [
...permissions,
- { id: "manage", level: 3, name: "Manager", description: "Full control" },
+ {
+ id: "manage",
+ level: 3,
+ name: "Manager",
+ description: "Full control",
+ },
];
await render(
@@ -373,25 +578,20 @@ module("Integration | Component | DAccessControl", function (hooks) {
</template>
);
- const permission = selectKit(".d-access-control__permission");
- await permission.expand();
+ await expandPermissionMenu();
- assert.true(
- permission.rowByValue("view").exists(),
- "keeps permissions not banned for this grantee"
- );
- assert.false(
- permission.rowByValue("edit").exists(),
- "removes a banned default permission"
- );
- assert.false(
- permission.rowByValue("manage").exists(),
- "removes a banned transformed permission"
- );
- assert.true(
- permission.rowByValue("remove").exists(),
- "keeps the remove action"
- );
+ assert
+ .dom(permissionOptionSelector("view"))
+ .exists("keeps permissions not banned for this grantee");
+ assert
+ .dom(permissionOptionSelector("edit"))
+ .doesNotExist("removes a banned default permission");
+ assert
+ .dom(permissionOptionSelector("manage"))
+ .doesNotExist("removes a banned transformed permission");
+ assert
+ .dom(permissionOptionSelector("remove"))
+ .exists("keeps the remove action");
});
test("puts mandatory permissions at the top of the rows and disables removing the permission", async function (assert) {
@@ -424,15 +624,66 @@ module("Integration | Component | DAccessControl", function (hooks) {
const rows = [...document.querySelectorAll(".d-access-control__row")];
assert.dom(rows[0]).hasClass("--mandatory", "the mandatory row is first");
assert
- .dom(
- rows[0].querySelector(
- ".d-access-control__permission.dropdown-select-box"
- )
- )
- .hasClass(
- "is-disabled",
- "the mandatory row's permission select is disabled"
- );
+ .dom(".d-access-control__permission", rows[0])
+ .isDisabled("the mandatory row's permission select is disabled");
+ });
+
+ test("sorts rows by mandatory status, type, and name", async function (assert) {
+ const state = controlledState([
+ {
+ type: "user",
+ id: 1,
+ permission: "edit",
+ display_name: "Zoe User",
+ mandatory: true,
+ },
+ {
+ type: "group",
+ id: 999,
+ permission: "view",
+ display_name: "Alpha Group",
+ mandatory: true,
+ },
+ {
+ type: "user",
+ id: 2,
+ permission: "edit",
+ display_name: "Aaron User",
+ },
+ {
+ type: "group",
+ id: 1001,
+ permission: "edit",
+ display_name: "Beta Group",
+ },
+ {
+ type: "group",
+ id: 1002,
+ permission: "view",
+ display_name: "Apple Group",
+ },
+ ]);
+
+ await render(
+ <template>
+ <DAccessControl
+ @groups={{GROUPS}}
+ @acl={{state.acl}}
+ @onChange={{state.onChange}}
+ />
+ </template>
+ );
+
+ assert.deepEqual(
+ rowNames(),
+ ["Alpha Group", "Zoe User", "Apple Group", "Beta Group", "Aaron User"],
+ "sorts mandatory rows by name, then groups by name, then users by name"
+ );
+ assert.deepEqual(
+ findAll(".d-access-control__row").map((row) => row.dataset.rowType),
+ ["group", "user", "group", "group", "user"],
+ "keeps regular groups before regular users"
+ );
});
test("injects mandatory acl rows for the target", async function (assert) {
@@ -461,15 +712,15 @@ module("Integration | Component | DAccessControl", function (hooks) {
.dom(".d-access-control__row")
.hasClass("--mandatory", "marks the row as mandatory");
assert
- .dom(".d-access-control__group-name")
- .hasText("Team A", "renders the mandatory group's name");
+ .dom(".d-access-control__item-name")
+ .includesText("Team A", "renders the mandatory group's name");
- assert.strictEqual(
- document.querySelector(".d-access-control__permission .select-kit-header")
- .dataset.value,
- "edit",
- "uses the mandatory permission"
- );
+ assert
+ .dom(".d-access-control__permission")
+ .hasText(
+ i18n("access_control.manage.access_permission_editor"),
+ "uses the mandatory permission"
+ );
assert.strictEqual(
state.onChangeCalls.length,
0,
@@ -507,11 +758,11 @@ module("Integration | Component | DAccessControl", function (hooks) {
.dom(".d-access-control__row")
.exists({ count: 1 }, "does not render a duplicate group row");
- assert.strictEqual(
- document.querySelector(".d-access-control__permission .select-kit-header")
- .dataset.value,
- "edit",
- "uses the mandatory permission"
- );
+ assert
+ .dom(".d-access-control__permission")
+ .hasText(
+ i18n("access_control.manage.access_permission_editor"),
+ "uses the mandatory permission"
+ );
});
});
diff --git a/frontend/discourse/tests/integration/components/select-kit/email-group-user-chooser-test.gjs b/frontend/discourse/tests/integration/components/select-kit/email-group-user-chooser-test.gjs
index f370bbbb362..dd6eeaebb8d 100644
--- a/frontend/discourse/tests/integration/components/select-kit/email-group-user-chooser-test.gjs
+++ b/frontend/discourse/tests/integration/components/select-kit/email-group-user-chooser-test.gjs
@@ -1,5 +1,5 @@
import { hash } from "@ember/helper";
-import { fillIn, render } from "@ember/test-helpers";
+import { fillIn, find, findAll, render } from "@ember/test-helpers";
import { module, test } from "qunit";
import EmailGroupUserChooser from "discourse/select-kit/components/email-group-user-chooser";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
@@ -16,6 +16,164 @@ module(
this.set("subject", selectKit());
});
+ test("renders group results with group name and full name", async function (assert) {
+ this.set("defaultSearchResults", [
+ {
+ name: "team_a",
+ full_name: "Team A",
+ isGroup: true,
+ },
+ ]);
+
+ await render(
+ <template>
+ <EmailGroupUserChooser
+ @options={{hash
+ customSearchOptions=(hash
+ defaultSearchResults=this.defaultSearchResults
+ )
+ }}
+ />
+ </template>
+ );
+
+ await this.subject.expand();
+
+ assert
+ .dom(".email-group-user-chooser--group")
+ .doesNotHaveClass("--name-only", "renders the default group row style");
+ assert
+ .dom(".email-group-user-chooser--group .identifier")
+ .hasText("team_a", "renders the group name as the identifier");
+ assert
+ .dom(".email-group-user-chooser--group .name")
+ .hasText("Team A", "renders the full group name as the label");
+ });
+
+ test("onlyShowGroupFullName renders only the group display name", async function (assert) {
+ this.set("defaultSearchResults", [
+ {
+ name: "team_a",
+ full_name: "Team A Full Name",
+ isGroup: true,
+ },
+ {
+ name: "team_b",
+ isGroup: true,
+ },
+ ]);
+
+ await render(
+ <template>
+ <EmailGroupUserChooser
+ @options={{hash
+ onlyShowGroupFullName=true
+ customSearchOptions=(hash
+ defaultSearchResults=this.defaultSearchResults
+ )
+ }}
+ />
+ </template>
+ );
+
+ await this.subject.expand();
+
+ assert
+ .dom(".email-group-user-chooser--group")
+ .hasClass(
+ "--full-name-only",
+ "applies the full-name-only group row style"
+ );
+ assert
+ .dom(".email-group-user-chooser--group .identifier")
+ .doesNotExist("hides the group identifier");
+ assert.deepEqual(
+ findAll(".email-group-user-chooser--group .name").map((row) =>
+ row.textContent.trim()
+ ),
+ ["Team A Full Name", "team_b"],
+ "uses the full name when present and falls back to the group name"
+ );
+ });
+
+ test("prioritizeUserNameOrdering can render the name before username", async function (assert) {
+ this.siteSettings.prioritize_username_in_ux = false;
+ this.set("defaultSearchResults", [
+ {
+ username: "ada",
+ name: "Ada Lovelace",
+ isUser: true,
+ },
+ ]);
+
+ await render(
+ <template>
+ <EmailGroupUserChooser
+ @options={{hash
+ prioritizeUserNameOrdering=true
+ customSearchOptions=(hash
+ defaultSearchResults=this.defaultSearchResults
+ )
+ }}
+ />
+ </template>
+ );
+
+ await this.subject.expand();
+
+ const userRow = find(".email-group-user-chooser--user");
+
+ assert
+ .dom(userRow)
+ .hasClass("--name-first", "applies the name-first row style");
+ assert.deepEqual(
+ [...userRow.querySelectorAll("span")].map((row) =>
+ row.textContent.trim()
+ ),
+ ["Ada Lovelace", "ada"],
+ "renders name before username"
+ );
+ });
+
+ test("prioritize_username_in_ux keeps username first", async function (assert) {
+ this.siteSettings.prioritize_username_in_ux = true;
+ this.set("defaultSearchResults", [
+ {
+ username: "ada",
+ name: "Ada Lovelace",
+ isUser: true,
+ },
+ ]);
+
+ await render(
+ <template>
+ <EmailGroupUserChooser
+ @options={{hash
+ prioritizeUserNameOrdering=true
+ customSearchOptions=(hash
+ defaultSearchResults=this.defaultSearchResults
+ )
+ }}
+ />
+ </template>
+ );
+
+ await this.subject.expand();
+
+ const userRow = find(".email-group-user-chooser--user");
+
+ assert
+ .dom(userRow)
+ .hasClass("--username-first", "keeps the username-first row style");
+ assert.deepEqual(
+ [...userRow.querySelectorAll("span")].map((row) =>
+ row.textContent.trim()
+ ),
+ ["ada", "Ada Lovelace"],
+ "renders username before name"
+ );
+ });
+
test("pasting", async function (assert) {
await render(<template><EmailGroupUserChooser /></template>);
diff --git a/lib/acl/target.rb b/lib/acl/target.rb
index 2f566424c82..068584818e3 100644
--- a/lib/acl/target.rb
+++ b/lib/acl/target.rb
@@ -1,22 +1,33 @@
# frozen_string_literal: true
module Acl
+ # This class is used to provide easy lookup methods for
+ # a single target's flattened ACL list, which consists
+ # of a mix of group and user IDs and their associated permissions,
+ # as an alternative to iterating through the flattened array.
class Target
- attr_reader :group_lookup, :permission_lookup
+ attr_reader :group_lookup, :permission_lookup, :user_lookup
def initialize(flattened_acl_list)
@group_lookup = {}
+ @user_lookup = {}
@permission_lookup = {}
flattened_acl_list.each do |acl|
- @permission_lookup[acl[:permission]] ||= { group_ids: [] }
+ @permission_lookup[acl[:permission]] ||= { group_ids: [], user_ids: [] }
if acl[:type].to_sym == :group
@group_lookup[acl[:id]] ||= []
@group_lookup[acl[:id]] << acl[:permission]
- # TODO (martin) Handle users here too in a followup PR when we allow adding them in the UI.
@permission_lookup[acl[:permission]][:group_ids] << acl[:id]
end
+
+ if acl[:type].to_sym == :user
+ @user_lookup[acl[:id]] ||= []
+ @user_lookup[acl[:id]] << acl[:permission]
+
+ @permission_lookup[acl[:permission]][:user_ids] << acl[:id]
+ end
end
end
@@ -38,5 +49,22 @@ module Acl
def group_ids_with_any_permission(permissions)
permissions.flat_map { |permission| permission_group_ids(permission) || [] }.uniq.dup
end
+
+ def user_has_permission?(user_or_id, permission)
+ @user_lookup[user_or_id.is_a?(Numeric) ? user_or_id : user_or_id&.id]&.include?(permission)
+ end
+
+ def user_has_any_permission?(user_or_id, permissions)
+ user_permissions = @user_lookup[user_or_id.is_a?(Numeric) ? user_or_id : user_or_id&.id]
+ (user_permissions || []).any? { |permission| permissions.include?(permission) }
+ end
+
+ def permission_user_ids(permission)
+ ((@permission_lookup[permission] || {}).dig(:user_ids) || []).dup
+ end
+
+ def user_ids_with_any_permission(permissions)
+ permissions.flat_map { |permission| permission_user_ids(permission) || [] }.uniq.dup
+ end
end
end
diff --git a/lib/acl/user.rb b/lib/acl/user.rb
index 267192291ec..706cbf0cbe8 100644
--- a/lib/acl/user.rb
+++ b/lib/acl/user.rb
@@ -1,6 +1,9 @@
# frozen_string_literal: true
module Acl
+ # This class is used to provide easy lookup methods for a single user's
+ # flattened ACL list, which can consist of multiple different targets, as an
+ # alternative to iterating through the flattened array.
class User
attr_reader :target_lookup, :permission_lookup
diff --git a/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb b/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb
index c2c7156c257..7477248b42f 100644
--- a/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb
+++ b/spec/jobs/regular/cleanup_acls_for_deleted_spec.rb
@@ -34,4 +34,41 @@ RSpec.describe Jobs::CleanupAclsForDeleted do
expect(AccessControlList.find_by(id: acl_4_id)).not_to eq(nil)
end
end
+
+ context "when a user is deleted" do
+ fab!(:user)
+ fab!(:other_user, :user)
+ fab!(:third_user, :user)
+ fab!(:group)
+
+ fab!(:access_control_list_1) do
+ Fabricate(:access_control_list_with_users, users: [user, other_user])
+ end
+ fab!(:access_control_list_2) do
+ Fabricate(:access_control_list_with_users, users: [other_user, third_user])
+ end
+ fab!(:access_control_list_3) { Fabricate(:access_control_list_with_users, users: [user]) }
+ fab!(:access_control_list_4) do
+ Fabricate(:access_control_list_with_users_and_groups, users: [user], groups: [group])
+ end
+
+ it "removes the user from associated access_control_list records when the user is destroyed" do
+ user.destroy!
+ described_class.new.execute(user_id: user.id)
+
+ expect(access_control_list_1.reload.allowed_user_ids).to eq([other_user.id])
+ expect(access_control_list_2.reload.allowed_user_ids).to eq([other_user.id, third_user.id])
+ end
+
+ it "destroys the ACL when the ACL record has no more allowed ids of users or groups" do
+ acl_3_id = access_control_list_3.id
+ acl_4_id = access_control_list_4.id
+
+ user.destroy!
+ described_class.new.execute(user_id: user.id)
+
+ expect(AccessControlList.find_by(id: acl_3_id)).to eq(nil)
+ expect(AccessControlList.find_by(id: acl_4_id)).not_to eq(nil)
+ end
+ end
end
diff --git a/spec/lib/acl/target_spec.rb b/spec/lib/acl/target_spec.rb
index 71bb1c3be20..438994c2f75 100644
--- a/spec/lib/acl/target_spec.rb
+++ b/spec/lib/acl/target_spec.rb
@@ -4,16 +4,15 @@ RSpec.describe Acl::Target do
subject(:target_acl) { described_class.new(flattened_acl_list) }
fab!(:group)
+ fab!(:user)
- # A single target (e.g. a Category) with two groups and one user entry.
- # `group` has view + edit, group 22 has view only, and a user entry exists
- # for the "manage" permission (users are ignored for group lookups).
let(:flattened_acl_list) do
[
{ type: :group, id: group.id, permission: "view", target_type: "Category", target_id: 5 },
{ type: :group, id: group.id, permission: "edit", target_type: "Category", target_id: 5 },
{ type: "group", id: 22, permission: "view", target_type: "Category", target_id: 5 },
- { type: :user, id: 99, permission: "manage", target_type: "Category", target_id: 5 },
+ { type: :user, id: user.id, permission: "manage", target_type: "Category", target_id: 5 },
+ { type: "user", id: 99, permission: "view", target_type: "Category", target_id: 5 },
]
end
@@ -86,4 +85,71 @@ RSpec.describe Acl::Target do
)
end
end
+
+ describe "#user_has_permission?" do
+ it "returns true when the user id holds the permission" do
+ expect(target_acl.user_has_permission?(user.id, "manage")).to eq(true)
+ end
+
+ it "accepts a user record as well as an id" do
+ expect(target_acl.user_has_permission?(user, "manage")).to eq(true)
+ end
+
+ it "returns false when the user does not hold the permission" do
+ expect(target_acl.user_has_permission?(99, "manage")).to eq(false)
+ end
+
+ it "returns nil for a user not present in the list" do
+ expect(target_acl.user_has_permission?(123_456, "view")).to be_nil
+ end
+
+ it "does not grant user permissions from non-user entries" do
+ expect(target_acl.user_has_permission?(group.id, "edit")).to be_nil
+ end
+ end
+
+ describe "#user_has_any_permission?" do
+ it "returns true when the user holds any of the permissions" do
+ expect(target_acl.user_has_any_permission?(user.id, %w[view manage])).to eq(true)
+ end
+
+ it "returns false when the user holds none of the permissions" do
+ expect(target_acl.user_has_any_permission?(99, %w[edit manage])).to eq(false)
+ end
+
+ it "returns false for a user not present in the list" do
+ expect(target_acl.user_has_any_permission?(123_456, %w[view manage])).to eq(false)
+ end
+ end
+
+ describe "#permission_user_ids" do
+ it "returns all user ids holding the permission" do
+ expect(target_acl.permission_user_ids("view")).to contain_exactly(99)
+ end
+
+ it "returns only the matching users for a more restrictive permission" do
+ expect(target_acl.permission_user_ids("manage")).to contain_exactly(user.id)
+ end
+
+ it "returns an empty array when only non-user entries hold the permission" do
+ expect(target_acl.permission_user_ids("edit")).to eq([])
+ end
+
+ it "returns an empty array for a permission that is not present" do
+ expect(target_acl.permission_user_ids("own")).to eq([])
+ end
+ end
+
+ describe "#user_ids_with_any_permission" do
+ it "returns the unique user ids across all the permissions" do
+ expect(target_acl.user_ids_with_any_permission(%w[view manage])).to contain_exactly(
+ user.id,
+ 99,
+ )
+ end
+
+ it "ignores permissions that are not present" do
+ expect(target_acl.user_ids_with_any_permission(%w[view own])).to contain_exactly(99)
+ end
+ end
end
diff --git a/spec/lib/acl/user_spec.rb b/spec/lib/acl/user_spec.rb
index 6735c340521..ba7e3ea3b25 100644
--- a/spec/lib/acl/user_spec.rb
+++ b/spec/lib/acl/user_spec.rb
@@ -8,8 +8,6 @@ RSpec.describe Acl::User do
fab!(:other_topic, :topic)
- # The flattened permissions a single user has across multiple targets: view +
- # edit on a Category, and view on a Topic.
let(:flattened_acl_list) do
[
{ type: :group, id: 10, permission: "view", target_type: "Category", target_id: category.id },
@@ -71,6 +69,12 @@ RSpec.describe Acl::User do
it "returns an empty array when the class has no entry for the permission" do
expect(user_acl.target_ids_with_permission(Topic, "edit")).to eq([])
end
+
+ it "returns a defensive copy" do
+ user_acl.target_ids_with_permission(Category, "view").clear
+
+ expect(user_acl.target_ids_with_permission(Category, "view")).to contain_exactly(category.id)
+ end
end
describe "#target_ids_with_any_permissions" do
@@ -85,5 +89,13 @@ RSpec.describe Acl::User do
topic.id,
)
end
+
+ it "returns a defensive copy" do
+ user_acl.target_ids_with_any_permissions(Category, %w[view edit]).clear
+
+ expect(user_acl.target_ids_with_any_permissions(Category, %w[view edit])).to contain_exactly(
+ category.id,
+ )
+ end
end
end
diff --git a/spec/models/access_control_list_spec.rb b/spec/models/access_control_list_spec.rb
index e65058aae12..a57e389c37f 100644
--- a/spec/models/access_control_list_spec.rb
+++ b/spec/models/access_control_list_spec.rb
@@ -4,6 +4,8 @@ RSpec.describe AccessControlList do
fab!(:target, :category)
fab!(:group) { Fabricate(:group, name: "marketing", full_name: "Marketing Team") }
fab!(:other_group) { Fabricate(:group, name: "support", full_name: "Support Team") }
+ fab!(:user) { Fabricate(:user, name: "User One") }
+ fab!(:other_user) { Fabricate(:user, name: "User Two") }
describe ".expand_list_for_bulk_insert" do
it "collapses multiple groups sharing a permission into one record" do
@@ -19,6 +21,7 @@ RSpec.describe AccessControlList do
expect(entry).to match(
permission: "view",
allowed_group_ids: contain_exactly(group.id, other_group.id),
+ allowed_user_ids: [],
target_type: "Category",
target_id: target.id,
owner: "core",
@@ -48,10 +51,31 @@ RSpec.describe AccessControlList do
expect(result.first[:owner]).to eq("chat")
end
+ it "collapses users and groups sharing a permission into one record" do
+ list = [
+ { type: "group", id: group.id, permission: "view" },
+ { type: "user", id: user.id, permission: "view" },
+ { type: :user, id: other_user.id, permission: "view" },
+ ]
+
+ result = described_class.expand_list_for_bulk_insert(list, target, "core")
+
+ expect(result).to contain_exactly(
+ {
+ permission: "view",
+ allowed_group_ids: contain_exactly(group.id),
+ allowed_user_ids: contain_exactly(user.id, other_user.id),
+ target_type: "Category",
+ target_id: target.id,
+ owner: "core",
+ },
+ )
+ end
+
it "returns records that insert_all! can persist as valid acls" do
list = [
{ type: "group", id: group.id, permission: "view" },
- { type: "group", id: other_group.id, permission: "edit" },
+ { type: "user", id: user.id, permission: "edit" },
]
described_class.insert_all!(described_class.expand_list_for_bulk_insert(list, target, "core"))
@@ -59,7 +83,7 @@ RSpec.describe AccessControlList do
acls = described_class.where(target: target)
expect(acls.pluck(:permission)).to contain_exactly("view", "edit")
expect(acls.find_by(permission: "view").allowed_group_ids).to contain_exactly(group.id)
- expect(acls.find_by(permission: "edit").allowed_group_ids).to contain_exactly(other_group.id)
+ expect(acls.find_by(permission: "edit").allowed_user_ids).to contain_exactly(user.id)
end
end
@@ -156,6 +180,39 @@ RSpec.describe AccessControlList do
expect(entry[:metadata]).to eq({ auto_group: true })
end
+ it "returns one entry per user per acl with the user display name" do
+ Fabricate(
+ :access_control_list_with_users,
+ target: target,
+ permission: "manage",
+ users: [user, other_user],
+ )
+
+ list = described_class.where(target: target, permission: "manage").flattened_list
+
+ expect(list).to contain_exactly(
+ include(
+ type: :user,
+ id: user.id,
+ permission: "manage",
+ display_name: user.display_name,
+ mandatory: false,
+ target_type: "Category",
+ target_id: target.id,
+ ),
+ include(
+ type: :user,
+ id: other_user.id,
+ permission: "manage",
+ display_name: other_user.display_name,
+ mandatory: false,
+ target_type: "Category",
+ target_id: target.id,
+ ),
+ )
+ expect(list).to all(exclude(:metadata))
+ end
+
it "marks mandatory acl entries" do
target
.class
@@ -208,6 +265,14 @@ RSpec.describe AccessControlList do
expect(loaded.allowed_groups_preloaded.map(&:id)).to contain_exactly(group.id, other_group.id)
end
+ it "populates allowed_users_preloaded from allowed_user_ids" do
+ acl = Fabricate(:access_control_list_with_users, users: [user, other_user])
+
+ loaded = described_class.where(id: acl.id).preload_allowed.first
+
+ expect(loaded.allowed_users_preloaded.map(&:id)).to contain_exactly(user.id, other_user.id)
+ end
+
it "loads the allowed groups for the whole relation without an N+1" do
one = Fabricate(:access_control_list_with_groups, groups: [group])
@@ -234,6 +299,27 @@ RSpec.describe AccessControlList do
end
end
+ describe ".matching_group" do
+ fab!(:member_user, :user)
+ fab!(:member_group) { Fabricate(:group).tap { |new_group| new_group.add(member_user) } }
+ fab!(:non_member_user, :user)
+ fab!(:group_acl) { Fabricate(:access_control_list_with_groups, groups: [member_group]) }
+ fab!(:direct_user_acl) { Fabricate(:access_control_list_with_users, users: [member_user]) }
+ fab!(:other_user_acl) { Fabricate(:access_control_list_with_users, users: [non_member_user]) }
+
+ it "matches acls allowing the group directly" do
+ expect(described_class.matching_group(member_group)).to include(group_acl)
+ end
+
+ it "matches acls allowing users in the group" do
+ expect(described_class.matching_group(member_group)).to include(direct_user_acl)
+ end
+
+ it "does not match acls for users outside the group" do
+ expect(described_class.matching_group(member_group)).not_to include(other_user_acl)
+ end
+ end
+
describe ".matching_user" do
fab!(:user)
fab!(:member_group) { Fabricate(:group).tap { |new_group| new_group.add(user) } }
diff --git a/spec/requests/access_control_lists_controller_spec.rb b/spec/requests/access_control_lists_controller_spec.rb
new file mode 100644
index 00000000000..248fab96f42
--- /dev/null
+++ b/spec/requests/access_control_lists_controller_spec.rb
@@ -0,0 +1,52 @@
+# frozen_string_literal: true
+
+RSpec.describe AccessControlListsController do
+ fab!(:current_user, :user)
+
+ describe "#search_grantees" do
+ before { sign_in(current_user) }
+
+ it "returns matching users and groups", :aggregate_failures do
+ user = Fabricate(:user, username: "acl_search_user")
+ group = Fabricate(:group, name: "acl_search_group", full_name: "ACL search group")
+
+ get "/access-control/grantees/search.json", params: { term: "acl_search" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["users"].map { |result| result["id"] }).to contain_exactly(
+ user.id,
+ )
+ expect(response.parsed_body["groups"]).to contain_exactly(
+ {
+ "id" => group.id,
+ "name" => group.name,
+ "full_name" => group.full_name,
+ "display_name" => group.full_name,
+ "automatic" => false,
+ },
+ )
+ end
+
+ it "returns no results for a blank term", :aggregate_failures do
+ get "/access-control/grantees/search.json", params: { term: "" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body).to eq({ "users" => [], "groups" => [] })
+ end
+
+ include_examples "invalid limit params",
+ "/access-control/grantees/search.json",
+ described_class::SEARCH_GRANTEES_LIMIT,
+ params: {
+ term: "acl_search",
+ }
+ end
+
+ context "when logged out" do
+ it "requires login" do
+ get "/access-control/grantees/search.json", params: { term: "acl_search" }
+
+ expect(response.status).to eq(403)
+ end
+ end
+end
diff --git a/spec/requests/api/schemas/json/site_response.json b/spec/requests/api/schemas/json/site_response.json
index 0af5d19473d..940ec01adcf 100644
--- a/spec/requests/api/schemas/json/site_response.json
+++ b/spec/requests/api/schemas/json/site_response.json
@@ -288,6 +288,9 @@
"full_name": {
"type": "string"
},
+ "display_name": {
+ "type": "string"
+ },
"flair_url": {
"type": [
"string",
diff --git a/spec/services/access_control_list/search_grantees_spec.rb b/spec/services/access_control_list/search_grantees_spec.rb
new file mode 100644
index 00000000000..4d3b7f59158
--- /dev/null
+++ b/spec/services/access_control_list/search_grantees_spec.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+RSpec.describe AccessControlList::SearchGrantees do
+ describe described_class::Contract, type: :model do
+ it { is_expected.to validate_presence_of(:limit) }
+
+ it "validates the limit range" do
+ expect(described_class.new(limit: 1)).to be_valid
+ expect(described_class.new(limit: 0)).not_to be_valid
+ expect(
+ described_class.new(limit: AccessControlList::SearchGrantees::MAX_RESULTS + 1),
+ ).not_to be_valid
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies) }
+
+ fab!(:current_user, :user)
+
+ let(:params) { { term:, limit: } }
+ let(:dependencies) { { guardian: } }
+ let(:guardian) { current_user.guardian }
+ let(:term) { "acl_search" }
+ let(:limit) { described_class::MAX_RESULTS }
+
+ context "when the contract is invalid" do
+ let(:limit) { 0 }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when the search term is blank" do
+ let(:term) { " " }
+
+ it { is_expected.to run_successfully }
+
+ it "returns empty grantee collections" do
+ expect(result.users).to eq([])
+ expect(result.groups).to eq([])
+ end
+ end
+
+ context "when matching grantees exist" do
+ fab!(:matching_user) { Fabricate(:user, username: "acl_search_user") }
+ fab!(:matching_group) do
+ Fabricate(:group, name: "acl_search_group", full_name: "ACL search group")
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "returns matching users and groups" do
+ expect(result.users.map(&:id)).to contain_exactly(matching_user.id)
+ expect(result.groups.map(&:id)).to contain_exactly(matching_group.id)
+ end
+ end
+ end
+end