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

Sye*_*aza 13 ruby rubygems ruby-on-rails-3

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

Mon*_*son 8

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

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

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

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


Sam*_*rbi 6

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

module Devise
  module Controllers
    module Helpers
      def authenticate_user!
        #do some stuff
      end
    end
  end
end   
Run Code Online (Sandbox Code Playgroud)

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


小智 6

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

  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
Run Code Online (Sandbox Code Playgroud)

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

  config.warden do |manager|
    manager.failure_app = CustomFailure
  end
Run Code Online (Sandbox Code Playgroud)

但我建议查看设计文档:)

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


Mir*_*318 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
Run Code Online (Sandbox Code Playgroud)