首页 > 其他 > 详细

rails--bcrypt对密码加密

时间:2018-05-24 22:36:46      阅读:230      评论:0      收藏:0      [点我收藏+]

一、引入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: "abc@a.com", password: "abcdef", password_confirmation: "abcdef") #如果这两个属性不一致将不能创建,此处假设user有email属性
#验证
user = User.find_by(email: "abc@a.com")

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

 

rails--bcrypt对密码加密

原文:https://www.cnblogs.com/ltns-hhyb/p/9085365.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!