confirmations_controller.rb 1.9 KB

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