I want to override authenticate_user and current_user method of devise gem

前端 未结 5 495
醉梦人生
醉梦人生 2020-12-16 15:22

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

相关标签:
5条回答
  • 2020-12-16 15:42

    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 ?

    0 讨论(0)
  • 2020-12-16 15:42

    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
    
    0 讨论(0)
  • 2020-12-16 15:46

    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

    0 讨论(0)
  • 2020-12-16 15:51

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

    0 讨论(0)
  • 2020-12-16 15:56

    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 讨论(0)
提交回复
热议问题