2016-05-13 20:04:16 +00:00
|
|
|
import mongoose from 'mongoose';
|
|
|
|
const Schema = mongoose.Schema;
|
|
|
|
|
|
|
|
const userSchema = new Schema({
|
|
|
|
name: { type: 'String' },
|
|
|
|
username: { type: 'String', required: true, unique: true},
|
|
|
|
password: { type: 'String' },
|
2016-05-17 19:50:37 +00:00
|
|
|
github: { type: 'String' },
|
|
|
|
email: { type: 'String', unique: true },
|
|
|
|
tokens: Array,
|
2016-05-13 20:04:16 +00:00
|
|
|
admin: { type: Boolean, default: false }
|
2016-05-17 19:50:37 +00:00
|
|
|
}, {timestamps: true});
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Password hash middleware.
|
|
|
|
*/
|
|
|
|
userSchema.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, null, (err, hash) => {
|
|
|
|
if (err) { return next(err); }
|
|
|
|
user.password = hash;
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
});
|
2016-05-13 20:04:16 +00:00
|
|
|
});
|
|
|
|
|
2016-05-17 19:50:37 +00:00
|
|
|
/**
|
|
|
|
* Helper method for validating user's password.
|
|
|
|
*/
|
|
|
|
userSchema.methods.comparePassword = function (candidatePassword, cb) {
|
|
|
|
bcrypt.compare(candidatePassword, this.password, (err, isMatch) => {
|
|
|
|
cb(err, isMatch);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2016-05-13 20:04:16 +00:00
|
|
|
export default mongoose.model('User', userSchema);
|