BigW Consortium Gitlab

labels_finder.rb 1.86 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 23 24 25
    if project?
      if project
        label_ids << project.group.labels if project.group.present?
        label_ids << project.labels
      end
26 27 28 29 30 31
    else
      label_ids << Label.where(group_id: projects.group_ids)
      label_ids << Label.where(project_id: projects.select(:id))
    end

    label_ids
32 33
  end

34
  def sort(items)
35
    items.reorder(title: :asc)
36 37
  end

38
  def with_title(items)
39 40 41 42
    return items if title.nil?
    return items.none if title.blank?

    items.where(title: title)
43 44
  end

45 46
  def group?
    params[:group_id].present?
47 48
  end

49 50
  def project?
    params[:project_id].present?
51 52
  end

53 54
  def projects?
    params[:project_ids].present?
55 56
  end

57
  def title
58
    params[:title] || params[:name]
59 60
  end

61 62 63
  def project
    return @project if defined?(@project)

64 65 66
    if project?
      @project = Project.find(params[:project_id])
      @project = nil unless authorized_to_read_labels?(@project)
67 68 69 70 71 72 73
    else
      @project = nil
    end

    @project
  end

74 75 76
  def projects
    return @projects if defined?(@projects)

77 78 79
    @projects = skip_authorization ? Project.all : ProjectsFinder.new.execute(current_user)
    @projects = @projects.in_namespace(params[:group_id]) if group?
    @projects = @projects.where(id: params[:project_ids]) if projects?
80
    @projects = @projects.reorder(nil)
81 82 83

    @projects
  end
84

85 86 87 88
  def authorized_to_read_labels?(project)
    return true if skip_authorization

    Ability.allowed?(current_user, :read_label, project)
89
  end
90
end