【问题标题】:How should i implement authentication/authorization with multiple models using Rails?我应该如何使用 Rails 实现多个模型的身份验证/授权?
【发布时间】:2012-01-18 18:42:56
【问题描述】:

我的应用中有 3 类用户:俱乐部、个人和管理员。每一个都非常不同,这意味着它们几乎不共享任何属性,除了身份验证数据,所以我宁愿使用 3 种不同的模型。另外,我想为所有这些类型的用户启用单一身份验证模型,使用 Authlogic,并使用 CanCan 处理授权。

一开始我是这么想的。

class User < ActiveRecord::Base
 # This class has the email and password in order to be authenticated with Authlogic
end

每一个我都会拥有

class Club < User end
class Admin < User end

但随后用户表将被其他类型用户的所有列弄乱,并且它们将保持为空。

另一种选择是

class User < ActiveRecord::Base
 # This class has the email and password in order to be authenticated with Authlogic
 belongs_to :role, :polymorphic => true
end

对于每种类型的用户,都会分配一个角色。问题是访问该方法的属性类似于user.role.logo。我认为解决这个问题的一种方法是使用委托,但我仍然不知道这是否是最佳选择。

问题是,您建议我如何实施?最好的方法是什么?

【问题讨论】:

  • 您真的需要 3 种不同的模型吗?我的意思是除了授权之外的其他原因......
  • 原因是这3种用户彼此非常不同,所以我不喜欢数据库中有一堆NULL字段的单个模型。

标签: ruby-on-rails authentication


【解决方案1】:

就像你建议的那样,我会创建一个用户模型来处理身份验证。然后,您可以在用户模型和您的角色模型之间创建一对一的多态关系。您的用户模型必须包含 role_type(字符串)和 role_id(整数)属性。

用户.rb

class User < ActiveRecord::Base
  belongs_to :role, :polymorphic => true
end

Admin.rb

class Admin < ActiveRecord::Base
  has_one :role
end

您可以测试用户角色的类别并访问其属性。例如:

User.first.role.is_a? Admin
=> true
User.first.role.last_name
=> "Smith"

【讨论】:

    【解决方案2】:

    我认为您正在尝试实现基于角色的授权。看看 wiki 页面 康康。

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

    【讨论】:

      猜你喜欢
      • 2016-10-02
      • 1970-01-01
      • 2022-01-21
      • 2017-12-10
      • 1970-01-01
      • 2022-12-11
      • 1970-01-01
      • 2011-05-28
      • 1970-01-01
      相关资源
      最近更新 更多