summaryrefslogtreecommitdiff
path: root/app/services/groups/group_links/create_service.rb
blob: 5f81e5972b0592051a715a8efcde3278c1b05225 (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
# frozen_string_literal: true

module Groups
  module GroupLinks
    class CreateService < Groups::BaseService
      def initialize(shared_group, shared_with_group, user, params)
        @shared_group = shared_group
        super(shared_with_group, user, params)
      end

      def execute
        unless shared_with_group && shared_group &&
               can?(current_user, :admin_group_member, shared_group) &&
               can?(current_user, :read_group, shared_with_group) &&
               sharing_allowed?
          return error('Not Found', 404)
        end

        link = GroupGroupLink.new(
          shared_group: shared_group,
          shared_with_group: shared_with_group,
          group_access: params[:shared_group_access],
          expires_at: params[:expires_at]
        )

        if link.save
          shared_with_group.refresh_members_authorized_projects(direct_members_only: true)
          success(link: link)
        else
          error(link.errors.full_messages.to_sentence, 409)
        end
      end

      private

      attr_reader :shared_group

      alias_method :shared_with_group, :group

      def sharing_allowed?
        sharing_outside_hierarchy_allowed? || within_hierarchy?
      end

      def sharing_outside_hierarchy_allowed?
        !shared_group.root_ancestor.namespace_settings.prevent_sharing_groups_outside_hierarchy
      end

      def within_hierarchy?
        shared_group.root_ancestor.self_and_descendants_ids.include?(shared_with_group.id)
      end
    end
  end
end