【问题标题】:Devise - Authentication of a User using a non-unique field设计 - 使用非唯一字段对用户进行身份验证
【发布时间】:2019-06-04 23:54:54
【问题描述】:

目前,我们根据用户的电子邮件字段对用户进行身份验证。然而,这个领域并不是唯一的。主要问题是我们应该只允许基于用户表上的 user_type 字段访问用户。如果有 2 个条目具有相同的 Email 但不同的 user_type,我们希望 Devise 尝试使用 user_type = 'Admin' 的条目登录。

有没有办法将设计身份验证限制为仅查看具有 user_type = 'Admin' 的用户而不查看其他用户?

【问题讨论】:

    标签: authentication devise


    【解决方案1】:

    我找到了 2 个解决问题的方法

    我自己想出的第一个方法是简单地创建一个名为 AdminUser 的 User 模型的子类,其默认范围仅允许 user_type = 'admin'

    class AdminUsers < User
      default_scope { where(user_type: 'admin') }
    end
    

    然后我刚刚更新了 routes.rb 文件以使用该模型而不是用户

    devise_for(
      :users,
      class_name: 'AdminUser',
      path:       'auth',
      controllers: {
        sessions: 'authentications',
        passwords: 'passwords'
      }
    )
    

    这很好用。唯一的小事情是,现在 current_user 返回了一个 AdminUser 实例而不是 User。我不能保证这在某些情况下不会引起问题。

    第二个解决方案来自这里:https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign_in-using-their-username-or-email-address

    我添加了这个方法,该方法将一个 Devises 内部方法覆盖到 User 模型中。

    def self.find_for_database_authentication(warden_conditions)
      where(warden_conditions).where("user_type = 'agent'").first
    end
    

    第二种解决方案似乎效果很好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 2021-05-11
      • 1970-01-01
      相关资源
      最近更新 更多