Files
freeCodeCamp/common/models/User-Identity.js

69 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-08-04 14:52:06 -07:00
import debugFactory from 'debug';
2015-08-04 14:52:06 -07:00
const debug = debugFactory('freecc:models:userIdent');
const { defaultProfileImage } = require('../utils/constantStrings.json');
2015-06-11 21:12:47 -07:00
function getFirstImageFromProfile(profile) {
return profile && profile.photos && profile.photos[0] ?
profile.photos[0].value :
null;
}
2015-08-04 14:52:06 -07:00
export default function(UserIdent) {
UserIdent.observe('before save', function(ctx, next) {
2015-06-11 12:13:22 -07:00
var userIdent = ctx.currentInstance || ctx.instance;
if (!userIdent) {
2015-06-11 12:13:22 -07:00
debug('no user identity instance found');
return next();
}
userIdent.user(function(err, user) {
2015-08-04 14:52:06 -07:00
let userChanged = false;
if (err) { return next(err); }
2015-06-11 12:13:22 -07:00
if (!user) {
debug('no user attached to identity!');
return next();
}
2015-08-04 14:52:06 -07:00
const picture = getFirstImageFromProfile(userIdent.profile);
2015-06-11 21:12:47 -07:00
debug('picture', picture, user.picture);
// check if picture was found
// check if user has no picture
// check if user has default picture
// set user.picture from oauth provider
if (
picture &&
(!user.picture || user.picture === defaultProfileImage)
) {
debug('setting user picture');
2015-08-04 14:52:06 -07:00
user.picture = picture;
userChanged = true;
}
// if user is not github cool
// and user signed in with github
// then make them github cool
// and set their username from their github profile.
if (!user.isGithubCool && userIdent.provider === 'github-login') {
debug(`
user isn't github cool yet but signed in with github
lets make them cool!
`);
user.isGithubCool = true;
user.username = userIdent.profile.username.toLowerCase();
userChanged = true;
}
if (userChanged) {
2015-06-11 21:12:47 -07:00
return user.save(function(err) {
if (err) { return next(err); }
next();
});
}
2015-08-04 14:52:06 -07:00
debug('exiting after user identity before save');
2015-06-11 21:12:47 -07:00
next();
});
});
2015-08-04 14:52:06 -07:00
}