ruby-on-rails - 如何在 Rails 4.2 中使用 has_secure_password 加密密码

标签 ruby-on-rails ruby ruby-on-rails-4 encryption bcrypt-ruby

我有一个 API 并且我安装了下一个 gem

 gem 'bcrypt' 

在我的用户模型中,我具体说明了:

has_secure_password

我的数据库有一个名字的字段

password_digest

当运行播种机时,密码是加密的,但是当尝试用我的方法创建新用户时,密码是正常的,这是我创建新用户的方法

def self.from_auth(data)
    User.where(email: data[:email]).first_or_create do |user|
        user.email = data[:info][:email]
        user.name = data[:info][:name]
        user.provider = data[:info][:provider]
        user.uid = data[:info][:uid]
        user.password_digest = data[:info][:password]
    end
end

谢谢:)

最佳答案

密码未保存为 bcrypt 哈希。

来自 bycrypt 文档

https://github.com/codahale/bcrypt-ruby

require 'bcrypt'

my_password = BCrypt::Password.create("my password")#=> "$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa"

my_password.version              #=> "2a"
my_password.cost                 #=> 10
my_password == "my password"     #=> true
my_password == "not my password" #=> false

my_password = BCrypt::Password.new("$2a$10$vI8aWBnW3fID.ZQ4/zo1G.q1lRps.9cGLcZEiGDMVr5yUP1KUOYTa")
my_password == "my password"     #=> true
my_password == "not my password" #=> false

所以你存储用户密码散列的代码应该是这样的

def self.from_auth(data)
  User.where(email: data[:email]).first_or_create do |user|
    user.email = data[:info][:email]
    user.name = data[:info][:name]
    user.provider = data[:info][:provider]
    user.uid = data[:info][:uid]
    user.password_digest = BCrypt::Password.create(data[:info][:password])
  end
end

然后就可以像文档说的那样测试了 http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html

关于ruby-on-rails - 如何在 Rails 4.2 中使用 has_secure_password 加密密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35383756/

相关文章:

ruby-on-rails - 如何使用选择菜单和 link_to 重定向到另一个页面 - Ruby on Rails

ruby-on-rails - ActiveRecord 'where' 子句使用函数

ruby - 使用 minitest 进行多项测试

ruby-on-rails - Rails Griddler 和对话/电子邮件线程

ruby-on-rails - 文本流到下一页与 Prawn 的标题重叠

ruby-on-rails - rails 3.1 : Why is rails_admin causing `rake asset:precompile` to fail?

ruby - 如何使用 ruby​​ 中的字符串进行多个组合?

ruby - 从派生类方法调用基类方法

mysql - Rails中如何获得两个日期时间列相减的平均值

ruby-on-rails - SimpleCaptcha 图像未加载(无法批量分配 protected 属性)