我想覆盖devise gem的authenticate_user和current_user方法

问题描述 投票:11回答:5

我想覆盖authenticate_user!和我的应用程序控制器中的devise gem的current_user方法可以请你帮我解决这个问题

ruby ruby-on-rails-3 rubygems
5个回答
6
投票

您可以像以下一样进行猴子修补:

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

但我会问最终的目标是什么,因为Devise已经内置了一些可定制性,并且覆盖这些方法让我想知道“为什么要使用Devise?”


8
投票

在覆盖用户的身份验证方式时:

Devise在引擎盖https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb下使用Warden

因此,您只需在Warden中添加新策略即可对用户进行身份验证。见https://github.com/hassox/warden/wiki/Strategies

您不应该覆盖current_user。你面临什么挑战?你需要退回不同的型号吗?


5
投票

如果你想将代码添加到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

4
投票

您必须创建一个自定义类来覆盖默认的Devise行为:

  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

在你的config / initializers / devise.rb中:

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

但我建议查看Devise文档:)

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


0
投票

application_controller.rb,您可以根据需要覆盖:

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
© www.soinside.com 2019 - 2024. All rights reserved.