【问题标题】:Rails role-based auth with roles stored in databaseRails 基于角色的身份验证,角色存储在数据库中
【发布时间】:2013-03-16 23:48:58
【问题描述】:

是否存在 gem,它实现了以下内容:

  • 用户可以有多个角色
  • 每个角色都有一组权限
  • 每个权限都只是布尔值
  • 存储在数据库中的角色和权限(最重要)

例如,我想要这样的东西:

if current_user.can?(:read_all, :list_of_orders)
...
end

can? 方法应该搜索,是否有任何角色允许它。

【问题讨论】:

  • 我知道cancan,但它的角色定义在文件中,我无法在应用运行时添加一些新角色。
  • 经过一番思考后,我希望使用 devise + cancan 和存储在模型字段中的序列化角色数组。只是因为不需要角色权限的运行时管理:)

标签: ruby-on-rails ruby gem


【解决方案1】:

在 Zippie 问题之后,我建议您使用 CanCan,但您也可以将其用于身份验证。请参阅以下链接,您会发现它们很有用 Rails 3 Authentication and Authorization with Devise and CanCan (Part 1)Rails 3 Authentication and Authorization with Devise and CanCan (Part 2)

您的ability.rb 中可能有类似的内容

class Ability
  include CanCan::Ability
  def initialize(user)
    user ||= User.new # guest user
   # raise user.role?(:administrator).inspect
    if user.role? :administrator

      can :manage, :all
      can :manage, User

    elsif user.role? :employee
      can :read, :all

    end

  end
end

这样在你看来你可以做类似的事情

您也可以在控制器中使用can? 来创建必要的过滤器。

【讨论】:

    【解决方案2】:

    查看用户身份验证设计,您可以在那里定义您的角色:

    https://github.com/plataformatec/devise
    

    或者更好的是,将它与 cancan 轻松结合:

    https://github.com/ryanb/cancan/wiki/Role-Based-Authorization
    

    【讨论】:

      【解决方案3】:

      你可以试试cancan gem,很强大

      https://github.com/ryanb/cancan

      例如:

      <% if can? :update, @article %>
        <%= link_to "Edit", edit_article_path(@article) %>
      <% end %> 
      

      您可以在ability.rb 中定义能力

      can :manage, Article  # user can perform any action on the article
      can :read, :all       # user can read any object
      can :manage, :all     # user can perform any action on any object
      

      【讨论】:

      • 是的,cancan 是很好的解决方案,但我需要动态(在运行时)管理角色。
      猜你喜欢
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 2014-04-04
      • 2015-05-17
      • 1970-01-01
      • 2023-01-24
      • 2021-11-22
      • 2019-10-10
      相关资源
      最近更新 更多