溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用mongoose和bcrypt怎么實現(xiàn)一個用戶密碼加密功能

發(fā)布時間:2021-04-09 15:56:00 來源:億速云 閱讀:246 作者:Leah 欄目:MongoDB數(shù)據(jù)庫

本篇文章給大家分享的是有關(guān)使用mongoose和bcrypt怎么實現(xiàn)一個用戶密碼加密功能,小編覺得挺實用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

使用npm安裝即可

npm install --save bcrypt

用戶模型

下面來創(chuàng)建代碼用戶user的schema,用戶名不能重復(fù)

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);

加密

下面加入用戶模型的是Mongoose的中間件,該中間件使用pre前置鉤子,在密碼保存之前,自動地把密碼變成hash。詳細(xì)代碼如下

let SALT_WORK_FACTOR = 5
UserSchema.pre('save', function(next) {
 var user = this;
 //產(chǎn)生密碼hash當(dāng)密碼有更改的時候(或者是新密碼)
 if (!user.isModified('password')) return next();
 // 產(chǎn)生一個salt
 bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) {
  if (err) return next(err);
  // 結(jié)合salt產(chǎn)生新的hash
  bcrypt.hash(user.password, salt, function(err, hash) {
   if (err) return next(err);
   // 使用hash覆蓋明文密碼
   user.password = hash;
   next();
  });
 });
});

在node.bcrypt.js中SALT_WORK_FACTOR默認(rèn)使用的是10,這里設(shè)置為5

驗證

加密之后,密碼原文被替換為密文了。我們無法解密,只能通過bcrypt的compare方法,對再次傳入的密碼和數(shù)據(jù)庫中保存的加密后的密碼進(jìn)行比較,如果匹配,則登錄成功

UserSchema.methods.comparePassword = function(candidatePassword, cb) {
 bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
  if (err) return cb(err);
  cb(null, isMatch);
 });
};

把上面的幾個步驟串在一起,完整代碼如下

var mongoose = require('mongoose'),
 Schema = mongoose.Schema,
 bcrypt = require('bcrypt'),
 SALT_WORK_FACTOR = 5;
var 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);

測試

把上面的代碼保存成user-model.js,然后運行下面代碼來實際測試

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 user
var testUser = new User({
 username: 'jmar777',
 password: 'Password123'
});
// save user to database
testUser.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('123Password', function(err, isMatch) {
   if (err) throw err;
   console.log('123Password:', isMatch); // -> 123Password: false
  });
 });
});

控制臺中輸入如下數(shù)據(jù):

使用mongoose和bcrypt怎么實現(xiàn)一個用戶密碼加密功能

數(shù)據(jù)庫數(shù)據(jù)如下:

使用mongoose和bcrypt怎么實現(xiàn)一個用戶密碼加密功能

以上就是使用mongoose和bcrypt怎么實現(xiàn)一個用戶密碼加密功能,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI