freeCodeCamp/models/User.js

74 lines
1.7 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({
2013-12-06 04:46:47 +00:00
// Local authentication
username: { type: String, unique: true, sparse: true },
password: String,
2013-12-06 04:46:47 +00:00
// OAuth 2.0 authentication
provider: String,
facebook: String,
twitter: String,
google: String,
github: String,
// Optional profile information
profile: {
name: { type: String, default: '' },
email: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
picture: { type: String, default: 'http://bit.ly/1cppDAL' }
2013-12-06 04:46:47 +00:00
},
// API access tokens
tokens: {
google: String,
facebook: String,
foursquare: String,
twitter: String,
2013-12-07 05:29:57 +00:00
github: String,
tumblr: String
2013-12-06 04:46:47 +00:00
}
});
userSchema.path('password').validate(function(password) {
if (this.provider) return true;
return password.length;
}, 'Password cannot be blank');
userSchema.path('username').validate(function(username) {
if (this.provider) return true;
return username.length;
}, 'Username 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);