confirmations_controller.rb 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # frozen_string_literal: true
  2. module Settings
  3. module TwoFactorAuthentication
  4. class ConfirmationsController < BaseController
  5. include ChallengableConcern
  6. skip_before_action :require_functional!
  7. before_action :require_challenge!
  8. before_action :ensure_otp_secret
  9. def new
  10. prepare_two_factor_form
  11. end
  12. def create
  13. if current_user.validate_and_consume_otp!(confirmation_params[:otp_attempt], otp_secret: session[:new_otp_secret])
  14. flash.now[:notice] = I18n.t('two_factor_authentication.enabled_success')
  15. current_user.otp_required_for_login = true
  16. current_user.otp_secret = session[:new_otp_secret]
  17. @recovery_codes = current_user.generate_otp_backup_codes!
  18. current_user.save!
  19. UserMailer.two_factor_enabled(current_user).deliver_later!
  20. session.delete(:new_otp_secret)
  21. render 'settings/two_factor_authentication/recovery_codes/index'
  22. else
  23. flash.now[:alert] = I18n.t('otp_authentication.wrong_code')
  24. prepare_two_factor_form
  25. render :new
  26. end
  27. end
  28. private
  29. def confirmation_params
  30. params.require(:form_two_factor_confirmation).permit(:otp_attempt)
  31. end
  32. def prepare_two_factor_form
  33. @confirmation = Form::TwoFactorConfirmation.new
  34. @new_otp_secret = session[:new_otp_secret]
  35. @provision_url = current_user.otp_provisioning_uri(current_user.email,
  36. otp_secret: @new_otp_secret,
  37. issuer: Rails.configuration.x.local_domain)
  38. @qrcode = RQRCode::QRCode.new(@provision_url)
  39. end
  40. def ensure_otp_secret
  41. redirect_to settings_otp_authentication_path if session[:new_otp_secret].blank?
  42. end
  43. end
  44. end
  45. end