在Devise身份验证后添加过滤器

时间:2017-11-28 14:53:28

标签: ruby-on-rails ruby-on-rails-4 devise

我需要将around_action :set_time_zone(或before_filter :set_time_zone)添加到应用程序控制器。问题是current_user始终为nil,因为在过滤器之后运行了Devise身份验证。

我想在设计身份验证后运行过滤器,以便我可以访问current_user并获取时区。

我的代码:

class ApplicationController < ActionController::Base
  around_action :set_time_zone

  private

  def set_time_zone
    current_user.time_zone # this raises an expception because current_user is nil
  end
end

class ExampleController < ApplicationController
  before_action :authenticate_user!
end

我希望将authenticate_user!保留在ExampleController中,并将set_time_zone保留在ApplicationController中。

我也尝试过使用append_before_filter :set_time_zone,但它并没有解决问题。

1 个答案:

答案 0 :(得分:0)

回想一下,Devise在幕后使用了Warden,它为你提供了许多回调。 看看每次用户身份验证时执行的after_authentication回调(每次会话中的第一次):

例如:

Warden::Manager.after_authentication do |user,auth,opts|
  user.time_zone
end

只需创建一个新的初始化文件并将代码放在那里。 ( /config/initializers/warden_callbacks.rb