2015-08-12 16:25:52 -07:00
|
|
|
import { observeMethod, observeQuery } from '../utils/rx';
|
2015-08-12 19:08:05 -07:00
|
|
|
import { getSocialProvider } from '../utils/auth';
|
2015-08-12 16:25:52 -07:00
|
|
|
|
|
|
|
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);
|
|
|
|
console.log('provider', provider);
|
|
|
|
console.log('id', profile.id);
|
|
|
|
findIdent({
|
2015-08-12 19:08:05 -07:00
|
|
|
provider: getSocialProvider(provider),
|
2015-08-12 16:25:52 -07:00
|
|
|
externalId: profile.id
|
|
|
|
})
|
|
|
|
.flatMap(identity => {
|
|
|
|
const modified = new Date();
|
|
|
|
if (!identity || identity.externalId !== profile.id) {
|
|
|
|
return observeQuery(UserIdentity, 'create', {
|
2015-08-12 19:08:05 -07:00
|
|
|
provider: getSocialProvider(provider),
|
2015-08-12 16:25:52 -07:00
|
|
|
externalId: profile.id,
|
|
|
|
authScheme,
|
|
|
|
profile,
|
|
|
|
credentials,
|
|
|
|
userId,
|
|
|
|
created: modified,
|
|
|
|
modified
|
|
|
|
});
|
|
|
|
}
|
|
|
|
identity.credentials = credentials;
|
|
|
|
return observeQuery(identity, 'updateAttributes', {
|
2015-08-12 19:08:05 -07:00
|
|
|
profile: getSocialProvider(provider),
|
2015-08-12 16:25:52 -07:00
|
|
|
credentials,
|
|
|
|
modified
|
|
|
|
});
|
|
|
|
})
|
|
|
|
.withLatestFrom(user$, (identity, user) => ({ identity, user }))
|
|
|
|
.subscribe(
|
|
|
|
({ identity, user }) => {
|
|
|
|
cb(null, user, identity);
|
|
|
|
},
|
|
|
|
cb
|
|
|
|
);
|
|
|
|
};
|
|
|
|
|
|
|
|
UserCredential.link = UserIdentity.link.bind(UserIdentity);
|
|
|
|
}
|