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?
- current_user = RequestStore.store[:current_user]
- if current_user.blank?
- errors.add(:current_user, 'is not present')
- false
- else
- @current_user_present = true
- true
- end
- end
- def users_attribute_is_array?
- if users.class == Array
- @users_attribute_is_array = true
- true
- else
- errors.add(:users, 'Is not an array')
- false
- end
- end
- def 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
- true
- rescue NoMethodError
- errors.add(:users, 'Does not have appropriate structure')
- return false
- 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