简体   繁体   中英

password encryption in nodejs with bcrypt

am really new to MERN stack development. I have this problem while using bcrypt, I just can't seem to get the code to work. Here is the code. Kindly help. I am trying to encrypt my passwords with 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();
        });
    });
});

the Package json is below

{
  "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"
  }
}

The password is still getting saved in the database without encryption.

I solved the problem, if(!user.isModified('password')) return next(); was being evaluated to falsey hence the rest of the code was not being executed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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