Skip to content

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

FIX: Logging hole in group user histories and convert group create to service (#37054)

Martin Brennan43ccc4def00f
diff --git a/app/controllers/admin/groups_controller.rb b/app/controllers/admin/groups_controller.rb
index bc3cb6b325a..dfc086117c0 100644
--- a/app/controllers/admin/groups_controller.rb
+++ b/app/controllers/admin/groups_controller.rb
@@ -7,31 +7,16 @@ class Admin::GroupsController < Admin::StaffController
end
def create
- guardian.ensure_can_create_group!
-
- attributes = group_params.to_h.except(:owner_usernames, :usernames)
- group = Group.new(attributes)
-
- group.membership_request_template = nil unless group_params[:allow_membership_requests]
-
- if group_params[:owner_usernames].present?
- owner_ids = User.where(username: group_params[:owner_usernames].split(",")).pluck(:id)
-
- owner_ids.each { |user_id| group.group_users.build(user_id: user_id, owner: true) }
- end
-
- if group_params[:usernames].present?
- user_ids = User.where(username: group_params[:usernames].split(",")).pluck(:id)
- user_ids -= owner_ids if owner_ids
-
- user_ids.each { |user_id| group.group_users.build(user_id: user_id) }
- end
-
- if group.save
- group.restore_user_count!
- render_serialized(group, BasicGroupSerializer)
- else
- render_json_error group
+ Groups::Create.call(
+ guardian:,
+ params: group_params.except(*DiscoursePluginRegistry.group_params),
+ options: {
+ dynamic_attributes: group_params.slice(*DiscoursePluginRegistry.group_params),
+ },
+ ) do |result|
+ on_success { |group:| render_serialized(group, BasicGroupSerializer) }
+ on_failed_policy(:can_create_group) { |policy| raise Discourse::InvalidAccess }
+ on_failure { render(json: failed_json, status: :unprocessable_entity) }
end
end
diff --git a/app/services/group_action_logger.rb b/app/services/group_action_logger.rb
index 02299afb485..b547ae4f51d 100644
--- a/app/services/group_action_logger.rb
+++ b/app/services/group_action_logger.rb
@@ -62,6 +62,13 @@ class GroupActionLogger
end
end
+ def log_group_creation
+ @group.group_users.each do |group_user|
+ log_make_user_group_owner(group_user.user) if group_user.owner?
+ log_add_user_to_group(group_user.user)
+ end
+ end
+
private
def excluded_attributes
diff --git a/app/services/groups/create.rb b/app/services/groups/create.rb
new file mode 100644
index 00000000000..c6057ad6e22
--- /dev/null
+++ b/app/services/groups/create.rb
@@ -0,0 +1,154 @@
+# frozen_string_literal: true
+
+class Groups::Create
+ include Service::Base
+
+ # @!method self.call(guardian:, params:)
+ # @param [Guardian] guardian
+ # @param [Hash] params
+ # @option params [String] :name
+ # @option params [Integer] :mentionable_level
+ # @option params [Integer] :messageable_level
+ # @option params [Integer] :visibility_level
+ # @option params [Integer] :members_visibility_level
+ # @option params [String] :automatic_membership_email_domains
+ # @option params [String] :title
+ # @option params [Boolean] :primary_group
+ # @option params [Integer] :grant_trust_level
+ # @option params [String] :incoming_email
+ # @option params [String] :flair_icon
+ # @option params [Integer] :flair_upload_id
+ # @option params [String] :flair_bg_color
+ # @option params [String] :flair_color
+ # @option params [String] :bio_raw
+ # @option params [Boolean] :public_admission
+ # @option params [Boolean] :public_exit
+ # @option params [Boolean] :allow_membership_requests
+ # @option params [String] :full_name
+ # @option params [Integer] :default_notification_level
+ # @option params [String] :membership_request_template
+ # @option params [String] :owner_usernames
+ # @option params [String] :usernames
+ # @option params [Boolean] :publish_read_state
+ # @option params [Hash] :custom_fields
+ # @option params [Array] :associated_group_ids
+
+ options { attribute :dynamic_attributes, default: -> { {} } }
+
+ params do
+ attribute :name, :string
+ attribute :mentionable_level, :integer, default: Group::ALIAS_LEVELS[:nobody]
+ attribute :messageable_level, :integer, default: Group::ALIAS_LEVELS[:nobody]
+ attribute :visibility_level, :integer, default: Group.visibility_levels[:public]
+ attribute :members_visibility_level, :integer, default: Group.visibility_levels[:public]
+ attribute :automatic_membership_email_domains, :string
+ attribute :title, :string
+ attribute :primary_group, :boolean, default: false
+ attribute :grant_trust_level, :integer
+ attribute :incoming_email, :string
+ attribute :flair_icon, :string
+ attribute :flair_upload_id, :integer
+ attribute :flair_bg_color, :string
+ attribute :flair_color, :string
+ attribute :bio_raw, :string
+ attribute :public_admission, :boolean, default: false
+ attribute :public_exit, :boolean, default: false
+ attribute :allow_membership_requests, :boolean, default: false
+ attribute :full_name, :string
+ attribute :default_notification_level,
+ :integer,
+ default: GroupUser.notification_levels[:watching]
+
+ attribute :membership_request_template, :string
+ attribute :owner_usernames, :array, default: -> { [] }
+ attribute :usernames, :array, default: -> { [] }
+ attribute :publish_read_state, :boolean, default: false
+ attribute :custom_fields, default: -> { {} }
+ attribute :associated_group_ids, :array
+
+ validates :name, presence: true
+ validates :default_notification_level, inclusion: { in: GroupUser.notification_levels.values }
+ validates :mentionable_level, inclusion: { in: Group::ALIAS_LEVELS.values }
+ validates :messageable_level, inclusion: { in: Group::ALIAS_LEVELS.values }
+ validates :visibility_level,
+ inclusion: {
+ in: Group.visibility_levels.values,
+ },
+ allow_blank: true
+ validates :members_visibility_level,
+ inclusion: {
+ in: Group.visibility_levels.values,
+ },
+ allow_blank: true
+
+ validate :custom_fields_allowed_keys, if: -> { custom_fields.present? }
+
+ after_validation { self.membership_request_template = nil unless allow_membership_requests }
+
+ def owner_ids
+ return [] if owner_usernames.blank?
+ User.where(username: owner_usernames).pluck(:id)
+ end
+
+ def user_ids
+ return [] if usernames.blank?
+ User.where(username: usernames).pluck(:id) - owner_ids
+ end
+
+ private
+
+ def custom_fields_allowed_keys
+ allowed_keys = DiscoursePluginRegistry.editable_group_custom_fields
+ return if allowed_keys.blank?
+
+ (custom_fields.keys.map(&:to_sym) - allowed_keys.map(&:to_sym)).each do |key|
+ errors.add(:custom_fields, "disallowed key: #{key}")
+ end
+ end
+ end
+
+ policy :can_create_group
+ model :user_attributes, :build_user_attributes, optional: true
+ model :group, :instantiate_group
+ only_if(:should_associate_groups) { step :associate_groups }
+
+ transaction do
+ step :save
+ step :log_group_histories
+ end
+
+ private
+
+ def can_create_group(guardian:)
+ guardian.can_create_group?
+ end
+
+ def build_user_attributes(params:)
+ params.owner_ids.map { { user_id: _1, owner: true } } + params.user_ids.map { { user_id: _1 } }
+ end
+
+ def instantiate_group(params:, guardian:, user_attributes:, options:)
+ Group.new(
+ params.except(:owner_usernames, :usernames, :associated_group_ids).merge(
+ options.dynamic_attributes,
+ ),
+ ) { _1.group_users.build(user_attributes) }
+ end
+
+ def should_associate_groups(guardian:, params:)
+ guardian.can_associate_groups? && params.associated_group_ids.present?
+ end
+
+ def associate_groups(group:, params:)
+ group.associated_group_ids = params.associated_group_ids
+ end
+
+ def save(group:)
+ group.save!
+ group.restore_user_count!
+ end
+
+ def log_group_histories(guardian:, group:)
+ GroupActionLogger.new(guardian.user, group).log_group_creation
+ end
+end
diff --git a/lib/service/contract_base.rb b/lib/service/contract_base.rb
index bdacc366460..08aa62037dc 100644
--- a/lib/service/contract_base.rb
+++ b/lib/service/contract_base.rb
@@ -6,7 +6,7 @@ class Service::ContractBase
include ActiveModel::AttributeMethods
include ActiveModel::Validations::Callbacks
- delegate :slice, :merge, to: :to_hash
+ delegate :slice, :merge, :except, to: :to_hash
class << self
def attribute(name, cast_type = nil, **options, &block)
diff --git a/spec/requests/admin/groups_controller_spec.rb b/spec/requests/admin/groups_controller_spec.rb
index 81e316e27eb..78ddc595574 100644
--- a/spec/requests/admin/groups_controller_spec.rb
+++ b/spec/requests/admin/groups_controller_spec.rb
@@ -21,20 +21,23 @@ RSpec.describe Admin::GroupsController do
end
context "when logged in as an admin" do
+ let(:group) { Group.last }
+
before { sign_in(admin) }
- it "should work" do
+ it "creates a group with the specified attributes" do
post "/admin/groups.json", params: group_params
- expect(response.status).to eq(200)
+ expect(response).to have_http_status(:ok)
- group = Group.last
-
- expect(group.name).to eq("testing")
+ expect(group).to have_attributes(
+ name: "testing",
+ allow_membership_requests: true,
+ membership_request_template: "Testing",
+ members_visibility_level: Group.visibility_levels[:staff],
+ )
+ expect(group.group_users.where(owner: true).map(&:user)).to contain_exactly(user)
expect(group.users).to contain_exactly(admin, user)
- expect(group.allow_membership_requests).to eq(true)
- expect(group.membership_request_template).to eq("Testing")
- expect(group.members_visibility_level).to eq(Group.visibility_levels[:staff])
end
context "with custom_fields" do
diff --git a/spec/services/group_action_logger_spec.rb b/spec/services/group_action_logger_spec.rb
index 7cefde81de7..120f6603e4e 100644
--- a/spec/services/group_action_logger_spec.rb
+++ b/spec/services/group_action_logger_spec.rb
@@ -93,6 +93,52 @@ RSpec.describe GroupActionLogger do
end
end
+ describe "#log_group_creation" do
+ subject(:log_creation) { logger.log_group_creation }
+
+ let(:owner_history) do
+ GroupHistory.where(group:, action: GroupHistory.actions[:make_user_group_owner])
+ end
+ let(:member_history) do
+ GroupHistory.where(group:, action: GroupHistory.actions[:add_user_to_group])
+ end
+
+ context "when group has only an owner" do
+ it "logs make_user_group_owner for the owner" do
+ expect { log_creation }.to change { owner_history.count }.by(1)
+ expect(owner_history).to contain_exactly(
+ an_object_having_attributes(acting_user: group_owner, target_user: group_owner),
+ )
+ end
+
+ it "logs add_user_to_group for the owner" do
+ expect { log_creation }.to change { member_history.count }.by(1)
+ expect(member_history).to contain_exactly(
+ an_object_having_attributes(acting_user: group_owner, target_user: group_owner),
+ )
+ end
+ end
+
+ context "when group has an owner and a member" do
+ before { group.add(user) }
+
+ it "logs make_user_group_owner only for the owner" do
+ expect { log_creation }.to change { owner_history.count }.by(1)
+ expect(owner_history).to contain_exactly(
+ an_object_having_attributes(acting_user: group_owner, target_user: group_owner),
+ )
+ end
+
+ it "logs add_user_to_group for both owner and member" do
+ expect { log_creation }.to change { member_history.count }.by(2)
+ expect(member_history).to contain_exactly(
+ an_object_having_attributes(acting_user: group_owner, target_user: group_owner),
+ an_object_having_attributes(acting_user: group_owner, target_user: user),
+ )
+ end
+ end
+ end
+
describe "#log_change_group_settings" do
it "should create the right record" do
group.update!(public_admission: true, created_at: Time.zone.now)
diff --git a/spec/services/groups/create_spec.rb b/spec/services/groups/create_spec.rb
new file mode 100644
index 00000000000..ed4900f6dd6
--- /dev/null
+++ b/spec/services/groups/create_spec.rb
@@ -0,0 +1,245 @@
+# frozen_string_literal: true
+
+RSpec.describe Groups::Create do
+ describe Groups::Create::Contract, type: :model do
+ subject(:contract) { described_class.new(name: "builders", **attributes) }
+
+ let(:attributes) { {} }
+
+ it { is_expected.to validate_presence_of :name }
+ it do
+ is_expected.to validate_inclusion_of(:mentionable_level).in_array(Group::ALIAS_LEVELS.values)
+ end
+ it do
+ is_expected.to validate_inclusion_of(:messageable_level).in_array(Group::ALIAS_LEVELS.values)
+ end
+ it do
+ is_expected.to validate_inclusion_of(:visibility_level).in_array(
+ Group.visibility_levels.values,
+ )
+ end
+ it do
+ is_expected.to validate_inclusion_of(:members_visibility_level).in_array(
+ Group.visibility_levels.values,
+ )
+ end
+ it do
+ is_expected.to validate_inclusion_of(:default_notification_level).in_array(
+ GroupUser.notification_levels.values,
+ )
+ end
+
+ context "when no editable group custom fields are registered" do
+ it { is_expected.to allow_value({}).for(:custom_fields) }
+ it { is_expected.to allow_value({ arbitrary_key: "value" }).for(:custom_fields) }
+ end
+
+ context "when editable group custom fields are registered" do
+ before { Plugin::Instance.new.register_editable_group_custom_field(:test) }
+
+ after { DiscoursePluginRegistry.reset! }
+
+ it { is_expected.to allow_value({}).for(:custom_fields) }
+ it { is_expected.to allow_value({ test: "value" }).for(:custom_fields) }
+ it { is_expected.not_to allow_value({ disallowed_key: "x" }).for(:custom_fields) }
+ end
+
+ describe "#membership_request_template" do
+ let(:attributes) { { membership_request_template: "Please let me in" } }
+
+ before { contract.valid? }
+
+ context "when allow_membership_requests is false" do
+ it "is nilified after validation" do
+ expect(contract.membership_request_template).to be_nil
+ end
+ end
+
+ context "when allow_membership_requests is true" do
+ let(:attributes) do
+ { membership_request_template: "Please let me in", allow_membership_requests: true }
+ end
+
+ it "is preserved after validation" do
+ expect(contract.membership_request_template).to eq("Please let me in")
+ end
+ end
+ end
+
+ describe "#owner_ids" do
+ fab!(:user_1, :user)
+ fab!(:user_2, :user)
+
+ context "when owner_usernames is blank" do
+ it { expect(contract.owner_ids).to be_empty }
+ end
+
+ context "when owner_usernames is present" do
+ let(:attributes) { { owner_usernames: [user_1.username, user_2.username] } }
+
+ it "returns user IDs for the given usernames" do
+ expect(contract.owner_ids).to contain_exactly(user_1.id, user_2.id)
+ end
+ end
+ end
+
+ describe "#user_ids" do
+ fab!(:owner, :user)
+ fab!(:member_1, :user)
+ fab!(:member_2, :user)
+
+ context "when usernames is blank" do
+ it { expect(contract.user_ids).to be_empty }
+ end
+
+ context "when usernames is present" do
+ let(:attributes) { { usernames: [member_1.username, member_2.username] } }
+
+ it "returns user IDs for the given usernames" do
+ expect(contract.user_ids).to contain_exactly(member_1.id, member_2.id)
+ end
+ end
+
+ context "when usernames includes an owner" do
+ let(:attributes) do
+ { owner_usernames: [owner.username], usernames: [owner.username, member_1.username] }
+ end
+
+ it "excludes owner IDs" do
+ expect(contract.user_ids).to contain_exactly(member_1.id)
+ end
+ end
+ end
+ end
+
+ describe ".call" do
+ subject(:result) { described_class.call(params:, **dependencies, options:) }
+
+ fab!(:admin)
+ fab!(:member_1, :user)
+ fab!(:member_2, :user)
+
+ let(:dependencies) { { guardian: } }
+ let(:options) { {} }
+ let(:guardian) { admin.guardian }
+ let(:params) do
+ {
+ name: "builders",
+ title: "Builders",
+ usernames: [member_1.username, member_2.username].join(","),
+ owner_usernames: [admin.username].join(","),
+ }
+ end
+
+ context "when user cannot create groups" do
+ let(:guardian) { member_1.guardian }
+
+ it { is_expected.to fail_a_policy(:can_create_group) }
+ end
+
+ context "when data is invalid" do
+ let(:params) { { name: nil } }
+
+ it { is_expected.to fail_a_contract }
+ end
+
+ context "when everything's ok" do
+ let(:group) { result.group }
+
+ it { is_expected.to run_successfully }
+
+ it "creates a group with the specified attributes" do
+ expect(group).to have_attributes(name: "builders", title: "Builders")
+ end
+
+ it "assigns owners" do
+ expect(group.group_users.where(owner: true).map(&:user)).to contain_exactly(admin)
+ end
+
+ it "assigns members" do
+ expect(group.group_users.where(owner: false).map(&:user)).to contain_exactly(
+ member_1,
+ member_2,
+ )
+ end
+
+ it "logs group history" do
+ expect { result }.to change { GroupHistory.count }.by(4)
+ end
+
+ context "when guardian can associate groups" do
+ fab!(:associated_group_1, :associated_group)
+ fab!(:associated_group_2, :associated_group)
+
+ before do
+ allow(guardian).to receive(:can_associate_groups?).and_return(true)
+ params[:associated_group_ids] = [associated_group_1.id, associated_group_2.id]
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "assigns associated groups" do
+ expect(group.associated_groups).to contain_exactly(associated_group_1, associated_group_2)
+ end
+ end
+
+ context "when guardian cannot associate groups" do
+ fab!(:associated_group_1, :associated_group)
+
+ before do
+ allow(guardian).to receive(:can_associate_groups?).and_return(false)
+ params[:associated_group_ids] = [associated_group_1.id]
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "does not assign associated groups" do
+ expect(group.associated_groups).to be_empty
+ end
+ end
+
+ context "with dynamic attributes" do
+ let(:options) { { dynamic_attributes: { allow_unknown_sender_topic_replies: true } } }
+
+ before { Plugin::Instance.new.register_group_param(:allow_unknown_sender_topic_replies) }
+
+ after { DiscoursePluginRegistry.reset! }
+
+ it { is_expected.to run_successfully }
+
+ it "applies the dynamic attributes" do
+ expect(group.allow_unknown_sender_topic_replies).to eq(true)
+ end
+ end
+
+ context "with membership_request_template" do
+ before do
+ params.merge!(
+ allow_membership_requests: true,
+ membership_request_template: "Please let me in",
+ )
+ end
+
+ it { is_expected.to run_successfully }
+
+ it "applies the value from the contract" do
+ expect(group.membership_request_template).to eq("Please let me in")
+ end
+ end
+
+ context "without owners or members" do
+ let(:params) { { name: "empty_group", title: "Empty" } }
+
+ it { is_expected.to run_successfully }
+
+ it "creates a group with no group_users" do
+ expect(group.group_users).to be_empty
+ end
+
+ it "does not log any group history" do
+ expect { result }.not_to change { GroupHistory.count }
+ end
+ end
+ end
+ end
+end