Commit 4d2dbb1

mo <mo.khan@gmail.com>
2018-09-18 22:27:58
extract authentication module
1 parent 0a81ca7
Changed files (3)
app/controllers/concerns/authentication.rb
@@ -0,0 +1,38 @@
+# frozen_string_literal: true
+
+module Authentication
+  extend ActiveSupport::Concern
+  included do
+    before_action :set_current_request_details
+    before_action :authenticate!
+    before_action :authenticate_mfa!
+    helper_method :current_user, :current_user?
+  end
+
+  def current_user
+    Current.user
+  end
+
+  def current_user?
+    Current.user?
+  end
+
+  private
+
+  def authenticate!
+    redirect_to new_session_path unless current_user?
+  end
+
+  def authenticate_mfa!
+    return unless Current.user?
+    mfa = Current.user.mfa
+    redirect_to new_mfa_path unless mfa.valid_session?(session[:mfa])
+  end
+
+  def set_current_request_details(uuid: session[:user_id])
+    Current.request_id = request.uuid
+    Current.user_agent = request.user_agent
+    Current.ip_address = request.ip
+    Current.user = User.find_by(uuid: uuid) if uuid.present?
+  end
+end
app/controllers/application_controller.rb
@@ -1,38 +1,12 @@
 # frozen_string_literal: true
 
 class ApplicationController < ActionController::Base
+  include Authentication
   protect_from_forgery with: :exception
-  before_action :authenticate!
-  before_action :authenticate_mfa!
-  helper_method :current_user, :current_user?
   add_flash_types :error, :warning
 
   def render_error(status, model: nil)
     @model = model
     render template: "errors/#{status}", status: status
   end
-
-  def current_user
-    return nil if session[:user_id].blank?
-    @current_user ||= User.find_by!(uuid: session[:user_id])
-  rescue ActiveRecord::RecordNotFound => error
-    logger.error(error)
-    nil
-  end
-
-  def current_user?
-    current_user.present?
-  end
-
-  private
-
-  def authenticate!
-    redirect_to new_session_path unless current_user?
-  end
-
-  def authenticate_mfa!
-    return unless current_user?
-    mfa = current_user.mfa
-    redirect_to new_mfa_path unless mfa.valid_session?(session[:mfa])
-  end
 end
app/models/current.rb
@@ -1,7 +1,7 @@
 # frozen_string_literal: true
 
 class Current < ActiveSupport::CurrentAttributes
-  attribute :client, :user
+  attribute :user
   attribute :request_id, :user_agent, :ip_address
 
   def user?