开发者

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 pl开发者_运维问答ease help me with regards to that Thanks


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


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 ?


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


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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜