2015-08-04 21:52:06 +00:00
|
|
|
import debugFactory from 'debug';
|
2015-06-11 18:38:08 +00:00
|
|
|
|
2015-08-12 19:15:19 +00:00
|
|
|
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-06-11 18:38:08 +00:00
|
|
|
|
2015-08-04 21:52:06 +00:00
|
|
|
export default function(UserIdent) {
|
2015-06-11 18:38:08 +00:00
|
|
|
UserIdent.observe('before save', function(ctx, next) {
|
2015-06-11 19:13:22 +00:00
|
|
|
var userIdent = ctx.currentInstance || ctx.instance;
|
2015-06-11 20:19:44 +00:00
|
|
|
if (!userIdent) {
|
2015-06-11 19:13:22 +00:00
|
|
|
debug('no user identity instance found');
|
|
|
|
return next();
|
|
|
|
}
|
2015-06-11 18:38:08 +00:00
|
|
|
userIdent.user(function(err, user) {
|
2015-08-04 21:52:06 +00:00
|
|
|
let userChanged = false;
|
2015-06-11 18:38:08 +00:00
|
|
|
if (err) { return next(err); }
|
2015-06-11 19:13:22 +00:00
|
|
|
if (!user) {
|
|
|
|
debug('no user attached to identity!');
|
|
|
|
return next();
|
|
|
|
}
|
2015-06-11 18:38:08 +00:00
|
|
|
|
2015-08-12 23:25:52 +00:00
|
|
|
const { profile, provider } = userIdent;
|
2015-08-06 00:49:19 +00:00
|
|
|
const picture = getFirstImageFromProfile(profile);
|
2015-06-11 18:38:08 +00:00
|
|
|
|
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-12 23:25:52 +00:00
|
|
|
if (!(/github/).test(provider)) {
|
|
|
|
user[provider.split('-')[0]] = profile.username;
|
|
|
|
}
|
|
|
|
|
2015-08-06 00:49:19 +00:00
|
|
|
// if user signed in with github refresh their info
|
2015-08-12 23:25:52 +00:00
|
|
|
if (/github/.test(provider)) {
|
2015-08-04 22:09:42 +00:00
|
|
|
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 22:09:42 +00:00
|
|
|
|
2015-08-04 21:52:06 +00:00
|
|
|
if (userChanged) {
|
2015-06-12 04:12:47 +00:00
|
|
|
return user.save(function(err) {
|
2015-06-11 18:38:08 +00:00
|
|
|
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-06-11 18:38:08 +00:00
|
|
|
});
|
|
|
|
});
|
2015-08-04 21:52:06 +00:00
|
|
|
}
|