A platform for community discussion. Free, open, simple.
FIX: Warn moderators before group changes that would lock them out (#36811)
Régis Hanole464ee9296be
diff --git a/config/locales/client.en.yml b/config/locales/client.en.ymlindex db245895571..4b748e060bb 100644--- a/config/locales/client.en.yml+++ b/config/locales/client.en.yml@@ -1152,6 +1152,7 @@ en:title: Interactionposting: Postingnotification: Notification+ self_lockout: "You are about to change group visibility in a way that will remove your own access. Are you sure you want to proceed?"email:title: "Email"status: "Synchronized %{old_emails} / %{total_emails} emails via IMAP."@@ -1298,6 +1299,8 @@ en:make_owner_description: "Make <b>%{username}</b> an owner of this group"remove_owner: "Remove as Owner"remove_owner_description: "Remove <b>%{username}</b> as an owner of this group"+ remove_member_self_lockout: "Removing yourself from this group will revoke your access to manage it. Are you sure you want to proceed?"+ remove_owner_self_lockout: "Removing yourself as owner will revoke your access to manage this group. Are you sure you want to proceed?"make_primary: "Make Primary"make_primary_description: "Make this the primary group for <b>%{username}</b>"remove_primary: "Remove as Primary"diff --git a/frontend/discourse/admin/controllers/edit-category/tabs.js b/frontend/discourse/admin/controllers/edit-category/tabs.jsindex c8c59f82430..5a853c4dce2 100644--- a/frontend/discourse/admin/controllers/edit-category/tabs.js+++ b/frontend/discourse/admin/controllers/edit-category/tabs.js@@ -9,6 +9,7 @@ import { AUTO_GROUPS } from "discourse/lib/constants";import discourseComputed from "discourse/lib/decorators";import { trackedArray } from "discourse/lib/tracked-tools";import DiscourseURL from "discourse/lib/url";+import { defaultHomepage } from "discourse/lib/utilities";import Category from "discourse/models/category";import { i18n } from "discourse-i18n";@@ -131,56 +132,55 @@ export default class EditCategoryTabsController extends Controller {}@action- saveCategory(data) {+ async saveCategory(data) {if (this.validators.some((validator) => validator())) {return;}this.model.setProperties(data);- if (this._wouldLoseAccess()) {- this.dialog.yesNoConfirm({+ const lostAccess = this._wouldLoseAccess();++ if (lostAccess) {+ const confirmed = await this.dialog.yesNoConfirm({message: i18n("category.errors.self_lockout"),- didConfirm: () => this._performSave({ lostAccess: true }),});- return;- }- this._performSave();- }+ if (!confirmed) {+ return;+ }+ }- _performSave({ lostAccess } = {}) {this.set("saving", true);- this.model- .save()- .then((result) => {- const updatedModel = this.site.updateCategory(result.category);- updatedModel.setupGroupsAndPermissions();-- if (lostAccess) {- DiscourseURL.routeTo("/");- return;- }-- if (!this.model.id) {- this.router.transitionTo(- "editCategory",- Category.slugFor(updatedModel)- );- }- // ensure breadcrumbs contain the updated category model- this.breadcrumbCategories = this.site.categoriesList.map((c) =>- c.id === this.model.id ? updatedModel : c+ try {+ const result = await this.model.save();+ const updatedModel = this.site.updateCategory(result.category);+ updatedModel.setupGroupsAndPermissions();++ if (lostAccess) {+ this.router.transitionTo(`discovery.${defaultHomepage()}`);+ return;+ }++ this.set("saving", false);++ if (!this.model.id) {+ this.router.transitionTo(+ "editCategory",+ Category.slugFor(updatedModel));- })- .catch((error) => {- popupAjaxError(error);- this.model.set("parent_category_id", undefined);- })- .finally(() => {- this.set("saving", false);- });+ }++ // ensure breadcrumbs contain the updated category model+ this.breadcrumbCategories = this.site.categoriesList.map((c) =>+ c.id === this.model.id ? updatedModel : c+ );+ } catch (error) {+ this.set("saving", false);+ popupAjaxError(error);+ this.model.set("parent_category_id", undefined);+ }}@actiondiff --git a/frontend/discourse/app/components/group-manage-save-button.gjs b/frontend/discourse/app/components/group-manage-save-button.gjsindex 5e488ecc7d6..ffee5c1446b 100644--- a/frontend/discourse/app/components/group-manage-save-button.gjs+++ b/frontend/discourse/app/components/group-manage-save-button.gjs@@ -6,12 +6,17 @@ import DButton from "discourse/components/d-button";import GroupFlairVisibilityWarning from "discourse/components/group-flair-visibility-warning";import GroupDefaultNotificationsModal from "discourse/components/modal/group-default-notifications";import { popupAjaxError } from "discourse/lib/ajax-error";+import { GROUP_VISIBILITY_LEVELS } from "discourse/lib/constants";import discourseComputed from "discourse/lib/decorators";+import { defaultHomepage } from "discourse/lib/utilities";import { or } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";export default class GroupManageSaveButton extends Component {+ @service currentUser;+ @service dialog;@service modal;+ @service router;@service groupAutomaticMembersDialog;saving = null;@@ -28,13 +33,41 @@ export default class GroupManageSaveButton extends Component {this.updateExistingUsers = value;}+ _wouldLoseAccess() {+ if (this.currentUser.admin) {+ return false;+ }++ const group = this.model;++ if (+ group.visibility_level === GROUP_VISIBILITY_LEVELS.owners ||+ group.members_visibility_level === GROUP_VISIBILITY_LEVELS.owners+ ) {+ return !group.is_group_owner_display;+ }++ return false;+ }+@actionasync save() {if (this.beforeSave) {this.beforeSave();}- this.set("saving", true);+ const lostAccess = this._wouldLoseAccess();++ if (lostAccess) {+ const confirmed = await this.dialog.yesNoConfirm({+ message: i18n("groups.manage.interaction.self_lockout"),+ });++ if (!confirmed) {+ return;+ }+ }+const group = this.model;const accepted = await this.groupAutomaticMembersDialog.showConfirm(@@ -43,36 +76,42 @@ export default class GroupManageSaveButton extends Component {);if (!accepted) {- this.set("saving", false);return;}+ this.set("saving", true);+const opts = {};if (this.updateExistingUsers !== null) {opts.update_existing_users = this.updateExistingUsers;}- return group- .save(opts)- .then(() => {- this.setProperties({- saved: true,- updateExistingUsers: null,- });-- if (this.afterSave) {- this.afterSave();- }- })- .catch((error) => {- const json = error.jqXHR.responseJSON;- if (error.jqXHR.status === 422 && json.user_count) {- this.editGroupNotifications(json);- } else {- popupAjaxError(error);- }- })- .finally(() => this.set("saving", false));+ try {+ await group.save(opts);++ if (lostAccess) {+ this.router.transitionTo(`discovery.${defaultHomepage()}`);+ return;+ }++ this.setProperties({+ saved: true,+ updateExistingUsers: null,+ });++ if (this.afterSave) {+ this.afterSave();+ }+ } catch (error) {+ const json = error.jqXHR?.responseJSON;+ if (error.jqXHR?.status === 422 && json?.user_count) {+ this.editGroupNotifications(json);+ } else {+ popupAjaxError(error);+ }+ } finally {+ this.set("saving", false);+ }}@actiondiff --git a/frontend/discourse/app/controllers/group/index.js b/frontend/discourse/app/controllers/group/index.jsindex 142857bffcb..d4880baf7f4 100644--- a/frontend/discourse/app/controllers/group/index.js+++ b/frontend/discourse/app/controllers/group/index.js@@ -1,13 +1,19 @@import Controller from "@ember/controller";import { action } from "@ember/object";+import { service } from "@ember/service";import { observes } from "@ember-decorators/object";import { ajax } from "discourse/lib/ajax";import { popupAjaxError } from "discourse/lib/ajax-error";import { removeValueFromArray } from "discourse/lib/array-tools";+import { GROUP_VISIBILITY_LEVELS } from "discourse/lib/constants";import discourseComputed, { debounce } from "discourse/lib/decorators";import { trackedArray } from "discourse/lib/tracked-tools";+import { i18n } from "discourse-i18n";export default class GroupIndexController extends Controller {+ @service currentUser;+ @service dialog;+@trackedArray bulkSelection = null;queryParams = ["order", "asc", "filter"];@@ -178,8 +184,35 @@ export default class GroupIndexController extends Controller {}}+ _wouldLoseAccessOnRemoval(user) {+ if (this.currentUser.admin) {+ return false;+ }++ if (user.id !== this.currentUser.id) {+ return false;+ }++ const group = this.model;++ return (+ group.visibility_level === GROUP_VISIBILITY_LEVELS.owners ||+ group.members_visibility_level === GROUP_VISIBILITY_LEVELS.owners+ );+ }+@action- removeMember(user) {+ async removeMember(user) {+ if (this._wouldLoseAccessOnRemoval(user)) {+ const confirmed = await this.dialog.yesNoConfirm({+ message: i18n("groups.members.remove_member_self_lockout"),+ });++ if (!confirmed) {+ return;+ }+ }+this.model.removeMember(user, this.memberParams);}@@ -189,7 +222,17 @@ export default class GroupIndexController extends Controller {}@action- removeOwner(user) {+ async removeOwner(user) {+ if (this._wouldLoseAccessOnRemoval(user)) {+ const confirmed = await this.dialog.yesNoConfirm({+ message: i18n("groups.members.remove_owner_self_lockout"),+ });++ if (!confirmed) {+ return;+ }+ }+this.model.removeOwner(user);}diff --git a/frontend/discourse/app/lib/constants.js b/frontend/discourse/app/lib/constants.jsindex 2d9beb085f9..73ccec14c01 100644--- a/frontend/discourse/app/lib/constants.js+++ b/frontend/discourse/app/lib/constants.js@@ -75,6 +75,14 @@ export const AUTO_GROUPS = {export const GROUP_SMTP_SSL_MODES = { none: 0, ssl_tls: 1, starttls: 2 };+export const GROUP_VISIBILITY_LEVELS = {+ public: 0,+ logged_on_users: 1,+ members: 2,+ staff: 3,+ owners: 4,+};+export const MAX_AUTO_MEMBERSHIP_DOMAINS_LOOKUP = 10;export const MAX_NOTIFICATIONS_LIMIT_PARAMS = 60;diff --git a/lib/tasks/javascript.rake b/lib/tasks/javascript.rakeindex 222f5d69cda..820131f5b09 100644--- a/lib/tasks/javascript.rake+++ b/lib/tasks/javascript.rake@@ -77,6 +77,8 @@ task "javascript:update_constants" => :environment doexport const GROUP_SMTP_SSL_MODES = #{Group.smtp_ssl_modes.to_json};+ export const GROUP_VISIBILITY_LEVELS = #{Group.visibility_levels.to_json};+export const MAX_AUTO_MEMBERSHIP_DOMAINS_LOOKUP = #{Admin::GroupsController::MAX_AUTO_MEMBERSHIP_DOMAINS_LOOKUP};export const MAX_NOTIFICATIONS_LIMIT_PARAMS = #{NotificationsController::INDEX_LIMIT};diff --git a/spec/system/category_moderator_self_lockout_spec.rb b/spec/system/category_moderator_self_lockout_spec.rbindex d3b3d8b53c8..90c1abf6f5c 100644--- a/spec/system/category_moderator_self_lockout_spec.rb+++ b/spec/system/category_moderator_self_lockout_spec.rb@@ -1,6 +1,6 @@# frozen_string_literal: true-describe "Category moderator self-lockout warning", type: :system do+describe "Category moderator self-lockout warning" dofab!(:moderator)fab!(:restricted_group, :group)fab!(:category)@@ -43,7 +43,7 @@ describe "Category moderator self-lockout warning", type: :system docategory_page.save_settingsdialog.click_yes- expect(page).to have_current_path("/")+ expect(page).to have_current_path("/latest")expect(category.reload.category_groups.map(&:group_id)).to contain_exactly(restricted_group.id,)diff --git a/spec/system/group_moderator_self_lockout_spec.rb b/spec/system/group_moderator_self_lockout_spec.rbnew file mode 100644index 00000000000..d32d26b262e--- /dev/null+++ b/spec/system/group_moderator_self_lockout_spec.rb@@ -0,0 +1,132 @@+# frozen_string_literal: true++describe "Group moderator self-lockout warning" do+ fab!(:moderator)+ fab!(:group)++ let(:group_page) { PageObjects::Pages::Group.new }+ let(:dialog) { PageObjects::Components::Dialog.new }+ let(:visibility_chooser) do+ PageObjects::Components::SelectKit.new(".groups-form-visibility-level")+ end+ let(:members_visibility_chooser) do+ PageObjects::Components::SelectKit.new(".groups-form-members-visibility-level")+ end+ let(:member_dropdown) { PageObjects::Components::SelectKit.new(".group-member-dropdown") }++ before { SiteSetting.moderators_manage_groups = true }++ def visit_interaction_settings+ group_page.visit(group)+ group_page.click_manage+ page.find(".user-secondary-navigation li", text: "Interaction").click+ end++ context "when non-owner moderator changes visibility to 'Owners only'" do+ before { sign_in(moderator) }++ it "shows confirmation dialog for visibility_level change" do+ visit_interaction_settings+ visibility_chooser.expand+ visibility_chooser.select_row_by_value(Group.visibility_levels[:owners])+ group_page.click_save++ expect(dialog).to be_open+ expect(dialog).to have_content(I18n.t("js.groups.manage.interaction.self_lockout"))+ end++ it "shows confirmation dialog for members_visibility_level change" do+ visit_interaction_settings+ members_visibility_chooser.expand+ members_visibility_chooser.select_row_by_value(Group.visibility_levels[:owners])+ group_page.click_save++ expect(dialog).to be_open+ expect(dialog).to have_content(I18n.t("js.groups.manage.interaction.self_lockout"))+ end++ it "saves when confirmed" do+ visit_interaction_settings+ visibility_chooser.expand+ visibility_chooser.select_row_by_value(Group.visibility_levels[:owners])+ group_page.click_save+ dialog.click_yes++ expect(page).to have_no_current_path(%r{/g/#{group.name}/manage})+ expect(group.reload.visibility_level).to eq(Group.visibility_levels[:owners])+ end++ it "does not save when cancelled" do+ visit_interaction_settings+ visibility_chooser.expand+ visibility_chooser.select_row_by_value(Group.visibility_levels[:owners])+ group_page.click_save+ dialog.click_no++ visit_interaction_settings+ expect(visibility_chooser).to have_selected_value(Group.visibility_levels[:public])+ end++ it "saves without dialog for non-restrictive visibility levels" do+ visit_interaction_settings+ visibility_chooser.expand+ visibility_chooser.select_row_by_value(Group.visibility_levels[:staff])+ group_page.click_save++ expect(dialog).to be_closed+ expect(group.reload.visibility_level).to eq(Group.visibility_levels[:staff])+ end+ end++ context "when owner moderator changes visibility to 'Owners only'" do+ before do+ group.add_owner(moderator)+ sign_in(moderator)+ end++ it "saves without showing dialog" do+ visit_interaction_settings+ visibility_chooser.expand+ visibility_chooser.select_row_by_value(Group.visibility_levels[:owners])+ group_page.click_save++ expect(dialog).to be_closed+ expect(group.reload.visibility_level).to eq(Group.visibility_levels[:owners])+ end+ end++ context "when owner moderator removes self with restrictive visibility" do+ before do+ group.update!(visibility_level: Group.visibility_levels[:owners])+ group.add_owner(moderator)+ sign_in(moderator)+ end++ it "shows confirmation dialog when removing self as owner" do+ group_page.visit(group)+ member_dropdown.expand+ member_dropdown.select_row_by_value("removeOwner")++ expect(dialog).to be_open+ expect(dialog).to have_content(I18n.t("js.groups.members.remove_owner_self_lockout"))+ end++ it "shows confirmation dialog when removing self as member" do+ group_page.visit(group)+ member_dropdown.expand+ member_dropdown.select_row_by_value("removeMember")++ expect(dialog).to be_open+ expect(dialog).to have_content(I18n.t("js.groups.members.remove_member_self_lockout"))+ end++ it "does not remove when cancelled" do+ group_page.visit(group)+ member_dropdown.expand+ member_dropdown.select_row_by_value("removeOwner")+ dialog.click_no++ expect(group.reload.group_users.find_by(user: moderator).owner).to be true+ end+ end+end