gitlab-org--gitlab-foss/app/finders/labels_finder.rb

100 lines
2.2 KiB
Ruby
Raw Normal View History

2016-09-20 00:08:04 -04:00
class LabelsFinder < UnionFinder
2016-09-19 16:16:16 -04:00
def initialize(current_user, params = {})
@current_user = current_user
@params = params
end
def execute(skip_authorization: false)
@skip_authorization = skip_authorization
items = find_union(label_ids, Label) || Label.none
2016-09-19 16:16:16 -04:00
items = with_title(items)
sort(items)
end
private
attr_reader :current_user, :params, :skip_authorization
2016-09-19 16:16:16 -04:00
2016-09-20 00:08:04 -04:00
def label_ids
2016-09-19 16:16:16 -04:00
label_ids = []
if project?
if project
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
end
else
label_ids << Label.where(group_id: projects.group_ids)
label_ids << Label.where(project_id: projects.select(:id))
end
label_ids
2016-09-19 16:16:16 -04:00
end
def sort(items)
items.reorder(title: :asc)
end
2016-09-19 16:16:16 -04:00
def with_title(items)
return items if title.nil?
return items.none if title.blank?
items.where(title: title)
2016-09-19 16:16:16 -04:00
end
def group?
params[:group_id].present?
2016-09-19 16:16:16 -04:00
end
def project?
params[:project_id].present?
2016-09-19 16:16:16 -04:00
end
def projects?
params[:project_ids].present?
end
2016-09-19 16:16:16 -04:00
def title
params[:title] || params[:name]
2016-09-19 16:16:16 -04:00
end
def project
return @project if defined?(@project)
if project?
@project = Project.find(params[:project_id])
@project = nil unless authorized_to_read_labels?(@project)
else
@project = nil
end
@project
end
2016-09-19 16:16:16 -04:00
def projects
return @projects if defined?(@projects)
@projects = skip_authorization ? Project.all : ProjectsFinder.new(current_user: current_user).execute
@projects = @projects.in_namespace(params[:group_id]) if group?
@projects = @projects.where(id: params[:project_ids]) if projects?
@projects = @projects.reorder(nil)
2016-09-19 16:16:16 -04:00
@projects
end
def authorized_to_read_labels?(project)
return true if skip_authorization
Ability.allowed?(current_user, :read_label, project)
end
2016-09-19 16:16:16 -04:00
end