【问题标题】:Add filter after devise's :authenticate_user?在设计的 :authenticate_user 之后添加过滤器?
【发布时间】:2013-09-17 14:24:24
【问题描述】:

我想在:authenticate_user! 之后添加第二个过滤器。

目前,我的基本命名空间控制器中有一个典型设置:

module Admin
  class AdminController < ApplicationController
    before_filter :authenticate_user!
  end
end

但是对此的任何变体都不起作用:重定向不会发生,因此用户在不应该访问时仍然可以访问。

# Doesn't work
before_filter :admin_only
def admin_only
  :authenticate_user!
end

# Doesn't work
before_filter do
  :authenticate_user!
end

# Doesn't work
before_filter [:authenticate_user!] 

如果这些变体中的任何一个可行,我可以添加额外的过滤代码。怎么回事?

【问题讨论】:

    标签: ruby-on-rails-3 devise namespaces


    【解决方案1】:

    只需在过滤方法之前附加您的额外内容

    before_filter :authenticate_user!, :my_extra_before_filter_method
    

    authenticate_user! 将首先执行,然后是您的自定义过滤器

    更新:你也可以拨打before_filter两次

    before_filter :authenticate_user!
    before_filter :my_extra_before_filter_method
    

    【讨论】:

    • 红宝石的“乐趣”:一百万种方法可以做同样的事情,但只有一种方法是正确的。
    【解决方案2】:

    This answer 到 a similar question 表示以下内容:

    Devise 在后台使用 Warden https://github.com/plataformatec/devise/blob/master/lib/devise/controllers/helpers.rb

    所以您可以在 Warden 中添加一个新策略来验证您的用户。见https://github.com/hassox/warden/wiki/Strategies

    要添加第二个过滤器吗?或者只是覆盖?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-04
      • 1970-01-01
      • 2015-06-26
      • 2013-06-28
      相关资源
      最近更新 更多