2016-05-13 20:04:16 +00:00
|
|
|
import mongoose from 'mongoose';
|
|
|
|
const Schema = mongoose.Schema;
|
2016-06-09 20:28:21 +00:00
|
|
|
const bcrypt = require('bcrypt-nodejs');
|
2016-05-13 20:04:16 +00:00
|
|
|
|
|
|
|
const userSchema = new Schema({
|
2016-06-23 22:29:55 +00:00
|
|
|
name: { type: String, default: '' },
|
2016-06-27 17:09:18 +00:00
|
|
|
username: { type: String, required: true, unique: true },
|
2016-06-23 22:29:55 +00:00
|
|
|
password: { type: String },
|
|
|
|
github: { type: String },
|
|
|
|
email: { type: String, unique: true },
|
|
|
|
tokens: Array,
|
|
|
|
admin: { type: Boolean, default: false }
|
2016-06-27 17:09:18 +00:00
|
|
|
}, { timestamps: true });
|
2016-05-17 19:50:37 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Password hash middleware.
|
|
|
|
*/
|
2016-06-27 17:09:18 +00:00
|
|
|
userSchema.pre('save', function checkPassword(next) { // eslint-disable-line consistent-return
|
2016-05-17 19:50:37 +00:00
|
|
|
const user = this;
|
|
|
|
if (!user.isModified('password')) { return next(); }
|
2016-06-27 17:09:18 +00:00
|
|
|
bcrypt.genSalt(10, (err, salt) => { // eslint-disable-line consistent-return
|
2016-05-17 19:50:37 +00:00
|
|
|
if (err) { return next(err); }
|
2016-06-27 17:09:18 +00:00
|
|
|
bcrypt.hash(user.password, salt, null, (innerErr, hash) => {
|
|
|
|
if (innerErr) { return next(innerErr); }
|
2016-05-17 19:50:37 +00:00
|
|
|
user.password = hash;
|
2016-06-27 17:09:18 +00:00
|
|
|
return next();
|
2016-05-17 19:50:37 +00:00
|
|
|
});
|
|
|
|
});
|
2016-05-13 20:04:16 +00:00
|
|
|
});
|
|
|
|
|
2016-05-17 19:50:37 +00:00
|
|
|
/**
|
|
|
|
* Helper method for validating user's password.
|
|
|
|
*/
|
2016-06-27 17:09:18 +00:00
|
|
|
userSchema.methods.comparePassword = function comparePassword(candidatePassword, cb) {
|
2016-06-24 22:18:22 +00:00
|
|
|
// userSchema.methods.comparePassword = (candidatePassword, cb) => {
|
2016-05-17 19:50:37 +00:00
|
|
|
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
|
|
|
|
cb(err, isMatch);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2016-06-24 22:18:22 +00:00
|
|
|
export default mongoose.model('User', userSchema);
|