groups_finder.rb 1.62 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# GroupsFinder
#
# Used to filter Groups by a set of params
#
# Arguments:
#   current_user - which user is requesting groups
#   params:
#     owned: boolean
#     parent: Group
#     all_available: boolean (defaults to true)
#
# Users with full private access can see all groups. The `owned` and `parent`
# params can be used to restrict the groups that are returned.
#
# Anonymous users will never return any `owned` groups. They will return all
# public groups instead, even if `all_available` is set to false.
17
class GroupsFinder < UnionFinder
18 19 20 21
  def initialize(current_user = nil, params = {})
    @current_user = current_user
    @params = params
  end
22

23
  def execute
24 25 26 27
    items = all_groups.map do |item|
      by_parent(item)
    end
    find_union(items, Group).with_route.order_id_desc
28 29 30 31
  end

  private

32 33 34
  attr_reader :current_user, :params

  def all_groups
35 36
    return [owned_groups] if params[:owned]
    return [Group.all] if current_user&.full_private_access?
Felipe Artur's avatar
Felipe Artur committed
37

38 39 40 41
    groups = []
    groups << Gitlab::GroupHierarchy.new(groups_for_ancestors, groups_for_descendants).all_groups if current_user
    groups << Group.unscoped.public_to_user(current_user) if include_public_groups?
    groups << Group.none if groups.empty?
42
    groups
Felipe Artur's avatar
Felipe Artur committed
43
  end
44

45 46 47 48 49 50 51 52
  def groups_for_ancestors
    current_user.authorized_groups
  end

  def groups_for_descendants
    current_user.groups
  end

53 54 55 56 57
  def by_parent(groups)
    return groups unless params[:parent]

    groups.where(parent: params[:parent])
  end
58 59 60 61 62 63 64 65

  def owned_groups
    current_user&.groups || Group.none
  end

  def include_public_groups?
    current_user.nil? || params.fetch(:all_available, true)
  end
66
end