two_factor_preference.rb 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class User::TwoFactorPreference < ApplicationModel
  3. include HasDefaultModelUserRelations
  4. include User::TwoFactorPreference::TriggersSubscriptions
  5. belongs_to :user, class_name: 'User', touch: true
  6. scope :authentication_methods, -> { where.not(method: 'recovery_codes') }
  7. scope :recovery_codes_methods, -> { where(method: 'recovery_codes') }
  8. after_destroy :remove_recovery_codes, :update_user_default
  9. after_save :update_user_default
  10. store :configuration
  11. private
  12. def remove_recovery_codes
  13. return if method == 'recovery_codes'
  14. return if user.two_factor_preferences.authentication_methods.exists?
  15. user.two_factor_preferences.recovery_codes&.destroy!
  16. end
  17. def update_user_default
  18. return if user.two_factor_preferences.authentication_methods.exists?(method: user.two_factor_default)
  19. new_default = user.auth_two_factor.user_authentication_methods.first&.method_name
  20. return if new_default == user.two_factor_default
  21. if new_default.nil?
  22. user.preferences[:two_factor_authentication]&.delete :default
  23. else
  24. user.preferences[:two_factor_authentication] ||= {}
  25. user.preferences[:two_factor_authentication][:default] = new_default
  26. end
  27. user.save!
  28. end
  29. end