summaryrefslogtreecommitdiff
path: root/app/finders/group_members_finder.rb
blob: a6ecd8355273398a2f673d50ea2d7147309e1ab8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# frozen_string_literal: true

class GroupMembersFinder < UnionFinder
  RELATIONS = %i(direct inherited descendants).freeze
  DEFAULT_RELATIONS = %i(direct inherited).freeze

  include CreatedAtFilter

  # Params can be any of the following:
  #   two_factor: string. 'enabled' or 'disabled' are returning different set of data, other values are not effective.
  #   sort:       string
  #   search:     string
  #   created_after: datetime
  #   created_before: datetime
  attr_reader :params

  def initialize(group, user = nil, params: {})
    @group = group
    @user = user
    @params = params
  end

  def execute(include_relations: DEFAULT_RELATIONS)
    return filter_members(group_members_list) if include_relations == [:direct]

    groups = groups_by_relations(include_relations)
    return GroupMember.none unless groups

    members = all_group_members(groups).distinct_on_user_with_max_access_level

    filter_members(members)
  end

  private

  attr_reader :user, :group

  def groups_by_relations(include_relations)
    case include_relations.sort
    when [:inherited]
      group.ancestors
    when [:descendants]
      group.descendants
    when [:direct, :inherited]
      group.self_and_ancestors
    when [:descendants, :direct]
      group.self_and_descendants
    when [:descendants, :inherited]
      find_union([group.ancestors, group.descendants], Group)
    when [:descendants, :direct, :inherited]
      group.self_and_hierarchy
    else
      nil
    end
  end

  def filter_members(members)
    members = members.search(params[:search]) if params[:search].present?
    members = members.sort_by_attribute(params[:sort]) if params[:sort].present?

    if params[:two_factor].present? && can_manage_members
      members = members.filter_by_2fa(params[:two_factor])
    end

    by_created_at(members)
  end

  def can_manage_members
    Ability.allowed?(user, :admin_group_member, group)
  end

  def group_members_list
    group.members
  end

  def all_group_members(groups)
    members_of_groups(groups).non_minimal_access
  end

  def members_of_groups(groups)
    GroupMember.non_request.of_groups(groups)
  end
end

GroupMembersFinder.prepend_if_ee('EE::GroupMembersFinder')