0

Remove Permission

by
Published today

Unshare a file or folder by deleting one of its permissions.

Script gdrive Verified

The script

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

3
export type DynSelect_permission_id = string
4

5
// Dropdown of the file's current permissions.
6
export async function permission_id(auth: RT.Gdrive, file_id: string) {
7
  const response = await fetch(
8
    `https://www.googleapis.com/drive/v3/files/${file_id}/permissions?supportsAllDrives=true&pageSize=100&fields=permissions(id,type,role,emailAddress,domain)`,
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 { permissions } = (await response.json()) as {
20
    permissions: {
21
      id: string
22
      type: string
23
      role: string
24
      emailAddress?: string
25
      domain?: string
26
    }[]
27
  }
28
  return permissions.map((p) => ({
29
    value: p.id,
30
    label: `${p.emailAddress ?? p.domain ?? p.type} (${p.role})`,
31
  }))
32
}
33

34
/**
35
 * Remove Permission
36
 * Unshare a file or folder by deleting one of its permissions (pick it from the dropdown, or take the id from List Permissions). The owner's permission can't be removed; transfer ownership first.
37
 */
38
export async function main(
39
  auth: RT.Gdrive,
40
  file_id: string,
41
  permission_id: DynSelect_permission_id
42
) {
43
  const url = new URL(
44
    `https://www.googleapis.com/drive/v3/files/${file_id}/permissions/${permission_id}`
45
  )
46
  url.searchParams.append("supportsAllDrives", "true")
47

48
  const response = await fetch(url, {
49
    method: "DELETE",
50
    headers: {
51
      Authorization: `Bearer ${auth.token}`,
52
      Accept: "application/json",
53
    },
54
  })
55

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

60
  return { success: true }
61
}
62