diff --git a/app/controllers/groups_controller.rb b/app/controllers/groups_controller.rb index e5c99c2433a..1314a763e2e 100644 --- a/app/controllers/groups_controller.rb +++ b/app/controllers/groups_controller.rb @@ -18,12 +18,7 @@ class GroupsController < ApplicationController page_size = 30 page = params[:page]&.to_i || 0 - groups = Group.order(name: :asc).where(visible: true) - - if !guardian.is_admin? - groups = groups.where(automatic: false) - end - + groups = Group.visible_groups(current_user) count = groups.count groups = groups.offset(page * page_size).limit(page_size) diff --git a/app/models/group.rb b/app/models/group.rb index 618d71cf313..8e457c72de7 100644 --- a/app/models/group.rb +++ b/app/models/group.rb @@ -63,6 +63,20 @@ class Group < ActiveRecord::Base validates :alias_level, inclusion: { in: ALIAS_LEVELS.values} + scope :visible_groups, ->(user) { + groups = Group.order(name: :asc).where("groups.id > 0") + + if !user || !user.admin + owner_group_ids = GroupUser.where(user: user, owner: true).pluck(:group_id) + + groups = groups.where(" + (groups.automatic = false AND groups.visible = true) OR groups.id IN (?) + ", owner_group_ids) + end + + groups + } + scope :mentionable, lambda {|user| levels = [ALIAS_LEVELS[:everyone]] diff --git a/spec/models/group_spec.rb b/spec/models/group_spec.rb index 86f79597c33..e3475bd1620 100644 --- a/spec/models/group_spec.rb +++ b/spec/models/group_spec.rb @@ -1,6 +1,8 @@ require 'rails_helper' describe Group do + let(:admin) { Fabricate(:admin) } + let(:user) { Fabricate(:user) } describe '#builtin' do context "verify enum sequence" do @@ -408,4 +410,44 @@ describe Group do expect(group.bio_cooked).to include("unicorn.png") end + describe ".visible_groups" do + let(:group) { Fabricate(:group, visible: false) } + let(:group_2) { Fabricate(:group, visible: true) } + let(:admin) { Fabricate(:admin) } + let(:user) { Fabricate(:user) } + + before do + group + group_2 + end + + describe 'when user is an admin' do + it 'should return the right groups' do + expect(Group.visible_groups(admin).pluck(:id).sort) + .to eq([group.id, group_2.id].concat(Group::AUTO_GROUP_IDS.keys - [0]).sort) + end + end + + describe 'when user is owner of a group' do + it 'should return the right groups' do + group.add_owner(user) + + expect(Group.visible_groups(user).pluck(:id).sort) + .to eq([group.id, group_2.id]) + end + end + + describe 'when user is not the owner of any group' do + it 'should return the right groups' do + expect(Group.visible_groups(user).pluck(:id).sort) + .to eq([group_2.id]) + end + end + + describe 'user is nil' do + it 'should return the right groups' do + expect(Group.visible_groups(nil).pluck(:id).sort).to eq([group_2.id]) + end + end + end end