BigW Consortium Gitlab

labels_finder.rb 2.17 KB
Newer Older
1
class LabelsFinder < UnionFinder
2 3 4 5 6
  def initialize(current_user, params = {})
    @current_user = current_user
    @params = params
  end

7 8
  def execute(skip_authorization: false)
    @skip_authorization = skip_authorization
9
    items = find_union(label_ids, Label) || Label.none
10 11 12 13 14 15
    items = with_title(items)
    sort(items)
  end

  private

16
  attr_reader :current_user, :params, :skip_authorization
17

18
  def label_ids
19
    label_ids = []
20

21 22
    if project?
      if project
23 24 25 26 27 28 29 30 31 32 33
        if project.group.present?
          labels_table = Label.arel_table

          label_ids << Label.where(
            labels_table[:type].eq('GroupLabel').and(labels_table[:group_id].eq(project.group.id)).or(
              labels_table[:type].eq('ProjectLabel').and(labels_table[:project_id].eq(project.id))
            )
          )
        else
          label_ids << project.labels
        end
34
      end
35 36 37 38 39 40
    else
      label_ids << Label.where(group_id: projects.group_ids)
      label_ids << Label.where(project_id: projects.select(:id))
    end

    label_ids
41 42
  end

43
  def sort(items)
44
    items.reorder(title: :asc)
45 46
  end

47
  def with_title(items)
48 49 50 51
    return items if title.nil?
    return items.none if title.blank?

    items.where(title: title)
52 53
  end

54 55
  def group?
    params[:group_id].present?
56 57
  end

58 59
  def project?
    params[:project_id].present?
60 61
  end

62 63
  def projects?
    params[:project_ids].present?
64 65
  end

66
  def title
67
    params[:title] || params[:name]
68 69
  end

70 71 72
  def project
    return @project if defined?(@project)

73 74 75
    if project?
      @project = Project.find(params[:project_id])
      @project = nil unless authorized_to_read_labels?(@project)
76 77 78 79 80 81 82
    else
      @project = nil
    end

    @project
  end

83 84 85
  def projects
    return @projects if defined?(@projects)

86
    @projects = skip_authorization ? Project.all : ProjectsFinder.new(current_user: current_user).execute
87 88
    @projects = @projects.in_namespace(params[:group_id]) if group?
    @projects = @projects.where(id: params[:project_ids]) if projects?
89
    @projects = @projects.reorder(nil)
90 91 92

    @projects
  end
93

94 95 96 97
  def authorized_to_read_labels?(project)
    return true if skip_authorization

    Ability.allowed?(current_user, :read_label, project)
98
  end
99
end