Where to override current_user helper method of devise gem

Omer Aslam picture Omer Aslam · Apr 27, 2012 · Viewed 18.2k times · Source

How can i override current_user of devise gem. Actually I need to add web services for mobile-app.

Currently devise is managing session and 'current_user' for web-application.

Now Mobile app will send user_id to the server. I need to override current user like this

def current_user
  if params[:user_id].blank?
    current_user
  else
    User.find(params[:user_id])
  end   
end

Should I need to modify devise gem as plugin ? or something else ?
Kindly explain in detail as I am new in rails.

Kind regards,

Answer

Limbo Peng picture Limbo Peng · Apr 27, 2012

According to the module Devise::Controllers::Helpers, current_user (together with all other devise helpers) is added to ApplicationController, which means that you can override it in this way:

# in application_controller.rb

def devise_current_user
  @devise_current_user ||= warden.authenticate(scope: :user)
end

def current_user
  if params[:user_id].blank?
    devise_current_user
  else
    User.find(params[:user_id])
  end   
end