-
-
Save johnny68/9f3d669bcf280ab87316b452ab6ae2af to your computer and use it in GitHub Desktop.
Merge AWS Cognito External Provider User with Cognito User on Pre SignUp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { PreSignUpTriggerEvent, PreSignUpTriggerHandler } from 'aws-lambda'; | |
import { CognitoIdentityServiceProvider } from 'aws-sdk'; | |
const providerName = { | |
google: 'Google', | |
facebook: 'Facebook' | |
}; | |
const tryMergeUserAccounts = async (event: PreSignUpTriggerEvent) => { | |
const { userPoolId, userName } = event; | |
const { email } = event.request.userAttributes; | |
const [provider, providerValue] = userName.split('_'); | |
// merge social provider with existing cognito user by email | |
if (['facebook', 'google'].includes(provider) && providerValue) { | |
const cognito = new CognitoIdentityServiceProvider(); | |
const { Users } = await cognito | |
.listUsers({ | |
UserPoolId: userPoolId, | |
AttributesToGet: ['email'], | |
Filter: `email = "${email}"` | |
}) | |
.promise(); | |
for (const user of Users) { | |
await cognito | |
.adminLinkProviderForUser({ | |
UserPoolId: userPoolId, | |
DestinationUser: { | |
ProviderName: 'Cognito', | |
ProviderAttributeValue: user.Username | |
}, | |
SourceUser: { | |
ProviderName: providerName[provider], | |
ProviderAttributeName: 'Cognito_Subject', | |
ProviderAttributeValue: providerValue | |
} | |
}) | |
.promise(); | |
} | |
// return true to indicate users were merged | |
return Users.length > 0; | |
} | |
return false; | |
}; | |
export const handler: PreSignUpTriggerHandler = async (event, _, callback) => { | |
// continue the flow only if did not link providers | |
const wereUsersMerged = await tryMergeUserAccounts(event); | |
return wereUsersMerged ? undefined : callback(null, event); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment