Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # frozen_string_literal: true
- module UsersValidationConcern
- extend ActiveSupport::Concern
- included do
- validate :current_user_present?
- validate :users_attribute_is_array?, unless: -> { users.nil? }
- validate :valid_users_structure?, if: -> { users_attribute_is_array? }
- validate :belongs_to_same_network?, if: lambda {
- users_attribute_is_array? && current_user_present? && valid_users_structure?
- }
- end
- def current_user_present?
- return @current_user if defined? @current_user
- @current_user = RequestStore.store[:current_user]
- errors.add(:current_user, 'is not present') unless @current_user
- end
- def users_attribute_is_array?
- return @users_attribute_is_array if defined? @users_attribute_is_array
- @users_attribute_is_array = users.class == Array
- errors.add(:users, 'Is not an array') unless @users_attribute_is_array
- end
- def valid_users_structure?
- return @valid_users_structure if defined? @valid_users_structure
- users.each do |user|
- if user.blank? || !user&.key?(:id) || !user&.key?(:role)
- errors.add(:users, 'Does not have appropriate structure')
- return false
- end
- if user&.key?(:role) && !user[:role]&.is_a?(Integer)
- errors.add(:users, "User's role does not have an appropriate type")
- return false
- end
- if user&.key?(:role) && !role_for_access_correct?(user[:role]&.to_i)
- errors.add(:users, "User with id #{user[:id]} does not have an appropriate role")
- return false
- end
- if user&.key?(:id) && User.find_by(id: user[:id]).blank?
- errors.add(:users, 'One of these users does not exists')
- return false
- end
- end
- @valid_users_structure = true
- rescue NoMethodError
- errors.add(:users, 'Does not have appropriate structure')
- @valid_users_structure = false
- return @valid_users_structure
- end
- def role_for_access_correct?(role)
- case access
- when 0
- [::ChatsUser::READ, ::ChatsUser::READ_WRITE_MANAGE].include?(role)
- when 1, 2
- [::ChatsUser::READ_WRITE, ::ChatsUser::READ_WRITE_MANAGE].include?(role)
- when 3
- [::ChatsUser::READ_WRITE].include?(role)
- else
- false
- end
- end
- def belongs_to_same_network?
- current_user_networks = RequestStore.store[:current_user].networks
- users.each do |user|
- user_networks = User.find(user[:id]).networks
- if (current_user_networks & user_networks).blank?
- errors.add(:networks, 'Users don not have the common network')
- return false
- end
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement