two_factor_authentications_controller.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # frozen_string_literal: true
  2. module Settings
  3. class TwoFactorAuthenticationsController < BaseController
  4. include ChallengableConcern
  5. layout 'admin'
  6. before_action :authenticate_user!
  7. before_action :verify_otp_required, only: [:create]
  8. before_action :require_challenge!, only: [:create]
  9. skip_before_action :require_functional!
  10. def show
  11. @confirmation = Form::TwoFactorConfirmation.new
  12. end
  13. def create
  14. current_user.otp_secret = User.generate_otp_secret(32)
  15. current_user.save!
  16. redirect_to new_settings_two_factor_authentication_confirmation_path
  17. end
  18. def destroy
  19. if acceptable_code?
  20. current_user.otp_required_for_login = false
  21. current_user.save!
  22. UserMailer.two_factor_disabled(current_user).deliver_later!
  23. redirect_to settings_two_factor_authentication_path
  24. else
  25. flash.now[:alert] = I18n.t('two_factor_authentication.wrong_code')
  26. @confirmation = Form::TwoFactorConfirmation.new
  27. render :show
  28. end
  29. end
  30. private
  31. def confirmation_params
  32. params.require(:form_two_factor_confirmation).permit(:otp_attempt)
  33. end
  34. def verify_otp_required
  35. redirect_to settings_two_factor_authentication_path if current_user.otp_required_for_login?
  36. end
  37. def acceptable_code?
  38. current_user.validate_and_consume_otp!(confirmation_params[:otp_attempt]) ||
  39. current_user.invalidate_otp_backup_code!(confirmation_params[:otp_attempt])
  40. end
  41. end
  42. end