2016-02-11 16:20:48 -05:00
|
|
|
import mongoose from 'mongoose'
|
2016-02-11 17:55:16 -05:00
|
|
|
import bcrypt from 'bcrypt'
|
2016-02-11 16:20:48 -05:00
|
|
|
|
|
|
|
|
const User = new mongoose.Schema({
|
|
|
|
|
type: { type: String, default: 'User' },
|
|
|
|
|
name: { type: String },
|
|
|
|
|
username: { type: String, required: true, unique: true },
|
2016-02-11 17:55:16 -05:00
|
|
|
password: { type: String, required: true },
|
2016-02-11 19:01:15 -05:00
|
|
|
salt: { type: String }
|
2016-02-11 16:20:48 -05:00
|
|
|
})
|
|
|
|
|
|
2016-02-11 19:20:45 -05:00
|
|
|
User.pre('save', function preSave(next) {
|
2016-02-11 17:55:16 -05:00
|
|
|
const user = this
|
|
|
|
|
|
2016-02-11 19:20:45 -05:00
|
|
|
if (!user.isModified('password')) {
|
2016-02-11 17:55:16 -05:00
|
|
|
return next()
|
|
|
|
|
}
|
|
|
|
|
|
2016-02-11 19:20:45 -05:00
|
|
|
new Promise((resolve, reject) => {
|
|
|
|
|
bcrypt.genSalt(10, (err, salt) => {
|
|
|
|
|
if (err) { return reject(err) }
|
2016-02-11 19:36:17 -05:00
|
|
|
resolve(salt)
|
2016-02-11 19:20:45 -05:00
|
|
|
})
|
|
|
|
|
})
|
|
|
|
|
.then(salt => {
|
2016-02-11 17:55:16 -05:00
|
|
|
bcrypt.hash(user.password, salt, (err, hash) => {
|
2016-02-11 19:20:45 -05:00
|
|
|
if (err) { throw new Error(err) }
|
2016-02-11 17:55:16 -05:00
|
|
|
|
|
|
|
|
user.password = hash
|
2016-02-11 19:01:15 -05:00
|
|
|
user.salt = salt
|
2016-02-11 19:36:17 -05:00
|
|
|
|
|
|
|
|
next(null)
|
2016-02-11 17:55:16 -05:00
|
|
|
})
|
|
|
|
|
})
|
2016-02-11 19:36:17 -05:00
|
|
|
.catch(err => next(err))
|
2016-02-11 17:55:16 -05:00
|
|
|
})
|
|
|
|
|
|
2016-02-11 19:20:45 -05:00
|
|
|
User.methods.validatePassword = function validatePassword(password) {
|
2016-02-11 17:55:16 -05:00
|
|
|
const user = this
|
|
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
bcrypt.compare(password, user.password, (err, isMatch) => {
|
2016-02-11 19:20:45 -05:00
|
|
|
if (err) { return reject(err) }
|
2016-02-11 17:55:16 -05:00
|
|
|
|
|
|
|
|
resolve(isMatch)
|
2016-02-11 19:20:45 -05:00
|
|
|
})
|
2016-02-11 17:55:16 -05:00
|
|
|
})
|
2016-02-11 19:20:45 -05:00
|
|
|
}
|
2016-02-11 17:55:16 -05:00
|
|
|
|
2016-02-11 16:20:48 -05:00
|
|
|
export default mongoose.model('user', User)
|