set_default_method.rb 972 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. # Copyright (C) 2012-2024 Zammad Foundation, https://zammad-foundation.org/
  2. class Service::User::TwoFactor::SetDefaultMethod < Service::User::TwoFactor::Base
  3. attr_reader :force
  4. def initialize(force: false, **)
  5. super(**)
  6. @force = force
  7. end
  8. def execute
  9. if !method_available? && !force
  10. raise Exceptions::UnprocessableEntity, __('The given two-factor authentication method is not enabled.')
  11. end
  12. if !method_configured? && !force
  13. raise Exceptions::UnprocessableEntity, __('The given two-factor authentication method is not configured.')
  14. end
  15. update_user_preferences!
  16. end
  17. private
  18. def method_configured?
  19. user
  20. .auth_two_factor
  21. .user_authentication_methods
  22. .find { |elem| elem.method_name == method_name }
  23. end
  24. def update_user_preferences!
  25. user.preferences[:two_factor_authentication] ||= {}
  26. user.preferences[:two_factor_authentication][:default] = method_name
  27. user.save!
  28. end
  29. end