A platform for community discussion. Free, open, simple.
FEATURE: Allow admins to remove users from chat DMs (#31366)
Ted Johanssonb5147a4634f0
diff --git a/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb b/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rbindex 3224a7abb7f..e33a0cc42b4 100644--- a/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb+++ b/plugins/chat/app/controllers/chat/api/channels_memberships_controller.rb@@ -44,4 +44,19 @@ class Chat::Api::ChannelsMembershipsController < Chat::Api::ChannelsControllerendendend++ def destroy+ Chat::RemoveUserFromChannel.call(service_params) do+ on_success { render(json: success_json) }+ on_failure { render(json: failed_json, status: 422) }+ on_model_not_found(:channel) { raise Discourse::NotFound }+ on_model_not_found(:target_user) { raise Discourse::NotFound }+ on_failed_policy(:can_remove_users_from_channel) do+ render_json_error(I18n.t("chat.errors.user_cant_be_removed_from_channel"), status: 403)+ end+ on_failed_contract do |contract|+ render(json: failed_json.merge(errors: contract.errors.full_messages), status: 400)+ end+ end+ endenddiff --git a/plugins/chat/app/models/chat/channel.rb b/plugins/chat/app/models/chat/channel.rbindex 29fc80979c6..8133eade078 100644--- a/plugins/chat/app/models/chat/channel.rb+++ b/plugins/chat/app/models/chat/channel.rb@@ -105,6 +105,7 @@ module Chat%i[category_channel?direct_message_channel?+ direct_message_group?public_channel?chatable_has_custom_fields?read_restricted?diff --git a/plugins/chat/app/models/chat/direct_message_channel.rb b/plugins/chat/app/models/chat/direct_message_channel.rbindex b179c96f90c..f8bc4627533 100644--- a/plugins/chat/app/models/chat/direct_message_channel.rb+++ b/plugins/chat/app/models/chat/direct_message_channel.rb@@ -28,12 +28,13 @@ module Chatself.slug.blank?end- def leave(user)+ def remove(user)return super unless direct_message_group?transaction domembership_for(user)&.destroy!direct_message.users.delete(user)endend+ alias leave removeendenddiff --git a/plugins/chat/app/serializers/chat/channel_serializer.rb b/plugins/chat/app/serializers/chat/channel_serializer.rbindex 9e8b6c8d399..7a8c2e37c9d 100644--- a/plugins/chat/app/serializers/chat/channel_serializer.rb+++ b/plugins/chat/app/serializers/chat/channel_serializer.rb@@ -139,6 +139,7 @@ module Chatdata[:can_moderate] = scope.can_moderate_chat?(object.chatable)data[:can_delete_self] = scope.can_delete_own_chats?(object.chatable)data[:can_delete_others] = scope.can_delete_other_chats?(object.chatable)+ data[:can_remove_members] = scope.can_remove_members?(object)dataenddiff --git a/plugins/chat/app/services/chat/remove_user_from_channel.rb b/plugins/chat/app/services/chat/remove_user_from_channel.rbnew file mode 100644index 00000000000..3a2146a8948--- /dev/null+++ b/plugins/chat/app/services/chat/remove_user_from_channel.rb@@ -0,0 +1,70 @@+# frozen_string_literal: true++module Chat+ # Service responsible for removing users from a channel.+ # The guardian passed in is the "acting user" when removing users.+ # The service is essentially deleting memberships for the users.+ #+ # @example+ # ::Chat::RemoveUserFromChannel.call(+ # guardian: guardian,+ # params: {+ # channel_id: 1,+ # user_id: 9,+ # }+ # )+ #+ class RemoveUserFromChannel+ include Service::Base++ # @!method self.call(guardian:, params:)+ # @param [Guardian] guardian+ # @param [Hash] params+ # @option params [Integer] :channel_id ID of the channel+ # @option params [Integer] :user_id+ # @return [Service::Base::Context]++ params do+ attribute :user_id, :integer+ attribute :channel_id, :integer++ validates :user_id, presence: true+ validates :channel_id, presence: true+ end++ model :channel+ model :target_user++ policy :can_remove_users_from_channel++ transaction do+ step :remove+ step :recompute_users_count+ end++ private++ def fetch_channel(params:)+ ::Chat::Channel.includes(:chatable).find_by(id: params.channel_id)+ end++ def fetch_target_user(params:)+ User.find_by(id: params.user_id)+ end++ def can_remove_users_from_channel(guardian:, channel:)+ guardian.can_remove_members?(channel)+ end++ def remove(channel:, target_user:)+ channel.remove(target_user)+ end++ def recompute_users_count(channel:)+ channel.update!(+ user_count: ::Chat::ChannelMembershipsQuery.count(channel),+ user_count_stale: false,+ )+ end+ end+enddiff --git a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel-info-members.gjs b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel-info-members.gjsindex 1543d4b8100..dc99b4e2b1e 100644--- a/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel-info-members.gjs+++ b/plugins/chat/assets/javascripts/discourse/components/chat/routes/channel-info-members.gjs@@ -6,9 +6,11 @@ import { action } from "@ember/object";import { LinkTo } from "@ember/routing";import { service } from "@ember/service";import { modifier } from "ember-modifier";+import DButton from "discourse/components/d-button";import FilterInput from "discourse/components/filter-input";import icon from "discourse/helpers/d-icon";import discourseDebounce from "discourse/lib/debounce";+import { bind } from "discourse/lib/decorators";import { INPUT_DELAY } from "discourse/lib/environment";import isElementInViewport from "discourse/lib/is-element-in-viewport";import DiscourseURL, { userPath } from "discourse/lib/url";@@ -21,11 +23,13 @@ import ChatUserInfo from "discourse/plugins/chat/discourse/components/chat-user-export default class ChatRouteChannelInfoMembers extends Component {@service appEvents;@service chatApi;+ @service currentUser;@service modal;@service loadingSlider;@service site;@tracked filter = "";+ @tracked updatedAt = Date.now();@tracked showAddMembers = false;addMemberLabel = i18n("chat.members_view.add_member");@@ -82,6 +86,7 @@ export default class ChatRouteChannelInfoMembers extends Component {if (this.filter?.length) {params.username = this.filter;}+ this.updatedAt;return this.chatApi.listChannelMemberships(this.args.channel.id, params);}@@ -113,6 +118,20 @@ export default class ChatRouteChannelInfoMembers extends Component {DiscourseURL.routeTo(userPath(user.username_lower));}+ @action+ async removeMember(user) {+ await this.chatApi.removeMemberFromChannel(this.args.channel.id, user.id);+ this.updatedAt = Date.now();+ this.load();+ }++ @bind+ canRemoveMember(user) {+ return (+ this.args.channel.canRemoveMembers && user.id !== this.currentUser.id+ );+ }+async debouncedLoad() {this.loadingSlider.transitionStarted();await this.members.load({ limit: 20 });@@ -166,19 +185,28 @@ export default class ChatRouteChannelInfoMembers extends Component {</li>{{/if}}{{#each this.members as |membership|}}- <li- class="c-channel-members__list-item -member"- {{on "click" (fn this.openMemberCard membership.user)}}- {{this.onEnter (fn this.openMemberCard membership.user)}}- tabindex="0"- >- <ChatUserInfo- @user={{membership.user}}- @avatarSize="tiny"- @interactive={{false}}- @showStatus={{true}}- @showStatusDescription={{true}}- />+ <li class="c-channel-members__list-item -member" tabindex="0">+ <div+ class="c-channel-members__list-item -user-info"+ role="button"+ {{on "click" (fn this.openMemberCard membership.user)}}+ {{this.onEnter (fn this.openMemberCard membership.user)}}+ >+ <ChatUserInfo+ @user={{membership.user}}+ @avatarSize="tiny"+ @interactive={{false}}+ @showStatus={{true}}+ @showStatusDescription={{true}}+ />+ </div>+ {{#if (this.canRemoveMember membership.user)}}+ <DButton+ @action={{fn this.removeMember membership.user}}+ @label="chat.channel_info.remove_member"+ class="btn-flat -remove-member"+ />+ {{/if}}</li>{{else}}{{#if this.noResults}}diff --git a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js b/plugins/chat/assets/javascripts/discourse/models/chat-channel.jsindex 462d5a8e1ed..524168ce775 100644--- a/plugins/chat/assets/javascripts/discourse/models/chat-channel.js+++ b/plugins/chat/assets/javascripts/discourse/models/chat-channel.js@@ -160,6 +160,10 @@ export default class ChatChannel {return this.meta.can_moderate;}+ get canRemoveMembers() {+ return this.meta.can_remove_members;+ }+get escapedTitle() {return escapeExpression(this.title);}diff --git a/plugins/chat/assets/javascripts/discourse/services/chat-api.js b/plugins/chat/assets/javascripts/discourse/services/chat-api.jsindex 7b66576754e..574878a9e02 100644--- a/plugins/chat/assets/javascripts/discourse/services/chat-api.js+++ b/plugins/chat/assets/javascripts/discourse/services/chat-api.js@@ -607,6 +607,16 @@ export default class ChatApi extends Service {});}+ /**+ * Remove member from a channel.+ *+ * @param {number} channelId - The ID of the channel.+ * @param {string} userId - The ID of the user to remove.+ */+ removeMemberFromChannel(channelId, userId) {+ return this.#deleteRequest(`/channels/${channelId}/memberships/${userId}`);+ }+get #basePath() {return "/chat/api";}diff --git a/plugins/chat/assets/stylesheets/common/chat-channel-members.scss b/plugins/chat/assets/stylesheets/common/chat-channel-members.scssindex c02abd9cd11..610d79f9c96 100644--- a/plugins/chat/assets/stylesheets/common/chat-channel-members.scss+++ b/plugins/chat/assets/stylesheets/common/chat-channel-members.scss@@ -20,6 +20,12 @@padding: 0.5rem;cursor: pointer;+ .-user-info {+ border: 0 none;+ display: flex;+ flex-grow: 1;+ }+.avatar {cursor: pointer;}@@ -57,6 +63,10 @@width: var(--font-0);}}++ .btn {+ margin-left: auto;+ }}&.-add-member {diff --git a/plugins/chat/config/locales/client.en.yml b/plugins/chat/config/locales/client.en.ymlindex 34ddfbd1e58..0355253e3f5 100644--- a/plugins/chat/config/locales/client.en.yml+++ b/plugins/chat/config/locales/client.en.yml@@ -348,6 +348,7 @@ en:tabs:members: Memberssettings: Settings+ remove_member: "Remove"new_message_modal:title: Send messagediff --git a/plugins/chat/config/locales/server.en.yml b/plugins/chat/config/locales/server.en.ymlindex 40969c44213..0691033ba22 100644--- a/plugins/chat/config/locales/server.en.yml+++ b/plugins/chat/config/locales/server.en.yml@@ -54,6 +54,7 @@ en:deleted_chat_username: deletederrors:users_cant_be_added_to_channel: "Users can't be added to this channel."+ user_cant_be_removed_from_channel: "User can't be removed from this channel"channel_exists_for_category: "A channel already exists for this category and name"channel_new_message_disallowed:archived: "The channel is archived, no new messages can be sent"diff --git a/plugins/chat/config/routes.rb b/plugins/chat/config/routes.rbindex 56037280fdb..50347b569cc 100644--- a/plugins/chat/config/routes.rb+++ b/plugins/chat/config/routes.rb@@ -27,6 +27,7 @@ Chat::Engine.routes.draw doget "/channels/:channel_id/memberships" => "channels_memberships#index"post "/channels/:channel_id/memberships" => "channels_memberships#create"delete "/channels/:channel_id/memberships/me" => "channels_current_user_membership#destroy"+ delete "/channels/:channel_id/memberships/:user_id" => "channels_memberships#destroy"delete "/channels/:channel_id/memberships/me/follows" =>"channels_current_user_membership_follows#destroy"put "/channels/:channel_id/memberships/me" => "channels_current_user_membership#update"diff --git a/plugins/chat/lib/chat/guardian_extensions.rb b/plugins/chat/lib/chat/guardian_extensions.rbindex 675d8681544..78d6ccc55e0 100644--- a/plugins/chat/lib/chat/guardian_extensions.rb+++ b/plugins/chat/lib/chat/guardian_extensions.rb@@ -254,5 +254,9 @@ module Chatdef can_delete_category?(category)super && category.deletable_for_chat?end++ def can_remove_members?(channel)+ is_admin? && (channel.category_channel? || channel.direct_message_group?)+ endendenddiff --git a/plugins/chat/spec/requests/chat/api/channels_memberships_controller_spec.rb b/plugins/chat/spec/requests/chat/api/channels_memberships_controller_spec.rbindex f4f30ec3f13..6df333c46ef 100644--- a/plugins/chat/spec/requests/chat/api/channels_memberships_controller_spec.rb+++ b/plugins/chat/spec/requests/chat/api/channels_memberships_controller_spec.rb@@ -2,14 +2,16 @@RSpec.describe Chat::Api::ChannelsMembershipsController dofab!(:current_user) { Fabricate(:user) }+ fab!(:other_user) { Fabricate(:user) }fab!(:channel_1) do- Fabricate(:direct_message_channel, group: true, users: [current_user, Fabricate(:user)])+ Fabricate(:direct_message_channel, group: true, users: [current_user, other_user])endbefore doSiteSetting.chat_enabled = trueSiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]channel_1.add(current_user)+ channel_1.add(other_user)sign_in(current_user)end@@ -52,4 +54,42 @@ RSpec.describe Chat::Api::ChannelsMembershipsController doendendend++ describe "#destroy" do+ context "when acting user is an admin" do+ let(:current_user) { Fabricate(:admin) }++ describe "success" do+ it "works" do+ delete "/chat/api/channels/#{channel_1.id}/memberships/#{other_user.id}"++ expect(response.status).to eq(200)+ end+ end++ context "when channel is not found" do+ it "returns a 404" do+ delete "/chat/api/channels/-999/memberships/#{other_user.id}"++ expect(response.status).to eq(404)+ end+ end++ context "when target user is not found" do+ it "returns a 404" do+ delete "/chat/api/channels/#{channel_1.id}/memberships/31337"++ expect(response.status).to eq(404)+ end+ end+ end++ context "when acting user is not an admin" do+ it "returns a 403" do+ delete "/chat/api/channels/#{channel_1.id}/memberships/#{other_user.id}"++ expect(response.status).to eq(403)+ end+ end+ endenddiff --git a/plugins/chat/spec/services/chat/remove_user_from_channel_spec.rb b/plugins/chat/spec/services/chat/remove_user_from_channel_spec.rbnew file mode 100644index 00000000000..f52e236aa06--- /dev/null+++ b/plugins/chat/spec/services/chat/remove_user_from_channel_spec.rb@@ -0,0 +1,119 @@+# frozen_string_literal: true++RSpec.describe Chat::RemoveUserFromChannel do+ describe described_class::Contract, type: :model do+ it { is_expected.to validate_presence_of :channel_id }+ it { is_expected.to validate_presence_of :user_id }+ end++ describe ".call" do+ subject(:result) { described_class.call(params:, **dependencies) }++ fab!(:acting_user) { Fabricate(:admin) }+ fab!(:user)+ fab!(:channel) { Fabricate(:chat_channel) }++ let(:guardian) { Guardian.new(acting_user) }+ let(:params) { { channel_id: channel.id, user_id: user.id } }+ let(:dependencies) { { guardian: } }++ context "when all steps pass" do+ context "when category channel" do+ context "with existing membership" do+ before do+ channel.add(user)+ channel.add(acting_user)+ Chat::Channel.ensure_consistency!+ end++ it { is_expected.to run_successfully }++ it "unfollows the channel" do+ membership = channel.membership_for(user)++ expect { result }.to change { membership.reload.following }.from(true).to(false)+ end++ it "recomputes user count" do+ expect { result }.to change { channel.reload.user_count }.from(2).to(1)+ end+ end++ context "with no existing membership" do+ it { is_expected.to run_successfully }++ it "does nothing" do+ expect { result }.to_not change { Chat::UserChatChannelMembership.count }+ end+ end+ end++ context "when group channel" do+ context "with existing membership" do+ fab!(:channel) do+ Fabricate(:direct_message_channel, group: true, users: [acting_user, user])+ end++ before { Chat::Channel.ensure_consistency! }++ it { is_expected.to run_successfully }++ it "leaves the channel" do+ membership = channel.membership_for(user)++ result++ expect(Chat::UserChatChannelMembership.exists?(membership.id)).to eq(false)+ expect(channel.chatable.direct_message_users.where(user_id: user.id).exists?).to eq(+ false,+ )+ end++ it "recomputes user count" do+ expect { result }.to change { channel.reload.user_count }.from(2).to(1)+ end+ end++ context "with no existing membership" do+ it { is_expected.to run_successfully }++ it "does nothing" do+ expect { result }.to_not change { Chat::UserChatChannelMembership.count }+ end+ end+ end++ context "when channel is a one-on-one DM" do+ context "with existing membership" do+ fab!(:channel) { Fabricate(:direct_message_channel, users: [acting_user, user]) }++ it { is_expected.to fail_a_policy(:can_remove_users_from_channel) }+ end+ end+ end++ context "when target user is not found" do+ before do+ params[:user_id] = 31_337+ params[:channel_id] = channel.id+ end++ it { is_expected.to fail_to_find_a_model(:target_user) }+ end++ context "when channel is not found" do+ before do+ params[:user_id] = user.id+ params[:channel_id] = -999+ end++ it { is_expected.to fail_to_find_a_model(:channel) }+ end++ context "when user is not an admin" do+ fab!(:acting_user) { Fabricate(:user) }++ it { is_expected.to fail_a_policy(:can_remove_users_from_channel) }+ end+ end+enddiff --git a/plugins/chat/spec/system/channel_members_page_spec.rb b/plugins/chat/spec/system/channel_members_page_spec.rbindex ef0fb6290b2..b593bb1d97b 100644--- a/plugins/chat/spec/system/channel_members_page_spec.rb+++ b/plugins/chat/spec/system/channel_members_page_spec.rb@@ -61,7 +61,11 @@ RSpec.describe "Channel - Info - Members page", type: :system dochat_page.visit_channel_members(channel_1)find(".c-channel-members__filter").fill_in(with: "cat")- expect(page).to have_selector(".c-channel-members__list-item", count: 1, text: "cat")+ expect(page).to have_selector(+ ".c-channel-members__list-item .-user-info",+ count: 1,+ text: "cat",+ )endend@@ -88,7 +92,7 @@ RSpec.describe "Channel - Info - Members page", type: :system doendend- context "when category channel" do+ context "when group DM channel" dofab!(:channel_1) doFabricate(:direct_message_channel,@@ -118,6 +122,54 @@ RSpec.describe "Channel - Info - Members page", type: :system doendend+ describe "removing members" do+ fab!(:current_user) { Fabricate(:admin) }++ before { channel_1.add(Fabricate(:user)) }++ context "when the channel is a category channel" do+ it "allows removing members" do+ chat_page.visit_channel_members(channel_1)++ expect(chat_page).to have_css(".c-channel-members__list-item .-remove-member")+ end+ end++ context "when the channel is a group DM" do+ fab!(:channel_1) do+ Fabricate(+ :direct_message_channel,+ slug: "test-channel",+ users: [current_user, Fabricate(:user), Fabricate(:user)],+ group: true,+ )+ end++ it "allows removing members" do+ chat_page.visit_channel_members(channel_1)++ expect(chat_page).to have_css(".c-channel-members__list-item .-remove-member")+ end+ end++ context "when the channel is a one-on-one DM" do+ fab!(:channel_1) do+ Fabricate(+ :direct_message_channel,+ slug: "test-channel",+ users: [current_user, Fabricate(:user)],+ group: false,+ )+ end++ it "does not allow removing members" do+ chat_page.visit_channel_members(channel_1)++ expect(chat_page).to have_no_css(".c-channel-members__list-item .-remove-member")+ end+ end+ end+context "when on mobile", mobile: true doit "has a link to the settings" dochat_page.visit_channel_members(channel_1)