2013-03-16 117 views
0

不存在的宝石,那下面的事情工具:Rails的基于角色的身份验证与存储在数据库角色

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

例如,我想这样的事情:

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

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

+0

我对cancan很了解,但是它在文件中定义了角色,并且我无法在应用程序运行时添加一些新角色。 – Drakmail 2013-03-16 19:13:23

+0

经过一番沉思之后,我希望使用设计模式字段中存储的cancan和序列化角色数组。只是因为不需要角色权限的运行时管理:) – Drakmail 2013-03-16 20:20:11

回答

1

定义能力继Zippie的问题,我建议你去黄灿灿的,但你也可以用它一起进行身份验证。看到以下链接,你会发现有用的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?在你的控制器创建您必要的过滤器。

1

见制订用户认证,你可以在那里定义你的角色:

https://github.com/plataformatec/devise 

,甚至更好,用康康舞轻松地结合起来:

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

你可以试试康康舞的宝石,它功能强大

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 
+0

是的,cancan是一个很好的解决方案,但我需要dynamic(在运行时)管理角色。 – Drakmail 2013-03-16 19:10:00

相关问题