mongoid - 如何使用 bcrypt 和 mongoid 保护用户密码

标签 mongoid bcrypt bcrypt-ruby

我刚刚开始使用 MongoDB,特别是 Mongoid

当然,我想确保我的用户的密码保持良好和安全,以前我会使用ActiveRecord来完成此操作并使用 bcrypt。我正在寻找一种漂亮、干净、安全、简单的方法来使用 Mongoid 实现同样的事情。

我查看了mongoid-encryptor但我还不太清楚如何使用它。

假设我的简化 User 如下所示,如 mongoid-encryptor 的自述文件中的示例。

class User
  include Mongoid::Document
  include Mongoid::Encryptor
  field :name
  field :password
  encrypts :password
end

在我的 WebApp 中(在本例中使用 Sinatra),我会定义一个帮助器,例如

def login (name, cleartxtpass)
  return User.where(name: name, password: cleartxtpass).first
end
  1. 如何让它使用 bcrypt
  2. 我需要对 cleartxtpass 进行任何预处理吗?或者 Mongoid::Encryptor 会处理这个问题吗?从文档中尚不清楚。

最佳答案

好吧,经过一番挖掘后,我决定不再使用 Mongoid::Encryptor ,而是坚持使用我在使用 ActiveRecord 时尝试和测试的方法来执行这些操作.

现在我的用户看起来像

class User
  include Mongoid::Document
  field :name, type: String
  field :password_hash, type: String
  index({name: 1}, {unique: true, name: 'user_name_index'})

  include BCrypt
  def password
    @password ||= Password.new(password_hash)
  end

  def password=(new_password)
    @password = Password.create(new_password)
    self.password_hash = @password
  end
end

我的身份验证辅助方法看起来像

  def auth_user(username, password)
    user = User.where(name: username).first
    return user if user && user.password == password
    return nil
  end

这真是一种享受。

关于mongoid - 如何使用 bcrypt 和 mongoid 保护用户密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16182340/

相关文章:

ruby-on-rails - 尝试更新用户模型时出现密码问题

node.js - bcrypt 不是 azure 应用服务上的有效 win 32 应用程序

node.js - bcrypt CompareSync 始终返回 false

mysql - Rails 控制台 : User will not save - Stack level too deep

ruby-on-rails - 使用 Mongoid 进行不区分大小写的排序

Mongoid 保存在没有嵌入关系的情况下静默失败

ruby - will_paginate 助手在 sinatra 和 mongoid 中未定义

ruby-on-rails - RSpec:如果未直接引用对象,则expect.to 接收失败

ruby-on-rails - ruby -BCrypt : Specify salt