Advertisement
vsokoltsov

Untitled

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