Created
February 22, 2021 20:53
-
-
Save amin3mej/3a9d52eb5a7fe766aa624b9fd5212d0a to your computer and use it in GitHub Desktop.
Auth0's rule to create an user credential for users who logged in with social accounts
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
function(user, context, callback) { | |
var request = require("request"); | |
function mergeProcess({ primaryUser, toMergeUser }) { | |
var provider = toMergeUser.identities[0].provider; | |
var providerUserId = toMergeUser.identities[0].user_id; | |
var userIdentitiesEndpoint = | |
auth0.baseUrl + "/users/" + primaryUser.user_id + "/identities"; | |
return new Promise(function(resolve, reject) { | |
request.post( | |
{ | |
url: userIdentitiesEndpoint, | |
headers: { | |
Authorization: "Bearer " + auth0.accessToken | |
}, | |
json: { provider: provider, user_id: String(providerUserId) } | |
}, | |
function(err, response, body) { | |
if (err) reject(err); | |
if (response && response.statusCode >= 400) { | |
reject( | |
new Error("Error linking account: " + response.statusMessage) | |
); | |
} else { | |
resolve(); | |
} | |
} | |
); | |
}); | |
} | |
function createUserPasswordConnection({ email }) { | |
return new Promise(function(resolve, reject) { | |
var ManagementClient = require("[email protected]").ManagementClient; | |
var managementClient = new ManagementClient({ | |
domain: auth0.domain, | |
clientId: configuration.CREATE_USER_PASSWORD_MANAGEMENT_CLIENT_ID, | |
clientSecret: configuration.CREATE_USER_PASSWORD_MANAGEMENT_CLIENT_SECRET, | |
scope: "create:users" | |
}); | |
managementClient | |
.createUser({ | |
email, | |
verify_email: false, | |
email_verified: false, | |
password: require("crypto") | |
.randomBytes(32) | |
.toString("hex") | |
.slice(0, 32), | |
connection: configuration.CREATE_USER_PASSWORD_MANAGEMENT_DATABASE_CONNECTION_NAME | |
}) | |
.then(resolve) | |
.catch(reject); | |
}); | |
} | |
var hasPasswordConnection = user.identities.find(function(identity) { | |
return ( | |
identity.provider === "auth0" && | |
identity.connection === configuration.CREATE_USER_PASSWORD_MANAGEMENT_DATABASE_CONNECTION_NAME | |
); | |
}); | |
if (hasPasswordConnection) callback(null, user, context); | |
else { | |
createUserPasswordConnection({ email: user.email }) | |
.then(function(createdUser) { | |
mergeProcess({ | |
primaryUser: user, | |
toMergeUser: createdUser | |
}) | |
.then(function() { | |
console.log("succeeded"); | |
context.primaryUser = user.user_id; | |
callback(null, user, context); | |
}) | |
.catch(function(e) { | |
console.log("failed", e); | |
callback(e); | |
}); | |
}) | |
.catch(function(e) { | |
console.log("failed", e); | |
callback(e); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment