Read about our upcoming Code of Conduct on this issue

create_service.rb 1.87 KB
Newer Older
1
2
# frozen_string_literal: true

3
4
module Groups
  class CreateService < Groups::BaseService
Felipe Artur's avatar
Felipe Artur committed
5
6
    def initialize(user, params = {})
      @current_user, @params = user, params.dup
7
      @chat_team = @params.delete(:create_chat_team)
8
9
    end

Felipe Artur's avatar
Felipe Artur committed
10
    def execute
Rubén Dávila's avatar
Rubén Dávila committed
11
12
      remove_unallowed_params

13
14
      @group = Group.new(params)

15
16
      after_build_hook(@group, params)

17
      unless can_use_visibility_level? && can_create_group?
18
        return @group
19
20
      end

Douwe Maan's avatar
Douwe Maan committed
21
      @group.name ||= @group.path.dup
22

23
      if create_chat_team?
Z.J. van de Weg's avatar
Z.J. van de Weg committed
24
        response = Mattermost::CreateTeamService.new(@group, current_user).execute
25
        return @group if @group.errors.any?
Z.J. van de Weg's avatar
Z.J. van de Weg committed
26
27

        @group.build_chat_team(name: response['name'], team_id: response['id'])
28
29
      end

Heinrich Lee Yu's avatar
Heinrich Lee Yu committed
30
      @group.add_owner(current_user) if @group.save
Felipe Artur's avatar
Felipe Artur committed
31
      @group
32
    end
Z.J. van de Weg's avatar
Z.J. van de Weg committed
33
34
35

    private

36
    def after_build_hook(group, params)
37
      # overridden in EE
38
39
    end

Z.J. van de Weg's avatar
Z.J. van de Weg committed
40
41
42
    def create_chat_team?
      Gitlab.config.mattermost.enabled && @chat_team && group.chat_team.nil?
    end
43
44
45
46
47

    def can_create_group?
      if @group.subgroup?
        unless can?(current_user, :create_subgroup, @group.parent)
          @group.parent = nil
48
          @group.errors.add(:parent_id, s_('CreateGroup|You don’t have permission to create a subgroup in this group.'))
49
50
51
52
53

          return false
        end
      else
        unless can?(current_user, :create_group)
54
          @group.errors.add(:base, s_('CreateGroup|You don’t have permission to create groups.'))
55
56
57
58
59
60
61
62
63

          return false
        end
      end

      true
    end

    def can_use_visibility_level?
64
      unless Gitlab::VisibilityLevel.allowed_for?(current_user, visibility_level)
65
66
67
68
69
70
        deny_visibility_level(@group)
        return false
      end

      true
    end
71
72
73
74

    def visibility_level
      params[:visibility].present? ? Gitlab::VisibilityLevel.level_value(params[:visibility]) : params[:visibility_level]
    end
75
76
  end
end