繁体   English   中英

使用bcrypt在nodejs中进行密码加密

[英]password encryption in nodejs with bcrypt

对于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();
        });
    });
});

Package 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(); 被评估为假,因此其余代码未执行

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM