78 lines
1.8 KiB
JavaScript
Raw Normal View History

var bcrypt = require('bcrypt-nodejs');
2014-02-03 17:50:47 -05:00
var crypto = require('crypto');
2014-11-08 20:42:48 -08:00
var mongoose = require('mongoose');
2013-11-15 11:13:21 -05:00
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, lowercase: true },
password: String,
2013-12-05 23:46:47 -05:00
2014-10-15 13:18:25 -07:00
facebook: String,
twitter: String,
2014-10-15 13:18:25 -07:00
google: String,
github: String,
2014-04-22 15:00:27 -04:00
instagram: String,
linkedin: String,
tokens: Array,
challengesCompleted: { type: Array, default: [] },
2013-12-05 23:46:47 -05:00
profile: {
name: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
2014-10-13 18:00:37 -07:00
picture: { type: String, default: '' },
username: { type: String, default: '' }
2014-02-17 10:00:43 -08:00
},
resetPasswordToken: String,
resetPasswordExpires: Date
});
/**
2014-11-08 20:42:48 -08:00
* Password hashing Mongoose middleware.
*/
userSchema.pre('save', function(next) {
var user = this;
2014-11-08 20:42:48 -08:00
if (!user.isModified('password')) { return next(); }
bcrypt.genSalt(5, function(err, salt) {
2014-11-08 20:42:48 -08:00
if (err) { return next(err); }
bcrypt.hash(user.password, salt, null, function(err, hash) {
2014-11-08 20:42:48 -08:00
if (err) { return next(err); }
user.password = hash;
next();
});
});
});
/**
2014-11-08 20:42:48 -08:00
* Helper method for validationg user's password.
*/
userSchema.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
2014-11-08 20:42:48 -08:00
if (err) { return cb(err); }
cb(null, isMatch);
});
};
2014-02-03 18:03:12 -05:00
/**
2014-11-08 20:42:48 -08:00
* Helper method for getting user's gravatar.
2014-02-03 18:03:12 -05:00
*/
2014-05-02 16:16:44 -04:00
userSchema.methods.gravatar = function(size) {
2014-11-08 20:42:48 -08:00
if (!size) { size = 200; }
2014-02-14 00:14:21 -05:00
2014-02-14 10:54:03 -05:00
if (!this.email) {
2014-05-02 16:16:44 -04:00
return 'https://gravatar.com/avatar/?s=' + size + '&d=retro';
2014-02-14 00:14:21 -05:00
}
2014-05-02 16:16:44 -04:00
var md5 = crypto.createHash('md5').update(this.email).digest('hex');
return 'https://gravatar.com/avatar/' + md5 + '?s=' + size + '&d=retro';
2014-02-03 17:50:47 -05:00
};
module.exports = mongoose.model('User', userSchema);