two_factor_preference.rb 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class User::TwoFactorPreference < ApplicationModel
  3. include HasDefaultModelUserRelations
  4. belongs_to :user, class_name: 'User', touch: true
  5. scope :authentication_methods, -> { where.not(method: 'recovery_codes') }
  6. scope :recovery_codes_methods, -> { where(method: 'recovery_codes') }
  7. after_destroy :remove_recovery_codes, :update_user_preferences
  8. after_save :update_user_preferences
  9. store :configuration
  10. private
  11. def remove_recovery_codes
  12. return if method.eql?('recovery_codes')
  13. current_user_two_factor_preferences = user.two_factor_preferences
  14. return if current_user_two_factor_preferences.recovery_codes.blank?
  15. return if current_user_two_factor_preferences.authentication_methods.present?
  16. current_user_two_factor_preferences.recovery_codes.destroy!
  17. end
  18. def update_user_preferences
  19. count = user.two_factor_preferences.authentication_methods.count
  20. return true if count > 1
  21. current_prefs = user.preferences
  22. current_pref_default_method = current_prefs.dig(:two_factor_authentication, :default)
  23. case count
  24. when 0
  25. return true if current_pref_default_method.nil?
  26. current_prefs = remove_default_method_from_preferences(current_prefs)
  27. when 1
  28. return true if method_is_default_for_user?(current_pref_default_method)
  29. current_prefs = add_default_method_to_preferences(current_prefs)
  30. end
  31. user.update!(preferences: current_prefs)
  32. true
  33. end
  34. def remove_default_method_from_preferences(preferences)
  35. preferences[:two_factor_authentication] = preferences[:two_factor_authentication].except(:default)
  36. preferences
  37. end
  38. def add_default_method_to_preferences(preferences)
  39. preferences[:two_factor_authentication] ||= {}
  40. preferences[:two_factor_authentication][:default] = first_configured_user_method
  41. preferences
  42. end
  43. def method_is_default_for_user?(method)
  44. method.present? && first_configured_user_method.eql?(method)
  45. end
  46. def first_configured_user_method
  47. user.two_factor_preferences&.authentication_methods&.first&.method
  48. end
  49. end