2016-05-13 22:04:16 +02:00
|
|
|
import mongoose from 'mongoose';
|
|
|
|
const Schema = mongoose.Schema;
|
2016-06-09 22:28:21 +02:00
|
|
|
const bcrypt = require('bcrypt-nodejs');
|
2016-05-13 22:04:16 +02:00
|
|
|
|
|
|
|
const userSchema = new Schema({
|
2016-06-09 02:52:59 +02:00
|
|
|
name: { type: String, default: '' },
|
|
|
|
username: { type: String, required: true, unique: true},
|
|
|
|
password: { type: String },
|
|
|
|
github: { type: String },
|
|
|
|
email: { type: String, unique: true },
|
2016-05-17 21:50:37 +02:00
|
|
|
tokens: Array,
|
2016-05-13 22:04:16 +02:00
|
|
|
admin: { type: Boolean, default: false }
|
2016-05-17 21:50:37 +02: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 22:04:16 +02:00
|
|
|
});
|
|
|
|
|
2016-05-17 21:50:37 +02: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 22:04:16 +02:00
|
|
|
export default mongoose.model('User', userSchema);
|