HackMD/lib/user.js

110 lines
2.7 KiB
JavaScript
Raw Normal View History

2015-05-04 07:53:29 +00:00
//user
//external modules
var mongoose = require('mongoose');
var md5 = require("md5");
2015-05-04 07:53:29 +00:00
//core
var config = require("../config.js");
2015-07-01 16:10:20 +00:00
var logger = require("./logger.js");
2015-05-04 07:53:29 +00:00
// create a user model
var model = mongoose.model('user', {
id: String,
profile: String,
history: String,
created: Date
});
//public
var user = {
model: model,
findUser: findUser,
newUser: newUser,
findOrNewUser: findOrNewUser,
getUserCount: getUserCount,
parsePhotoByProfile: parsePhotoByProfile
2015-05-04 07:53:29 +00:00
};
function parsePhotoByProfile(profile) {
var photo = null;
switch (profile.provider) {
case "facebook":
photo = 'https://graph.facebook.com/' + profile.id + '/picture';
break;
case "twitter":
photo = profile.photos[0].value;
break;
case "github":
photo = 'https://avatars.githubusercontent.com/u/' + profile.id + '?s=48';
break;
case "dropbox":
//no image api provided, use gravatar
photo = 'https://www.gravatar.com/avatar/' + md5(profile.emails[0].value);
break;
}
return photo;
}
2015-05-04 07:53:29 +00:00
function getUserCount(callback) {
model.count(function(err, count){
if(err) callback(err, null);
else callback(null, count);
});
}
function findUser(id, callback) {
var rule = {};
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if (checkForHexRegExp.test(id))
rule._id = id;
else
rule.id = id;
model.findOne(rule, function (err, user) {
2015-05-04 07:53:29 +00:00
if (err) {
2015-07-01 16:10:20 +00:00
logger.error('find user failed: ' + err);
2015-05-04 07:53:29 +00:00
callback(err, null);
}
2015-05-15 04:58:13 +00:00
if (!err && user) {
2015-05-04 07:53:29 +00:00
callback(null, user);
} else {
2015-07-01 16:10:20 +00:00
logger.error('find user failed: ' + err);
2015-05-04 07:53:29 +00:00
callback(err, null);
};
});
}
function newUser(id, profile, callback) {
var user = new model({
id: id,
profile: JSON.stringify(profile),
created: Date.now()
});
user.save(function (err) {
if (err) {
2015-07-01 16:10:20 +00:00
logger.error('new user failed: ' + err);
2015-05-04 07:53:29 +00:00
callback(err, null);
} else {
2015-07-01 16:10:20 +00:00
logger.info("new user success: " + user.id);
2015-05-04 07:53:29 +00:00
callback(null, user);
};
});
}
function findOrNewUser(id, profile, callback) {
findUser(id, function(err, user) {
2015-05-15 04:58:13 +00:00
if(err || !user) {
2015-05-04 07:53:29 +00:00
newUser(id, profile, function(err, user) {
if(err) {
2015-07-01 16:10:20 +00:00
logger.error('find or new user failed: ' + err);
2015-05-04 07:53:29 +00:00
callback(err, null);
} else {
callback(null, user);
}
});
} else {
callback(null, user);
}
});
}
module.exports = user;