Skip to content

Instantly share code, notes, and snippets.

@Vichoko
Last active October 11, 2023 19:30
Show Gist options
  • Save Vichoko/8e7c0b558f0a4ac3b366bf4cf21404d4 to your computer and use it in GitHub Desktop.
Save Vichoko/8e7c0b558f0a4ac3b366bf4cf21404d4 to your computer and use it in GitHub Desktop.
add default roles to auth0 user during signup / first login
const fetch = require('node-fetch')
const AUTH0_CLIENT_ID = "something";
const AUTH0_DOMAIN = "https://domain.com";
const AUTH0_AUDIENCE = "https://domain.us.auth0.com/api/v2/";
const MANAGEMENT_API_DOMAIN = "domain.us.auth0.com";
const ROLE_ID = "rol_something";
var getAccessToken = async function (event) {
console.log('Fetching access token from ' + AUTH0_DOMAIN + '/oauth/token...');
try {
var response = await fetch(
AUTH0_DOMAIN + '/oauth/token',
{
method: 'POST',
headers: {
'cache-control': 'no-cache',
'content-type': 'application/json'
},
body: JSON.stringify({
audience: AUTH0_AUDIENCE,
grant_type: 'client_credentials',
client_id: AUTH0_CLIENT_ID,
client_secret: event.secrets.AUTH0_CLIENT_SECRET
}),
})
} catch (error) {
console.log(error);
return
}
const data = await response.json();
if (data.error === "access_denied") {
throw data.error
}
return data.token
}
/**
* Handler that will be called during the execution of a PostLogin flow.
*
* @param {Event} event - Details about the user and the context in which they are logging in.
* @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
*/
exports.onExecutePostLogin = async (event, api) => {
const count = event.stats && event.stats.logins_count ? event.stats.logins_count : 0;
if (count > 1) {
return;
}
const access_token = await getAccessToken(event);
const options = {
method: 'POST',
headers: {
'content-type': 'application/json',
authorization: `Bearer ${access_token}`,
'cache-control': 'no-cache'
},
body: JSON.stringify({ roles: [ROLE_ID] })
};
try {
const response = await fetch(`https://${MANAGEMENT_API_DOMAIN}/api/v2/users/${event.user.user_id}/roles`, options);
const responseData = await response.json();
console.log(responseData);
} catch (error) {
console.error(error);
}
};
@Vichoko
Copy link
Author

Vichoko commented Oct 11, 2023

Here is an Node18 Action Flow alternative to the deprecated solution (from https://community.auth0.com/t/how-do-i-add-a-default-role-to-a-new-user-on-first-login/25857):

function (user, context, callback) {

    const count = context.stats && context.stats.loginsCount ? context.stats.loginsCount : 0;
    if (count > 1) {
        return callback(null, user, context);
    }

    const ManagementClient = require('auth0@2.27.0').ManagementClient;
    const management = new ManagementClient({
      token: auth0.accessToken,
      domain: auth0.domain
    });

    const params =  { id : user.user_id};
    const data = { "roles" : ["ROLE_ID_1","ROLE_ID_2"]};

    management.users.assignRoles(params, data, function (err, user) {
    if (err) {
        // Handle error.
        console.log(err);
     }
    callback(null, user, context);
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment