rails--bcrypt对密码加密

一、引入gem包

gem 'bcrypt',  '3.1.11' #不一定要指定版本号,最好指定合适的 然后执行bundle install

二、用户需要有password_digest属性

rails generate migration add_password_digest_to_users password_digest:string

三、用户需要添加has_secure_password方法

该方法会给user添加两个虚拟属性password和password_confirmation,且创建user的时候会执行存在性验证和匹配验证

并且获得authenticate方法(根据密码验证),如果密码正确,返回对应的用户对象,否则返回false

class User < ApplicationRecord
    ...
    ...
    has_secure_password
end

四、给密码添加合适的长度验证

    has_secure_password
    validates :password, presence: true, length: { minimum: 6 }

五、创建并验证用户

User.create(email: "[email protected]", password: "abcdef", password_confirmation: "abcdef") #如果这两个属性不一致将不能创建,此处假设user有email属性
#验证
user = User.find_by(email: "[email protected]")

user.authenticate("not the right password") # => false
user.authenticate("abcdef") # => true

猜你喜欢

转载自www.cnblogs.com/ltns-hhyb/p/9085365.html
今日推荐