summaryrefslogtreecommitdiff
path: root/app/finders/snippets_finder.rb
blob: da6e6e87a6ff336cae9660a6415543220c449f1f (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
class SnippetsFinder
  def execute(current_user, params = {})
    filter = params[:filter]
    user = params.fetch(:user, current_user)

    case filter
    when :all then
      snippets(current_user).fresh
    when :public then
      Snippet.are_public.fresh
    when :by_user then
      by_user(current_user, user, params[:scope])
    when :by_project
      by_project(current_user, params[:project], params[:scope])
    end
  end

  private

  def snippets(current_user)
    if current_user
      Snippet.public_and_internal
    else
      # Not authenticated
      #
      # Return only:
      #   public snippets
      Snippet.are_public
    end
  end

  def by_user(current_user, user, scope)
    snippets = user.snippets.fresh

    if current_user
      include_private = user == current_user
      by_scope(snippets, scope, include_private)
    else
      snippets.are_public
    end
  end

  def by_project(current_user, project, scope)
    snippets = project.snippets.fresh

    if current_user
      include_private = project.team.member?(current_user) || current_user.admin?
      by_scope(snippets, scope, include_private)
    else
      snippets.are_public
    end
  end

  def by_scope(snippets, scope = nil, include_private = false)
    case scope.to_s
    when 'are_private'
      include_private ? snippets.are_private : Snippet.none
    when 'are_internal'
      snippets.are_internal
    when 'are_public'
      snippets.are_public
    else
      include_private ? snippets : snippets.public_and_internal
    end
  end
end