has_two_factor.rb 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. # Trigger GraphQL subscriptions on user changes.
  3. module User::HasTwoFactor
  4. extend ActiveSupport::Concern
  5. included do
  6. has_many :two_factor_preferences, dependent: :destroy do
  7. def recovery_codes
  8. recovery_codes_methods.first
  9. end
  10. end
  11. end
  12. def auth_two_factor
  13. @auth_two_factor ||= Auth::TwoFactor.new(self)
  14. end
  15. def two_factor_setup_required?
  16. auth_two_factor.user_setup_required?
  17. end
  18. def two_factor_configured?
  19. auth_two_factor.user_configured?
  20. end
  21. def two_factor_default
  22. preferences.dig(:two_factor_authentication, :default)
  23. end
  24. def two_factor_enabled_authentication_methods
  25. auth_two_factor
  26. .enabled_authentication_methods
  27. .map do |method|
  28. {
  29. method: method.method_name,
  30. configured: two_factor_authentication_method_configured?(method),
  31. default: two_factor_authentication_method_default?(method),
  32. # configuration_possible: method.configuration_possible?, # Maybe needed for the e-mail/sms method (like a health check), for later.
  33. }
  34. end
  35. end
  36. def two_factor_destroy_all_authentication_methods
  37. auth_two_factor.all_authentication_methods.each do |method|
  38. auth_two_factor.authentication_method_object(method.method_name)&.destroy_user_config
  39. end
  40. end
  41. def two_factor_verify_configuration?(authentication_method, payload, configuration)
  42. auth_two_factor.verify_configuration?(authentication_method, payload, configuration)
  43. end
  44. private
  45. def two_factor_authentication_method_configured?(method)
  46. auth_two_factor.user_authentication_methods.include?(method)
  47. end
  48. def two_factor_authentication_method_default?(method)
  49. auth_two_factor.user_authentication_methods.include?(method) &&
  50. auth_two_factor.user_default_authentication_method == method
  51. end
  52. end