Last active
September 13, 2018 09:14
-
-
Save thameera/1086472ac51a8dab6ed5fef803a9f537 to your computer and use it in GitHub Desktop.
Create and link DB users for social logins
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
function (user, context, callback) { | |
/* Disclaimer: Not well-tested. Might have clashes with existing linking rules, enterprise connections, etc */ | |
console.log('-- User creation/linking rule --'); | |
var DB_CONN = 'DB_CONNECTION_NAME_HERE'; | |
if (context.clientID !== 'CLIENT_ID_HERE') { | |
return callback(null, user, context); | |
} | |
var dbIdentity = _.find(user.identities, { connection: DB_CONN }); | |
if (dbIdentity) { | |
console.log('User already has a database account'); | |
return callback(null, user, context); | |
} | |
console.log('User has no DB identity. Going to create one.'); | |
/* Obtain Management API token */ | |
request.post({ | |
url: 'https://' + auth0.domain + '/oauth/token', | |
json: { 'client_id': configuration.API_EXPLORER_CLIENT_ID, 'client_secret': configuration.API_EXPLORER_CLIENT_SECRET, 'audience':auth0.baseUrl+'/', 'grant_type':'client_credentials'} | |
}, function(err, response, body) { | |
if (err || response.statusCode >= 400) { | |
console.log('Error obtaining access token.', err ? err : response.statusMessage); | |
return callback(err); | |
} | |
var token = body.access_token; | |
console.log('Obtained access token.', token); | |
/* Create DB user */ | |
request.post({ | |
url: auth0.baseUrl + '/users', | |
headers: { | |
Authorization: 'Bearer ' + token | |
}, | |
json: { | |
connection: DB_CONN, | |
email: user.email, | |
username: user.email.split('@')[0], | |
password: require('uuid').v4() | |
} | |
}, function(err2, response2, body2) { | |
if (err2 || response2.statusCode >= 400) { | |
console.log('Error creating user.', err2 ? err2 : response2.statusMessage); | |
return callback(err2); | |
} | |
console.log('Created new user', body2); | |
var dbUserId = body2.identities[0].user_id; | |
/* Link DB user to current user */ | |
request.post({ | |
url: auth0.baseUrl + '/users/' + user.user_id + '/identities', | |
headers: { | |
Authorization: 'Bearer ' + token | |
}, | |
json: { provider: 'auth0', user_id: dbUserId } | |
}, function(err3, response3, body3) { | |
if (err3 || response3.statusCode >= 400) { | |
console.log('Error linking user.', err3 ? err3 : response3.statusMessage); | |
return callback(err3); | |
} | |
console.log('DB user successfully created and linked'); | |
return callback(null, user, context); | |
}); // link user | |
}); // create user | |
}); // /oauth/token | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment