使用bcrypt在nodejs中进行密码加密
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用bcrypt在nodejs中进行密码加密相关的知识,希望对你有一定的参考价值。
我是MERN堆栈开发的新手。我在使用bcrypt时遇到这个问题,我似乎无法让代码工作。这是代码。请帮助。我正在尝试使用bcrypt加密我的密码
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
var SALT_WORK_FACTOR = 10;
const userSchema = new Schema({
name: String,
email: String,
phoneNumber: Number,
username: String,
password: String,
googleId: String,
credits: {type: Number, default: 0}
});
// this creates an instance of an object to be sent to the database
mongoose.model('users', userSchema);
userSchema.pre('save', function(next){
var user = this;
if (!user.isModified('password')) return next();
bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt){
if(err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash){
if(err) return next(err);
user.password = hash;
next();
});
});
});
包json在下面
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"engines": {
"node": "8.8.1",
"npm": "5.0.3"
},
"scripts": {
"start": "node index.js",
"server": "nodemon index.js",
"client": "npm run start --prefix client",
"dev": "concurrently "npm run server" "npm run client"",
"heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix client && npm run build --prefix client"
},
"author": "David Mbwana",
"license": "ISC",
"dependencies": {
"axios": "^0.17.1",
"bcrypt": "^1.0.3",
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.2",
"concurrently": "^3.5.1",
"connect-flash": "^0.1.1",
"cookie-session": "^2.0.0-beta.3",
"express": "^4.16.2",
"express-validator": "^4.3.0",
"mongoose": "^4.13.6",
"nodemon": "^1.12.5",
"passport": "^0.4.0",
"passport-google-oauth20": "^1.0.0",
"passport-http": "^0.3.0",
"passport-local": "^1.0.0",
"path": "^0.12.7",
"redux-thunk": "^2.2.0",
"stripe": "^5.4.0"
}
}
密码仍然在没有加密的情况下保存在数据库中。
答案
我解决了这个问题,if(!user.isModified('password')) return next();
被评估为falsey因此其余的代码没有被执行
以上是关于使用bcrypt在nodejs中进行密码加密的主要内容,如果未能解决你的问题,请参考以下文章