【问题标题】:Combining Devise authenticate helpers with `OR` statements in Rails在 Rails 中将 Devise 身份验证助手与“或”语句相结合
【发布时间】:2015-08-02 06:00:18
【问题描述】:

我目前正在使用 Devise gem 来处理用户身份验证。

有一些辅助方法基本上允许您在用户访问控制器中的某个路由/视图之前对其进行身份验证。

即如果您需要user_type_ones 登录才能访问/home

class FooController < ApplicationController
   before_action :authenticate_user_type_one!

   def home
     #stuff
   end
end

你会怎样做才能让特定类型的用户可以访问该页面。

所以如果我有三种类型的用户,user_type_oneuser_type_twouser_type_three,我只希望 user_type_ones 和 user_type_twos 访问 /home,我想做这样的事情.

before_action :authenticate_user_type_one! || :authenticate_user_type_two!

【问题讨论】:

  • 这三种类型的用户是三种完全不同的模型,还是以某种方式继承?为什么不定义另一个before_action 来检查current_user 属于哪种类型的用户?

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


【解决方案1】:

Devise 为您处理了许多默认设置,并且做得非常出色,但是当您需要开始自定义行为时,它会变得非常棘手。特别是如果您是 Rails 开发的新手,我通常认为最好编写自己的自定义方法来手动检查您需要检查的内容。然后,随着您对 Devise 越来越熟悉,您可以慢慢了解它可能具有的内置工具,或者您可以破解的内部挂钩,从而更优雅地获得所需的行为。

具体来说,作为起点,我会尝试编写自定义 before_action:

class FooController < ApplicationController
  before_action :authenticate_apple_or_orange_or_pear!

  def home
    stuff
  end

  protected

  def authenticate_apple_or_orange_or_pear!
    unless apple_signed_in? or orange_signed_in? or pear_signed_in?
      redirect_to go_away_and_never_return_path, alert: "You're not wanted here."
    end
  end

end

如果我正确理解您的需求,这应该可以满足您的要求。它会检查是否有任何所需的帐户类型已登录,如果没有,它将访问者重定向到不同的路径,从而阻止对该控制器的访问。

如果这是您跨多个控制器需要的东西,您还可以将此方法定义移动到 application_controller.rb 中,并且它将对所有从 ApplicationController 继承的控制器可用(通常意味着所有控制器) .

【讨论】:

    猜你喜欢
    • 2016-02-26
    • 1970-01-01
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-03-02
    • 2016-04-12
    相关资源
    最近更新 更多