freeCodeCamp/server/boot/a-extendUserIdent.js

82 lines
2.2 KiB
JavaScript
Raw Normal View History

2016-03-03 04:54:14 +00:00
import { Observable } from 'rx';
2015-11-04 05:51:16 +00:00
import debugFactory from 'debug';
import dedent from 'dedent';
import { observeMethod, observeQuery } from '../utils/rx';
import { getSocialProvider } from '../utils/auth';
2015-08-18 21:48:22 +00:00
const debug = debugFactory('fcc:userIdent');
export default function({ models }) {
const { User, UserIdentity, UserCredential } = models;
const findUserById = observeMethod(User, 'findById');
const findIdent = observeMethod(UserIdentity, 'findOne');
UserIdentity.link = function(
userId,
provider,
authScheme,
profile,
credentials,
options = {},
cb
) {
if (typeof options === 'function' && !cb) {
cb = options;
options = {};
}
const user$ = findUserById(userId);
2015-08-18 21:48:22 +00:00
const query = {
where: {
provider: getSocialProvider(provider),
externalId: profile.id
}
};
debug('link identity query', query);
findIdent(query)
.flatMap(identity => {
const modified = new Date();
2015-08-18 21:48:22 +00:00
if (!identity) {
return observeQuery(UserIdentity, 'create', {
provider: getSocialProvider(provider),
externalId: profile.id,
authScheme,
profile,
credentials,
userId,
created: modified,
modified
});
}
2015-08-18 22:22:28 +00:00
if (identity.userId.toString() !== userId.toString()) {
2015-08-18 21:48:22 +00:00
return Observable.throw(
2015-11-04 05:51:16 +00:00
new Error(
dedent`
2016-01-11 01:56:12 +00:00
Your GitHub is already associated with another account.
You may have accidentally created a duplicate account.
No worries, though. We can fix this real quick.
Please email us with your GitHub username: team@freecodecamp.com.
2015-11-04 05:51:16 +00:00
`.split('/n').join(' ')
)
2015-08-18 21:48:22 +00:00
);
}
identity.credentials = credentials;
return observeQuery(identity, 'updateAttributes', {
2015-08-21 23:08:49 +00:00
profile,
credentials,
modified
});
})
.withLatestFrom(user$, (identity, user) => ({ identity, user }))
.subscribe(
({ identity, user }) => {
cb(null, user, identity);
},
cb
);
};
UserCredential.link = UserIdentity.link.bind(UserIdentity);
}