Welcome to mirror list, hosted at ThFree Co, Russian Federation.

bulk_destroy_service.rb « snippets « services « app - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 6eab9fb320ecb2d59cd23797a12eb201f03b16c4 (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
# frozen_string_literal: true

module Snippets
  class BulkDestroyService
    include Gitlab::Allowable

    attr_reader :current_user, :snippets

    DeleteRepositoryError = Class.new(StandardError)
    SnippetAccessError = Class.new(StandardError)

    def initialize(user, snippets)
      @current_user = user
      @snippets = snippets
    end

    def execute(options = {})
      return ServiceResponse.success(message: 'No snippets found.') if snippets.empty?

      user_can_delete_snippets! unless options[:hard_delete]
      attempt_delete_repositories!
      snippets.destroy_all # rubocop: disable Cop/DestroyAll

      ServiceResponse.success(message: 'Snippets were deleted.')
    rescue SnippetAccessError
      service_response_error("You don't have access to delete these snippets.", 403)
    rescue DeleteRepositoryError
      service_response_error('Failed to delete snippet repositories.', 400)
    rescue StandardError
      # In case the delete operation fails
      service_response_error('Failed to remove snippets.', 400)
    end

    private

    def user_can_delete_snippets!
      allowed = DeclarativePolicy.user_scope do
        snippets.find_each.all? { |snippet| user_can_delete_snippet?(snippet) }
      end

      raise SnippetAccessError unless allowed
    end

    def user_can_delete_snippet?(snippet)
      can?(current_user, :admin_snippet, snippet)
    end

    def attempt_delete_repositories!
      snippets.each do |snippet|
        result = Repositories::DestroyService.new(snippet.repository).execute

        raise DeleteRepositoryError if result[:status] == :error
      end
    end

    def service_response_error(message, http_status)
      ServiceResponse.error(message: message, http_status: http_status)
    end
  end
end