data_privacy_task_validator.rb 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. class Validations::DataPrivacyTaskValidator < ActiveModel::Validator
  3. attr_reader :record
  4. def validate(record)
  5. @record = record
  6. check_for_user
  7. check_for_system_user
  8. check_for_current_user
  9. check_for_last_admin
  10. check_for_existing_task
  11. end
  12. private
  13. def check_for_user
  14. return if !record.deletable_type_changed?
  15. return if deletable_is_user?
  16. invalid_because(:deletable, __('is not a User'))
  17. end
  18. def check_for_system_user
  19. return if !record.deletable_id_changed?
  20. return if !deletable_is_user?
  21. return if deletable.id != 1
  22. invalid_because(:deletable, __('is undeletable system User with ID 1'))
  23. end
  24. def check_for_current_user
  25. return if !record.deletable_id_changed?
  26. return if !deletable_is_user?
  27. return if deletable.id != UserInfo.current_user_id
  28. invalid_because(:deletable, __('is your current account'))
  29. end
  30. def check_for_last_admin
  31. return if !record.deletable_id_changed?
  32. return if !deletable_is_user?
  33. return if !last_admin?
  34. invalid_because(:deletable, __('is last account with admin permissions'))
  35. end
  36. def check_for_existing_task
  37. return if !record.deletable_id_changed?
  38. return if !deletable_is_user?
  39. return if !tasks_exists?
  40. invalid_because(:deletable, __('has an existing DataPrivacyTask queued'))
  41. end
  42. def deletable_is_user?
  43. deletable.is_a?(User)
  44. end
  45. def deletable
  46. record.deletable
  47. end
  48. def invalid_because(attribute, message, **options)
  49. record.errors.add attribute, message, **options
  50. end
  51. def tasks_exists?
  52. DataPrivacyTask.where(
  53. deletable: deletable
  54. ).where.not(
  55. id: record.id,
  56. ).where.not(
  57. state: 'failed'
  58. ).exists?
  59. end
  60. def last_admin?
  61. return false if !deletable_is_admin?
  62. future_admin_ids.blank?
  63. end
  64. def future_admin_ids
  65. other_admin_ids - existing_jobs_admin_ids
  66. end
  67. def other_admin_ids
  68. admin_users.where.not(id: deletable.id).pluck(:id)
  69. end
  70. def deletable_is_admin?
  71. admin_users.exists?(id: deletable.id)
  72. end
  73. def existing_jobs_admin_ids
  74. DataPrivacyTask.where(
  75. deletable_id: other_admin_ids,
  76. deletable_type: 'User'
  77. ).pluck(:deletable_id)
  78. end
  79. def admin_users
  80. User.with_permissions('admin')
  81. end
  82. end