|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +class Devise::TwoFactorController < DeviseController |
| 4 | + prepend_before_action :require_no_authentication |
| 5 | + prepend_before_action :ensure_sign_in_initiated |
| 6 | + |
| 7 | + # Extensions can inject custom actions or override defaults via on_load |
| 8 | + ActiveSupport.run_load_hooks(:devise_two_factor_controller, self) |
| 9 | + |
| 10 | + # Auto-generate default new_<module> actions for each registered 2FA module. |
| 11 | + # Extensions that injected a custom action via on_load won't be overwritten. |
| 12 | + Devise.two_factor_method_configs.each_key do |mod| |
| 13 | + unless method_defined?(:"new_#{mod}") |
| 14 | + define_method(:"new_#{mod}") do |
| 15 | + @resource = find_pending_resource |
| 16 | + end |
| 17 | + end |
| 18 | + end |
| 19 | + |
| 20 | + # POST /users/two_factor |
| 21 | + # All methods POST here. Warden picks the right strategy via valid?. |
| 22 | + def create |
| 23 | + self.resource = warden.authenticate!(auth_options) |
| 24 | + set_flash_message!(:notice, :signed_in, scope: :"devise.sessions") |
| 25 | + sign_in(resource_name, resource) |
| 26 | + yield resource if block_given? |
| 27 | + respond_with resource, location: after_sign_in_path_for(resource) |
| 28 | + end |
| 29 | + |
| 30 | + protected |
| 31 | + |
| 32 | + def auth_options |
| 33 | + resource = find_pending_resource |
| 34 | + default_method = resource.enabled_two_factors.first |
| 35 | + { scope: resource_name, recall: "#{controller_path}#new_#{default_method}" } |
| 36 | + end |
| 37 | + |
| 38 | + def translation_scope |
| 39 | + 'devise.two_factor' |
| 40 | + end |
| 41 | + |
| 42 | + def find_pending_resource |
| 43 | + return unless session[:devise_two_factor_resource_id] |
| 44 | + resource_class.where(id: session[:devise_two_factor_resource_id]).first |
| 45 | + end |
| 46 | + |
| 47 | + private |
| 48 | + |
| 49 | + def ensure_sign_in_initiated |
| 50 | + return if session[:devise_two_factor_resource_id].present? |
| 51 | + set_flash_message!(:alert, :sign_in_not_initiated, scope: :"devise.failure") |
| 52 | + redirect_to new_session_path(resource_name) |
| 53 | + end |
| 54 | +end |
0 commit comments