Created
April 14, 2025 23:08
-
-
Save nicosabena/991d6348befc95bfeff7af354b423857 to your computer and use it in GitHub Desktop.
Auth0 action to prevent users from logging in the first time with the same email address as an existing user
This file contains hidden or 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
| const { ManagementClient } = require("auth0"); | |
| exports.onExecutePostLogin = async (event, api) => { | |
| const INITIAL_LOGIN_CHECK = "initial_login_check" | |
| const initialLoginCheck = event.user.app_metadata[INITIAL_LOGIN_CHECK]; | |
| if (initialLoginCheck) { | |
| // We already checked for duplicate emails, no further work | |
| // to be done in this Action. | |
| return; | |
| } | |
| const domain = event.secrets.TENANT_DOMAIN; | |
| const clientId = event.secrets.CLIENT_ID; | |
| const clientSecret = event.secrets.CLIENT_SECRET; | |
| const management = new ManagementClient({ domain, clientId, clientSecret }); | |
| // Search for other candidate users | |
| // getByEmail is fast, but it's case sensitive | |
| const { data: usersWithSameEmail } = await management.usersByEmail.getByEmail({ | |
| email: event.user.email, | |
| }); | |
| // exclude the user logging in from the check | |
| const otherUsers = usersWithSameEmail.filter(user => user.user_id !== event.user.user_id); | |
| if (otherUsers.length === 0) { | |
| // No other users with the same email found. We mark the user | |
| // as checked and allow the login | |
| api.user.setAppMetadata(INITIAL_LOGIN_CHECK, Date.now()); | |
| } else { | |
| // this error will be sent back to the application as: | |
| // - error=access_denied | |
| // - error_description=identity_with_duplicated_email | |
| // The application will need to explain the situation to the user | |
| // | |
| // optional, include the connection name so that the application can instruct the user which identity to use | |
| const connectionName = otherUsers[0].identities[0].connection; | |
| api.access.deny(`identity_with_duplicated_email:${connectionName}`); | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment