freeCodeCamp/models/User.js

67 lines
1.6 KiB
JavaScript
Raw Normal View History

var mongoose = require('mongoose'),
2013-11-15 16:13:21 +00:00
bcrypt = require('bcrypt');
var userSchema = new mongoose.Schema({
username: { type: String, unique: true },
email: String,
name: String,
password: String,
tokens: {
google: String,
facebook: String,
foursquare: String,
twitter: String,
github: String
},
provider: String,
facebook: String,
google: String,
isAdmin: Boolean,
});
userSchema.path('password').validate(function(password) {
if (this.provider) return true;
return password.length;
}, 'Password cannot be blank');
userSchema.path('email').validate(function(email) {
if (this.provider) return true;
return email.length;
}, 'Email cannot be blank');
userSchema.path('firstName').validate(function(firstName) {
if (this.provider) return true;
return firstName.length;
}, 'First Name cannot be blank');
userSchema.path('lastName').validate(function(lastName) {
if (this.provider) return true;
return lastName.length;
}, 'Last Name cannot be blank');
userSchema.pre('save', function(next) {
var user = this;
2013-11-18 19:37:01 +00:00
var SALT_FACTOR = 5;
if (!user.isModified('password')) return next();
2013-11-18 19:37:01 +00:00
bcrypt.genSalt(SALT_FACTOR, function(err, salt) {
if (err) return next(err);
bcrypt.hash(user.password, salt, function(err, hash) {
if (err) return next(err);
user.password = hash;
next();
});
});
});
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if(err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', userSchema);