freeCodeCamp/common/models/User-Identity.js

63 lines
1.6 KiB
JavaScript
Raw Normal View History

2015-08-04 21:52:06 +00:00
import debugFactory from 'debug';
import {
setProfileFromGithub,
getFirstImageFromProfile
} from '../../server/utils/auth';
2015-08-04 21:52:06 +00:00
const debug = debugFactory('freecc:models:userIdent');
const { defaultProfileImage } = require('../utils/constantStrings.json');
2015-08-04 21:52:06 +00:00
export default function(UserIdent) {
UserIdent.observe('before save', function(ctx, next) {
2015-06-11 19:13:22 +00:00
var userIdent = ctx.currentInstance || ctx.instance;
if (!userIdent) {
2015-06-11 19:13:22 +00:00
debug('no user identity instance found');
return next();
}
userIdent.user(function(err, user) {
2015-08-04 21:52:06 +00:00
let userChanged = false;
if (err) { return next(err); }
2015-06-11 19:13:22 +00:00
if (!user) {
debug('no user attached to identity!');
return next();
}
2015-08-06 00:49:19 +00:00
const { profile } = userIdent;
const picture = getFirstImageFromProfile(profile);
2015-06-12 04:12:47 +00: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 21:52:06 +00:00
user.picture = picture;
userChanged = true;
}
2015-08-06 00:49:19 +00:00
// if user signed in with github refresh their info
2015-08-11 06:38:10 +00:00
if (/github/.test(userIdent.provider)) {
debug("user isn't github cool or username from github is different");
2015-08-06 00:49:19 +00:00
setProfileFromGithub(user, profile, profile._json);
2015-08-04 21:52:06 +00:00
userChanged = true;
}
2015-08-04 21:52:06 +00:00
if (userChanged) {
2015-06-12 04:12:47 +00:00
return user.save(function(err) {
if (err) { return next(err); }
next();
});
}
2015-08-04 21:52:06 +00:00
debug('exiting after user identity before save');
2015-06-12 04:12:47 +00:00
next();
});
});
2015-08-04 21:52:06 +00:00
}