data_privacy_task_validator.rb 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Validations::DataPrivacyTaskValidator < ActiveModel::Validator
  3. attr_reader :record
  4. delegate :deletable, to: :record
  5. def validate(record)
  6. @record = record
  7. check_for_deletable_type
  8. check_for_existing_task
  9. check_for_user
  10. end
  11. private
  12. def check_for_deletable_type
  13. return if !record.deletable_type_changed?
  14. return if [User, Ticket].any? { deletable.is_a?(_1) }
  15. record.errors.add(:base, __('Data privacy task allows to delete a user or a ticket only.'))
  16. end
  17. def check_for_user
  18. return if !record.deletable_id_changed?
  19. return if !deletable.is_a?(User)
  20. check_for_system_user
  21. check_for_current_user
  22. check_for_last_admin
  23. end
  24. def check_for_system_user
  25. return if deletable.id != 1
  26. record.errors.add(:base, __('It is not possible to delete the system user.'))
  27. end
  28. def check_for_current_user
  29. return if deletable.id != UserInfo.current_user_id
  30. record.errors.add(:base, __('It is not possible to delete your current account.'))
  31. end
  32. def check_for_last_admin
  33. return if !last_admin?
  34. record.errors.add(:base, __('It is not possible to delete the last account with admin permissions.'))
  35. end
  36. def check_for_existing_task
  37. return if !record.deletable_id_changed?
  38. return if !tasks_exists?
  39. record.errors.add(:base, __('Selected object is already queued for deletion.'))
  40. end
  41. def tasks_exists?
  42. DataPrivacyTask
  43. .where.not(id: record.id)
  44. .where.not(state: 'failed')
  45. .exists? deletable: deletable
  46. end
  47. def last_admin?
  48. return false if !deletable_is_admin?
  49. future_admin_ids.blank?
  50. end
  51. def future_admin_ids
  52. other_admin_ids - existing_jobs_admin_ids
  53. end
  54. def other_admin_ids
  55. admin_users.where.not(id: deletable.id).pluck(:id)
  56. end
  57. def deletable_is_admin?
  58. admin_users.exists?(id: deletable.id)
  59. end
  60. def existing_jobs_admin_ids
  61. DataPrivacyTask.where(
  62. deletable_id: other_admin_ids,
  63. deletable_type: 'User'
  64. ).pluck(:deletable_id)
  65. end
  66. def admin_users
  67. User.with_permissions('admin')
  68. end
  69. end