Rails 3.1 中的授权:CanCan、CanTango、declarative_authorization? [英] Authorization in Rails 3.1 : CanCan, CanTango, declarative_authorization?

查看:32
本文介绍了Rails 3.1 中的授权:CanCan、CanTango、declarative_authorization?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看过 declarative_authorization、CanCan 和 CanTango.他们都擅长向应用程序添加授权,但我想知道如何向模型的特定实例添加授权,即一个人可以在一个项目中拥有管理访问权限并且只有有限(阅读少于管理:有限更新等)在另一个.

I have looked at declarative_authorization, CanCan, and CanTango. They all are good in adding authorization to the application but I was wondering how does one add authorization to specific instance of a model i.e. a person can have a manage access in one project and only limited (read less than manage: limited update, etc) in another.

你能有更好的方法吗?如果我的问题听起来太琐碎,我深表歉意.这可能是因为我是 RoR 的新手.

Could you please a better way? Apologies if my question sounds too trivial. It could be because I am new to RoR.

谢谢,约翰

推荐答案

我知道 CanCan 和 declarative_authorization,并且我对两者都实现了基于角色的授权,我推荐 CanCan.只有我的两分钱.

As I know CanCan and declarative_authorization, and I implemented role-based authorizations with both, I recommend CanCan. Just my two cents.

示例(未经测试,很遗憾我无法在这里测试,也无法访问我的代码)

Example (untested, unfortunately I cannot test here and I have no access to my code)

假设我们有一个这样的结构:

So let's say we have a structure like this:

class User < ActiveRecord::Base
  belongs_to :role
end

class Role < ActiveRecord::Base
  has_many :users

  # attributes: project_read, project_create, project_update
end

然后,CanCan 可能看起来像这样:

Then, CanCan could look like this:

class Ability
  include CanCan::Ability

  def initialize(user)
    @user = user
    @role = user.role

    # user can see a project if he has project_read => true in his role
    can :read, Project if role.project_read? 

    # same, but with create
    can :create, Project if role.project_create?

    # can do everything with projects if he is an admin
    can :manage, Project if user.admin?
  end

end

您可以在 github 上的 CanCan wiki 中找到您需要的所有信息.个人推荐阅读:

You can find all information you need in the CanCan wiki on github. Personal recommendation to read:

基本上,您只需要扩展上面的示例以通过您的关系包含您的角色.为简单起见,您还可以在 ability.rb 中创建其他辅助方法.

Basically you just need to extend the example above to include your roles through your relations. To keep it simple, you can also create additional helper methods in ability.rb.

你可能会接受的主要警告(至少我是这样):在你定义用户不能之前,确保你的用户可以用模型做一些事情>.否则你会沮丧地坐在那里想但是为什么?我从来没有写过用户不能.".是的.但是你也从来没有明确写过他可以......

The main mean caveat you may fall for (at least I do): Make sure your user can do something with a model before you define what the user can't. Otherwise you'll sit there frustrated and think "but why? I never wrote the user can't.". Yeah. But you also never explicitly wrote that he can...

这篇关于Rails 3.1 中的授权:CanCan、CanTango、declarative_authorization?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆