1 | |
2 |
|
3 | async function getManagementToken(auth: RT.Auth0): Promise<string> { |
4 | const response = await fetch(`https://${auth.domain}/oauth/token`, { |
5 | method: "POST", |
6 | headers: { "Content-Type": "application/json" }, |
7 | body: JSON.stringify({ |
8 | grant_type: "client_credentials", |
9 | client_id: auth.client_id, |
10 | client_secret: auth.client_secret, |
11 | audience: `https://${auth.domain}/api/v2/`, |
12 | }), |
13 | }) |
14 | if (!response.ok) { |
15 | throw new Error(`${response.status} ${await response.text()}`) |
16 | } |
17 | const { access_token } = (await response.json()) as { access_token: string } |
18 | return access_token |
19 | } |
20 | |
21 | * Assign Roles to User |
22 | * Assign one or more roles to a user. Pass role IDs (e.g. rol_abc123). |
23 | */ |
24 | export async function main(auth: RT.Auth0, user_id: string, roles: string[]) { |
25 | const token = await getManagementToken(auth) |
26 | const url = new URL(`https://${auth.domain}/api/v2/users/${user_id}/roles`) |
27 |
|
28 | const response = await fetch(url, { |
29 | method: "POST", |
30 | headers: { |
31 | Authorization: `Bearer ${token}`, |
32 | "Content-Type": "application/json", |
33 | Accept: "application/json", |
34 | }, |
35 | body: JSON.stringify({ roles }), |
36 | }) |
37 |
|
38 | if (!response.ok) { |
39 | throw new Error(`${response.status} ${await response.text()}`) |
40 | } |
41 |
|
42 | if (response.status === 204) return { success: true } |
43 | return await response.json() |
44 | } |
45 |
|