Search code examples
ruby-on-rails-3authenticationruby-on-rails-3.1rubygemsdevise

Where to override current_user helper method of devise gem


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,


Solution

  • 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