Last active
October 11, 2023 19:30
-
-
Save Vichoko/8e7c0b558f0a4ac3b366bf4cf21404d4 to your computer and use it in GitHub Desktop.
add default roles to auth0 user during signup / first login
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
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); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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):