Skip to content

Commit

Permalink
Hash password before saving user
Browse files Browse the repository at this point in the history
  • Loading branch information
DeadlockDruid committed Sep 25, 2018
1 parent 197f512 commit 4b2285e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"author": "",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.3",
"crypto-js": "^3.1.9-1",
"expect": "^23.6.0",
Expand Down
2 changes: 1 addition & 1 deletion server/middleware/authenticate.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { User } = require("./../models/user");

var authenticate = (res, res, next) => {
var authenticate = (req, res, next) => {
var token = req.header('x-auth');

User.findByToken(token).then((user) => {
Expand Down
17 changes: 17 additions & 0 deletions server/models/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const bcrypt = require('bcryptjs');

var UserSchema = new mongoose.Schema({
email: {
Expand Down Expand Up @@ -73,6 +74,22 @@ UserSchema.statics.findByToken = function (token) {
});
};

UserSchema.pre('save', function(next) {
var user = this;

if (user.isModified('password')) {
bcrypt.genSalt(10, (err, salt) =>{
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
next();
});
});
} else {
next();
}

});

var User = mongoose.model('User', UserSchema);

module.exports = { User };

0 comments on commit 4b2285e

Please sign in to comment.