freeCodeCamp/models/User.js

69 lines
1.8 KiB
JavaScript
Raw Normal View History

var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
2014-02-03 22:50:47 +00:00
var crypto = require('crypto');
2013-11-15 16:13:21 +00:00
var userSchema = new mongoose.Schema({
email: { type: String, unique: true },
password: String,
2013-12-06 04:46:47 +00:00
2014-01-07 21:33:48 +00:00
facebook: { type: String, unique: true, sparse: true },
twitter: { type: String, unique: true, sparse: true },
google: { type: String, unique: true, sparse: true },
github: { type: String, unique: true, sparse: true },
tokens: Array,
2013-12-06 04:46:47 +00:00
profile: {
name: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
picture: { type: String, default: '' }
}
});
/**
* Hash the password for security.
*/
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, null, 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);
});
};
2014-02-03 23:03:12 +00:00
/**
* Get a URL to a user's Gravatar email.
2014-02-03 23:03:12 +00:00
*/
userSchema.methods.gravatar = function(size, defaults) {
2014-02-03 23:03:12 +00:00
if (!size) size = 200;
if (!defaults) defaults = 'retro';
2014-02-14 05:14:21 +00:00
2014-02-14 15:54:03 +00:00
if (!this.email) {
2014-02-14 05:14:21 +00:00
return 'https://gravatar.com/avatar/?s=' + size + '&d=' + defaults;
}
2014-02-07 14:54:03 +00:00
var md5 = crypto.createHash('md5').update(this.email);
return 'https://gravatar.com/avatar/' + md5.digest('hex').toString() + '?s=' + size + '&d=' + defaults;
2014-02-03 22:50:47 +00:00
};
module.exports = mongoose.model('User', userSchema);