I want to override authenticate_user and current_u

2019-01-25 09:56发布

问题:

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

回答1:

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?"



回答2:

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 ?



回答3:

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



回答4:

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


回答5:

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