Last active
June 10, 2016 10:52
-
-
Save thameera/153f83efe43f01089bd15aa4b985e46f to your computer and use it in GitHub Desktop.
Auth0 - Create new passwordless user and link him to current account on first login
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@2.56.0'); | |
// Create and link user only during first login | |
if (context.stats.loginsCount > 1) { | |
return callback(null, user, context); | |
} | |
// Create new user | |
// Note: the access token must have create:users and update:users scopes | |
request.post({ | |
url: auth0.baseUrl + '/users', | |
headers: { | |
Authorization: 'Bearer ' + configuration.ACCESS_TOKEN | |
}, | |
json: { connection: 'email', email: user.email } | |
}, | |
function(err, response, body) { | |
if (err) return callback(err); | |
if (response.statusCode !== 201) return callback(new Error(body)); | |
var newUserId = body.user_id.split('|')[1]; | |
// Link the accounts. Primary acct: original user. Secondary acct: newly created user. | |
request.post({ | |
url: auth0.baseUrl + '/users/' + user.user_id + '/identities', | |
headers: { | |
Authorization: 'Bearer ' + configuration.ACCESS_TOKEN | |
}, | |
json: {provider: 'email', user_id: newUserId} | |
}, | |
function(err, response, body) { | |
if (err) return callback(err); | |
if (response.statusCode >= 400) return callback(new Error('Error linking accounts: ' + response.statusMessage)); | |
return callback(null, user, context); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment