has_two_factor.rb 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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_enabled_authentication_methods
  22. auth_two_factor
  23. .enabled_authentication_methods
  24. .map do |method|
  25. {
  26. method: method.method_name,
  27. configured: two_factor_authentication_method_configured?(method),
  28. default: two_factor_authentication_method_default?(method),
  29. # configuration_possible: method.configuration_possible?, # TODO: For the e-mail/sms method (like a health check), for later.
  30. }
  31. end
  32. end
  33. def two_factor_destroy_authentication_method(method)
  34. auth_two_factor.authentication_method_object(method).destroy_user_config
  35. end
  36. def two_factor_destroy_all_authentication_methods
  37. auth_two_factor.user_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. def two_factor_recovery_codes_generate(force: false)
  45. return if !auth_two_factor.recovery_codes_enabled? || (auth_two_factor.user_recovery_codes_exists? && !force)
  46. Auth::TwoFactor::RecoveryCodes.new(self).generate
  47. end
  48. def two_factor_update_default_method(method_name)
  49. current_prefs = preferences
  50. current_prefs[:two_factor_authentication] ||= {}
  51. current_prefs[:two_factor_authentication][:default] = method_name
  52. update!(preferences: current_prefs)
  53. end
  54. private
  55. def two_factor_authentication_method_configured?(method)
  56. auth_two_factor.user_authentication_methods.include?(method)
  57. end
  58. def two_factor_authentication_method_default?(method)
  59. auth_two_factor.user_authentication_methods.include?(method) && auth_two_factor.user_default_authentication_method == method
  60. end
  61. end