Add coverage for permissions/positions validation checks

This commit is contained in:
Matt Jankowski 2024-09-11 10:15:57 -04:00
parent 83a105454d
commit 7010bf3900
2 changed files with 30 additions and 8 deletions

View File

@ -91,10 +91,13 @@ class UserRole < ApplicationRecord
validates :name, presence: true, unless: :everyone?
validates :color, format: { with: VALID_COLOR }, if: :color?
validate :validate_permissions_elevation
validate :validate_position_elevation
validate :validate_dangerous_permissions
validate :validate_own_role_edition
with_options if: -> { defined?(@current_account) } do
validate :validate_own_role_edition
validate :validate_permissions_elevation
validate :validate_position_elevation
end
validate :validate_dangerous_permissions, if: :everyone?
before_validation :set_position
@ -179,21 +182,21 @@ class UserRole < ApplicationRecord
end
def validate_own_role_edition
return unless defined?(@current_account) && @current_account.user_role.id == id
return unless @current_account.user_role.id == id
errors.add(:permissions_as_keys, :own_role) if permissions_changed?
errors.add(:position, :own_role) if position_changed?
end
def validate_permissions_elevation
errors.add(:permissions_as_keys, :elevated) if defined?(@current_account) && @current_account.user_role.computed_permissions & permissions != permissions
errors.add(:permissions_as_keys, :elevated) if @current_account.user_role.computed_permissions & permissions != permissions
end
def validate_position_elevation
errors.add(:position, :elevated) if defined?(@current_account) && @current_account.user_role.position < position
errors.add(:position, :elevated) if @current_account.user_role.position < position
end
def validate_dangerous_permissions
errors.add(:permissions_as_keys, :dangerous) if everyone? && Flags::DEFAULT & permissions != permissions
errors.add(:permissions_as_keys, :dangerous) if Flags::DEFAULT & permissions != permissions
end
end

View File

@ -22,6 +22,25 @@ RSpec.describe UserRole do
it { is_expected.to allow_values('#112233', '#aabbcc', '').for(:color) }
it { is_expected.to_not allow_values('x', '112233445566', '#xxyyzz').for(:color) }
end
context 'when current_account is set' do
subject { Fabricate :user_role }
let(:account) { Fabricate :account }
before { subject.current_account = account }
it { is_expected.to_not allow_value(999_999).for(:position).with_message(:elevated) }
it { is_expected.to_not allow_value(999_999).for(:permissions).against(:permissions_as_keys).with_message(:elevated) }
context 'when current_account is changing their own role' do
let(:account) { Fabricate :account, user: Fabricate(:user, role: subject) }
it { is_expected.to_not allow_value(100).for(:permissions).against(:permissions_as_keys).with_message(:own_role) }
it { is_expected.to_not allow_value(100).for(:position).with_message(:own_role) }
end
end
end
describe 'Callback for position' do