//native
async function getManagementToken(auth: RT.Auth0): Promise<string> {
const response = await fetch(`https://${auth.domain}/oauth/token`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
grant_type: "client_credentials",
client_id: auth.client_id,
client_secret: auth.client_secret,
audience: `https://${auth.domain}/api/v2/`,
}),
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
const { access_token } = (await response.json()) as { access_token: string }
return access_token
}
/**
* Assign Roles to User
* Assign one or more roles to a user. Pass role IDs (e.g. rol_abc123).
*/
export async function main(auth: RT.Auth0, user_id: string, roles: string[]) {
const token = await getManagementToken(auth)
const url = new URL(`https://${auth.domain}/api/v2/users/${user_id}/roles`)
const response = await fetch(url, {
method: "POST",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
body: JSON.stringify({ roles }),
})
if (!response.ok) {
throw new Error(`${response.status} ${await response.text()}`)
}
if (response.status === 204) return { success: true }
return await response.json()
}
Submitted by hugo989 6 days ago