Advertisement
vsokoltsov

Untitled

Jan 15th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. # frozen_string_literal: true
  2.  
  3. module UsersValidationConcern
  4. extend ActiveSupport::Concern
  5.  
  6. included do
  7. validate :current_user_present?
  8. validate :users_attribute_is_array?, unless: -> { users.nil? }
  9. validate :valid_users_structure?, if: -> { users_attribute_is_array? }
  10. validate :belongs_to_same_network?, if: lambda {
  11. users_attribute_is_array? && current_user_present? && valid_users_structure?
  12. }
  13. end
  14.  
  15. def current_user_present?
  16. return @current_user if defined? @current_user
  17. @current_user = RequestStore.store[:current_user]
  18. errors.add(:current_user, 'is not present') unless @current_user
  19. end
  20.  
  21. def users_attribute_is_array?
  22. return @users_attribute_is_array if defined? @users_attribute_is_array
  23. @users_attribute_is_array = users.class == Array
  24. errors.add(:users, 'Is not an array') unless @users_attribute_is_array
  25. end
  26.  
  27. def valid_users_structure?
  28. return @valid_users_structure if defined? @valid_users_structure
  29. users.each do |user|
  30. if user.blank? || !user&.key?(:id) || !user&.key?(:role)
  31. errors.add(:users, 'Does not have appropriate structure')
  32. return false
  33. end
  34.  
  35. if user&.key?(:role) && !user[:role]&.is_a?(Integer)
  36. errors.add(:users, "User's role does not have an appropriate type")
  37. return false
  38. end
  39.  
  40. if user&.key?(:role) && !role_for_access_correct?(user[:role]&.to_i)
  41. errors.add(:users, "User with id #{user[:id]} does not have an appropriate role")
  42. return false
  43. end
  44.  
  45. if user&.key?(:id) && User.find_by(id: user[:id]).blank?
  46. errors.add(:users, 'One of these users does not exists')
  47. return false
  48. end
  49. end
  50. @valid_users_structure = true
  51. rescue NoMethodError
  52. errors.add(:users, 'Does not have appropriate structure')
  53. @valid_users_structure = false
  54. return @valid_users_structure
  55. end
  56.  
  57. def role_for_access_correct?(role)
  58. case access
  59. when 0
  60. [::ChatsUser::READ, ::ChatsUser::READ_WRITE_MANAGE].include?(role)
  61. when 1, 2
  62. [::ChatsUser::READ_WRITE, ::ChatsUser::READ_WRITE_MANAGE].include?(role)
  63. when 3
  64. [::ChatsUser::READ_WRITE].include?(role)
  65. else
  66. false
  67. end
  68. end
  69.  
  70. def belongs_to_same_network?
  71. current_user_networks = RequestStore.store[:current_user].networks
  72. users.each do |user|
  73. user_networks = User.find(user[:id]).networks
  74. if (current_user_networks & user_networks).blank?
  75. errors.add(:networks, 'Users don not have the common network')
  76. return false
  77. end
  78. end
  79. end
  80. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement