Skip to content

Instantly share code, notes, and snippets.

@AshleyGrant
Created August 9, 2017 21:53
Show Gist options
  • Save AshleyGrant/40de5a59f138fb5e70f5a02cee58bdde to your computer and use it in GitHub Desktop.
Save AshleyGrant/40de5a59f138fb5e70f5a02cee58bdde to your computer and use it in GitHub Desktop.
Auth0 Rule
function (user, context, callback) {
// only do this for users from Azure AD
// or maybe for a specific connection
if (user.identities[0].provider !== 'waad')
return callback(null, user, context);
// To call Azure's Graph API we need an access token
// The access token can be either
// - The access token given to the logged in user by the IdP (provided that it has
// the necessary permissions)
// - An access token obtained through the client credentials grant (
// using the same client_id/key configured for the Azure AD connection,
// or a new set of credentials, obtained specifically for this).
// for simplicity, we will use the user's IdP access token
var aad_access_token = user.identities[0].access_token;
// call Azure's graph api to get information about the user
var baseUrl = 'https://graph.windows.net/'+ user.tenantid + '/users/'+ user.oid;
console.log('baseUrl:' + baseUrl);
var apiRequest = function(segment, nullEncoding, callback) {
var options = {
url: baseUrl + '/' + segment + '?api-version=1.6',
headers: {
'Authorization': 'Bearer ' + aad_access_token
}
};
if (nullEncoding) {
options.encoding = null;
}
console.log('Requesting to '+ options.url);
request(options, function(err, response, body){
if (err) {
console.log("Error when calling "+ options.url);
console.log(err);
}
callback(err, response, body);
});
};
var getThumbnail = function(cb) {
apiRequest('thumbnailPhoto', true, function(err, response, body) {
if (!err && response.statusCode === 200) {
user.thumbnailPhoto = "data:" + response.headers["content-type"] + ";base64," + new Buffer(body).toString('base64');
}
cb(err);
});
};
getThumbnail(function(err) {
// save the values in app_metadata before returning
user.app_metadata = user.app_metadata || {};
user.app_metadata.thumbnailPhoto = user.thumbnailPhoto;
context.idToken["https://moderndev.auth0.com/thumbnail_photo"] = user.thumbnailPhoto;
// persist the app_metadata update
auth0.users.updateAppMetadata(user.user_id, user.app_metadata)
.then(function(){
callback(null, user, context);
})
.catch(function(err){
callback(err);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment