Add password hashing

This commit is contained in:
Adrian Obelmejias
2016-02-11 17:55:16 -05:00
parent de1bd615fa
commit 35fc841fc7
2 changed files with 35 additions and 1 deletions
+1
View File
@@ -23,6 +23,7 @@
"babel-polyfill": "^6.5.0",
"babel-preset-es2015": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"bcrypt": "^0.8.5",
"jsonwebtoken": "^5.5.4",
"koa": "^2.0.0-alpha.3",
"koa-bodyparser": "^2.0.1",
+34 -1
View File
@@ -1,10 +1,43 @@
import mongoose from 'mongoose'
import bcrypt from 'bcrypt'
const User = new mongoose.Schema({
type: { type: String, default: 'User' },
name: { type: String },
username: { type: String, required: true, unique: true },
password: { type: String, required: true }
password: { type: String, required: true },
salt: { type: String, required: true }
})
User.pre('save', function(next) {
const user = this
if(!user.isModified('password')) {
return next()
}
bcrypt.genSalt(10, (err, salt) => {
if(err) { return next(err) }
bcrypt.hash(user.password, salt, (err, hash) => {
if(err) { return next(err) }
user.password = hash
next()
})
})
})
User.methods.validatePassword = function(password) {
const user = this
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, isMatch) => {
if(err) { return reject(err) }
resolve(isMatch)
});
})
};
export default mongoose.model('user', User)