0

Move User to Org Unit

by
Published today

Move a user to another organizational unit, picked from a dropdown of the account's org units. Listing org units needs admin.directory.orgunit or admin.directory.orgunit.readonly on the connection.

Script gworkspace Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 1 hour ago
1
//native
2

3
export type DynSelect_org_unit_path = string
4

5
// Dropdown of every org unit in the account, plus the root "/".
6
export async function org_unit_path(auth: RT.Gworkspace) {
7
  const response = await fetch(
8
    "https://admin.googleapis.com/admin/directory/v1/customer/my_customer/orgunits?type=all",
9
    {
10
      headers: {
11
        Authorization: `Bearer ${auth.token}`,
12
        Accept: "application/json",
13
      },
14
    },
15
  )
16
  if (!response.ok) {
17
    throw new Error(`${response.status} ${await response.text()}`)
18
  }
19
  const { organizationUnits = [] } = (await response.json()) as {
20
    organizationUnits?: { orgUnitPath: string }[]
21
  }
22
  return [
23
    { value: "/", label: "/ (root)" },
24
    ...organizationUnits
25
      .map((o) => o.orgUnitPath)
26
      .sort()
27
      .map((p) => ({ value: p, label: p })),
28
  ]
29
}
30

31
/**
32
 * Move User to Org Unit
33
 * Move a user to another organizational unit, picked from a dropdown of the account's org units. Listing org units needs admin.directory.orgunit or admin.directory.orgunit.readonly on the connection.
34
 */
35
export async function main(
36
  auth: RT.Gworkspace,
37
  user_key: string,
38
  org_unit_path: DynSelect_org_unit_path,
39
) {
40
  const response = await fetch(
41
    `https://admin.googleapis.com/admin/directory/v1/users/${encodeURIComponent(user_key)}`,
42
    {
43
      method: "PATCH",
44
      headers: {
45
        Authorization: `Bearer ${auth.token}`,
46
        "Content-Type": "application/json",
47
        Accept: "application/json",
48
      },
49
      body: JSON.stringify({ orgUnitPath: org_unit_path }),
50
    },
51
  )
52

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

57
  return await response.json()
58
}
59