Syed Raza
Syed Raza

Reputation: 1100

I want to override authenticate_user and current_user method of devise gem

I want to override authenticate_user! and current_user method of devise gem in my application Controller can you please help me with regards to that Thanks

Upvotes: 17

Views: 24317

Answers (5)

Lucas Andrade
Lucas Andrade

Reputation: 4590

At application_controller.rb you can overwrite just as you want:

def authenticate_user!
  super # just if want the default behavior 
  call_a_method_to_something if current_user
  # or
  call_a_method_to_something if current_user.nil?
end

Upvotes: 1

Mirror318
Mirror318

Reputation: 12693

If you want to add code to authenticate_user!

class DuckController < ApplicationController
  before_action :authenticate_duck

  ...

  private

  def authenticate_duck
    #use Devise's method
    authenticate_user!
    #add your own stuff
    unless current_user.duck.approved?
      flash[:alert] = "Your duck is still pending. Please contact support for support."
      redirect_to :back
    end
  end
end

Upvotes: 9

Rendrum
Rendrum

Reputation: 264

You have to create a custom class to override the default Devise behavior:

  class CustomFailure < Devise::FailureApp
    def redirect_url
      #return super unless [:worker, :employer, :user].include?(scope) #make it specific to a scope
       new_user_session_url(:subdomain => 'secure')
    end

    # You need to override respond to eliminate recall
    def respond
      if http_auth?
        http_auth
      else
        redirect
      end
    end
  end

And in your config/initializers/devise.rb:

  config.warden do |manager|
    manager.failure_app = CustomFailure
  end

But I suggest check out the Devise documentation :)

https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-when-the-user-can-not-be-authenticated

Upvotes: 6

Monica Wilkinson
Monica Wilkinson

Reputation: 635

On overriding how a user is authenticated:

Devise uses Warden under the hood https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb

So you can just add a new strategy in Warden to authenticate your users. See https://github.com/hassox/warden/wiki/Strategies

You should not need to override current_user. What challenge are you facing ? Do you need a different model returned ?

Upvotes: 9

Sammy Larbi
Sammy Larbi

Reputation: 3122

You may be able to monkey-patch it like:

module Devise
  module Controllers
    module Helpers
      def authenticate_user!
        #do some stuff
      end
    end
  end
end   

But I would ask what the ultimate goal is, because Devise has some customizability built into it already, and overriding these methods makes me wonder "why use Devise at all?"

Upvotes: 9

Related Questions