0

List Users

by
Published 4 days ago

Search and list users in the tenant. Use `q` (Lucene query syntax, e.g. email:"[email protected]") to filter; page and per_page paginate.

Script auth0 Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 5 days ago
1
//native
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
/**
22
 * List Users
23
 * Search and list users in the tenant. Use `q` (Lucene query syntax, e.g. email:"jane@example.com") to filter; page and per_page paginate.
24
 */
25
export async function main(
26
  auth: RT.Auth0,
27
  q: string | undefined,
28
  page: number | undefined,
29
  per_page: number | undefined,
30
  sort: string | undefined,
31
  include_totals: boolean | undefined
32
) {
33
  const token = await getManagementToken(auth)
34
  const url = new URL(`https://${auth.domain}/api/v2/users`)
35
  if (q !== undefined && q !== "") {
36
    url.searchParams.append("q", q)
37
    url.searchParams.append("search_engine", "v3")
38
  }
39
  if (page !== undefined) url.searchParams.append("page", String(page))
40
  if (per_page !== undefined)
41
    url.searchParams.append("per_page", String(per_page))
42
  if (sort !== undefined && sort !== "") url.searchParams.append("sort", sort)
43
  if (include_totals !== undefined)
44
    url.searchParams.append("include_totals", String(include_totals))
45

46
  const response = await fetch(url, {
47
    method: "GET",
48
    headers: {
49
      Authorization: `Bearer ${token}`,
50
      Accept: "application/json",
51
    },
52
  })
53

54
  if (!response.ok) {
55
    throw new Error(`${response.status} ${await response.text()}`)
56
  }
57

58
  return await response.json()
59
}
60