freeCodeCamp/models/User.js

78 lines
1.9 KiB
JavaScript
Raw Normal View History

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