2018-05-03 14:15:57 +00:00
|
|
|
var mongoose = require('mongoose');
|
|
|
|
var Schema = mongoose.Schema;
|
|
|
|
var bcrypt = require('bcrypt-nodejs');
|
|
|
|
|
|
|
|
var UserSchema = new Schema({
|
2018-06-07 06:44:15 +00:00
|
|
|
|
|
|
|
name: String,
|
|
|
|
userid: String,
|
|
|
|
updated_at: { type: Date, default: Date.now },
|
|
|
|
username: {
|
|
|
|
type: String,
|
|
|
|
unique: true,
|
|
|
|
required: true
|
|
|
|
},
|
|
|
|
password: {
|
|
|
|
type: String,
|
|
|
|
required: false
|
2018-06-08 02:57:29 +00:00
|
|
|
},
|
|
|
|
social: {
|
|
|
|
type: Boolean,
|
|
|
|
required: false
|
2018-06-07 06:44:15 +00:00
|
|
|
}
|
2018-05-03 14:15:57 +00:00
|
|
|
});
|
|
|
|
|
2018-06-07 06:44:15 +00:00
|
|
|
// UserSchema.statics.findOrCreate = function findOneOrCreate(condition, callback) {
|
|
|
|
// console.log(JSON.stringify(condition));
|
|
|
|
// const self = this;
|
|
|
|
// self.findOne(condition, (err, result) => {
|
|
|
|
// return result ? callback(err, result) : self.create(condition, (err, result) => {
|
|
|
|
// return callback(err, result)
|
|
|
|
// })
|
|
|
|
// })
|
|
|
|
// };
|
|
|
|
|
|
|
|
|
|
|
|
UserSchema.statics.findOneOrCreate = function(displayName, cb){
|
|
|
|
console.log('findOneOrCreate'+displayName);
|
|
|
|
return (displayName ? this.find({name: displayName}, cb) : this.findOne({}, cb)).then(page => page ? page : this.create({}, cb))
|
|
|
|
};
|
2018-05-30 21:51:57 +00:00
|
|
|
|
2018-05-03 14:15:57 +00:00
|
|
|
UserSchema.pre('save', function (next) {
|
|
|
|
var user = this;
|
|
|
|
if (this.isModified('password') || this.isNew) {
|
|
|
|
bcrypt.genSalt(10, function (err, salt) {
|
|
|
|
if (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
|
|
|
bcrypt.hash(user.password, salt, null, function (err, hash) {
|
|
|
|
if (err) {
|
|
|
|
return next(err);
|
|
|
|
}
|
|
|
|
user.password = hash;
|
|
|
|
next();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
return next();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
UserSchema.methods.comparePassword = function (passw, cb) {
|
|
|
|
bcrypt.compare(passw, this.password, function (err, isMatch) {
|
|
|
|
if (err) {
|
|
|
|
return cb(err);
|
|
|
|
}
|
|
|
|
cb(null, isMatch);
|
|
|
|
});
|
|
|
|
};
|
|
|
|
|
2018-06-07 06:44:15 +00:00
|
|
|
module.exports = mongoose.model('User', UserSchema);
|