使用mongoose和bcrypt怎么實現(xiàn)一個用戶密碼加密功能-創(chuàng)新互聯(lián)

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

10年積累的網(wǎng)站設(shè)計、做網(wǎng)站經(jīng)驗,可以快速應(yīng)對客戶對網(wǎng)站的新想法和需求。提供各種問題對應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認識你,你也不認識我。但先網(wǎng)站設(shè)計后付款的網(wǎng)站建設(shè)流程,更有蕪湖縣免費網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。

使用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。詳細代碼如下

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默認使用的是10,這里設(shè)置為5

驗證

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

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)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

當(dāng)前名稱:使用mongoose和bcrypt怎么實現(xiàn)一個用戶密碼加密功能-創(chuàng)新互聯(lián)
標(biāo)題URL:http://www.bm7419.com/article48/dgcshp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站策劃、商城網(wǎng)站網(wǎng)站制作、品牌網(wǎng)站設(shè)計、響應(yīng)式網(wǎng)站、靜態(tài)網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

手機網(wǎng)站建設(shè)