summaryrefslogtreecommitdiff
path: root/app/models/members/member_role.rb
blob: 42ce228c318a3a608f4b4cd8f6627ca1bd6b0e7e (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
# frozen_string_literal: true

class MemberRole < ApplicationRecord # rubocop:disable Gitlab/NamespacedClass
  include IgnorableColumns
  ignore_column :download_code, remove_with: '15.9', remove_after: '2023-01-22'

  has_many :members
  belongs_to :namespace

  validates :namespace, presence: true
  validates :base_access_level, presence: true
  validate :belongs_to_top_level_namespace
  validate :validate_namespace_locked, on: :update
  validate :attributes_locked_after_member_associated, on: :update

  validates_associated :members

  before_destroy :prevent_delete_after_member_associated

  private

  def belongs_to_top_level_namespace
    return if !namespace || namespace.root?

    errors.add(:namespace, s_("MemberRole|must be top-level namespace"))
  end

  def validate_namespace_locked
    return unless namespace_id_changed?

    errors.add(:namespace, s_("MemberRole|can't be changed"))
  end

  def attributes_locked_after_member_associated
    return unless members.present?

    errors.add(:base, s_("MemberRole|cannot be changed because it is already assigned to a user. "\
      "Please create a new Member Role instead"))
  end

  def prevent_delete_after_member_associated
    return unless members.present?

    errors.add(:base, s_("MemberRole|cannot be deleted because it is already assigned to a user. "\
      "Please disassociate the member role from all users before deletion."))

    throw :abort # rubocop:disable Cop/BanCatchThrow
  end
end