0

Create User

by
Published today

Create a user in the Workspace account. `primary_email` must be on one of the account's verified domains; the password needs 8 to 100 characters. Extra user fields (phones, recovery email, custom schemas…) go in `additional_fields`. The org-unit dropdown 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
 * Create User
33
 * Create a user in the Workspace account. `primary_email` must be on one of the account's verified domains; the password needs 8 to 100 characters. Extra user fields (phones, recovery email, custom schemas…) go in `additional_fields`. The org-unit dropdown needs admin.directory.orgunit or admin.directory.orgunit.readonly on the connection.
34
 */
35
export async function main(
36
  auth: RT.Gworkspace,
37
  primary_email: string,
38
  given_name: string,
39
  family_name: string,
40
  password: string,
41
  change_password_at_next_login: boolean = true,
42
  org_unit_path: DynSelect_org_unit_path | undefined,
43
  additional_fields: { [key: string]: any } | undefined,
44
) {
45
  const body: { [key: string]: any } = {
46
    ...additional_fields,
47
    primaryEmail: primary_email,
48
    name: { givenName: given_name, familyName: family_name },
49
    password,
50
    changePasswordAtNextLogin: change_password_at_next_login,
51
  }
52
  if (org_unit_path !== undefined && org_unit_path !== "") {
53
    body.orgUnitPath = org_unit_path
54
  }
55

56
  const response = await fetch(
57
    "https://admin.googleapis.com/admin/directory/v1/users",
58
    {
59
      method: "POST",
60
      headers: {
61
        Authorization: `Bearer ${auth.token}`,
62
        "Content-Type": "application/json",
63
        Accept: "application/json",
64
      },
65
      body: JSON.stringify(body),
66
    },
67
  )
68

69
  if (!response.ok) {
70
    throw new Error(`${response.status} ${await response.text()}`)
71
  }
72

73
  return await response.json()
74
}
75