Skip to content

Instantly share code, notes, and snippets.

@thameera
Last active August 4, 2020 07:29
Show Gist options
  • Save thameera/d6f1a88feb1dc1ecbfc86f14ddf7c0cd to your computer and use it in GitHub Desktop.
Save thameera/d6f1a88feb1dc1ecbfc86f14ddf7c0cd to your computer and use it in GitHub Desktop.
Post-user registration hook to add user_id to app_metadata

How to set up

  1. Go to Clients -> Create New -> and choose Non-Interactive to create a non-interactive client.
  2. Go to APIs -> Auth0 Management API -> Non Interactive Clients
  3. Authorize the newly created client. Also, check the update:users scope and click 'Update'.
  4. Go to Hooks page and create a new post-registration hook with the contents in post-reg-hook.js file. Please make sure to change tenant_url in line 4 to your Auth0 domain.
  5. In the hook editor, click on the wrench icon on top-left -> Secrets. Create two new secrets named client_id and client_secret and add the client ID and secret of the client you created in the first step.

Now, when a user signs up, their app_metadata will include an id attribute that contains the user_id.

module.exports = function (user, context, cb) {
var request = require('[email protected]');
var tenant_url = 'https://example.au.auth0.com'; // Change this to your Auth0 domain
request.post({
url: tenant_url + '/oauth/token',
json: { 'client_id': context.webtask.secrets.client_id, 'client_secret': context.webtask.secrets.client_secret, 'audience':tenant_url+'/api/v2/', 'grant_type':'client_credentials'}
}, function(err, response, body) {
if (err) {
console.log(err);
return cb();
}
var token = body.access_token;
var url = tenant_url + '/api/v2/users/auth0|' + user.id;
request.patch({
url: url,
headers: {
Authorization: 'Bearer ' + token
},
json: { 'app_metadata': { 'id': 'auth0|' + user.id } }
}, function(err, response, body) {
if (response && response.statusCode >= 400) {
console.log(response.statusMessage);
}
cb();
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment