In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-12 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)05/31 Report--
This article is about how to use mongoose and bcrypt to achieve a user password encryption function, the editor feels very practical, so share with you to learn, I hope you can get something after reading this article, say no more, follow the editor to have a look.
Use npm to install
Npm install-save bcrypt
User model
Let's create the schema of the code user user. The user name cannot be duplicated.
Var mongoose = require ('mongoose'), Schema = mongoose.Schema, bcrypt = require (' bcrypt'); var UserSchema = new Schema ({username: {type: String, required: true, index: {unique: true}}, password: {type: String, required: true}}); module.exports = mongoose.model ('User', UserSchema)
Encrypt
The next addition to the user model is the Mongoose middleware, which uses pre front hooks to automatically change the password to hash before the password is saved. The detailed code is as follows
Let SALT_WORK_FACTOR = 5UserSchema.pre ('save', function (next) {var user = this; / / generate password hash when the password is changed (or a new password) if (! user.isModified (' password')) return next (); / / generate a salt bcrypt.genSalt (SALT_WORK_FACTOR, function (err, salt) {if (err) return next (err)) / / generate new hash bcrypt.hash with salt (user.password, salt, function (err, hash) {if (err) return next (err); / / overwrite plaintext password user.password = hash; next ();}) with hash;});})
In node.bcrypt.js, SALT_WORK_FACTOR defaults to 10, which is set to 5
Verification
After encryption, the original password text is replaced with ciphertext. We cannot decrypt it. We can only compare the re-passed password with the encrypted password saved in the database through the compare method of bcrypt. If there is a match, the login is successful.
UserSchema.methods.comparePassword = function (candidatePassword, cb) {bcrypt.compare (candidatePassword, this.password, function (err, isMatch) {if (err) return cb (err); cb (null, isMatch);};}
String the above steps together, and the complete code is as follows
Var mongoose = require ('mongoose'), Schema = mongoose.Schema, bcrypt = require (' bcrypt'), SALT_WORK_FACTOR = 5 UserSchema = new Schema ({username: {type: String, required: true, index: {unique: true}}, password: {type: String, required: true}}); UserSchema.pre ('save', function (next) {var user = this; / only hash the password if it has been modified (or is new) if (! user.isModified (' password')) return next () / generate a salt bcrypt.genSalt (SALT_WORK_FACTOR, function (err, salt) {if (err) return next (err); / / hash the password using our new salt bcrypt.hash (user.password, salt, function (err, hash) {if (err) return next (err); / / override the cleartext password with the hashed one user.password = hash; next ();});}) UserSchema.methods.comparePassword = function (candidatePassword, cb) {bcrypt.compare (candidatePassword, this.password, function (err, isMatch) {if (err) return cb (err); cb (null, isMatch);});}; module.exports = mongoose.model ('User', UserSchema)
test
Save the above code as user-model.js, and then run the following code to actually test
Var mongoose = require ('mongoose'), User = require ('. / user-model'); var connStr = 'mongodb://localhost:27017/mongoose-bcrypt-test';mongoose.connect (connStr, function (err) {if (err) throw err; console.log (' Successfully connected to MongoDB');}); / / create a user a new uservar testUser = new User ({username: 'jmar777', password:' Password123'}); / / save user to databasetestUser.save (function (err) {if (err) throw err) / fetch user and test password verification User.findOne ({username: 'jmar777'}, function (err, user) {if (err) throw err; / / test a matching password user.comparePassword (' Password123', function (err, isMatch) {if (err) throw err; console.log ('Password123:', isMatch); / / > Password123: true}); / / test a failing password user.comparePassword (' 123 passwordbacks, function (err, isMatch) {if (err) throw err Console.log ('123 password isMatch); / /-> 123Password: false});});})
Enter the following data in the console:
The database data is as follows:
The above is how to use mongoose and bcrypt to achieve a user password encryption function, the editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.