Как получить список всех пользователей с доступом к общему диску Google с помощью скрипта приложений
Я использовал getEditors для получения списка редакторов электронной таблицы, и возвращенный список включает пользователей общих дисков. Однако пользователи с доступом к общему диску "менеджер контента" не включаются в список. Любая причина, почему это так?
Я также обнаружил, что getAccess можно использовать для получения типа доступа конкретного пользователя к папке на диске. Используя этот подход, моей целью было бы идентифицировать всех пользователей с разрешением FILE_ORGANIZER или ORGANIZER. См. Официальную документацию по разрешениям. Можно ли использовать оператор if или цикл для получения этой информации?
В качестве альтернативы, есть ли обходной путь для получения списка всех пользователей с доступом к общему диску, который я, возможно, не рассматривал?
PS: Расширенный сервис дисковода не включен.
// This code aims to protect a sheet in a spreadsheet
// by granting specific users access (super users)
// and revoking the access of any other user that can edit the spreadsheet.
/*
Attempted approach:
user1 and user2 have manager permission to the shared drive as a whole
user3 has content manager permission to the shared drive as a whole
user4 only has access to this spreadsheet in the shared drive
My objective is to ensure that only users 1 and 2 can edit the protected sheet.
Result:
Log shows that users 1 and 2 have access and user 4 does not.
However, user3 can still edit the sheet because they were no included in the getEditors() result hence their access could not be revoked.
*/
function protectASheet() {
var superusers = ['user1', 'user2'];
var ss = SpreadsheetApp.getActive();
var editors = ss.getEditors(); //get file editors
var sheet = SpreadsheetApp.getActive().getSheetByName('TestSheet');
//Set protection
var protection = sheet.protect().setDescription('This sheet is protected.');
protection.addEditors(superusers); //Grant superusers edit permission
protection.removeEditors(editors); //Revoke other file editors' permission
Logger.log("Only the following can edit " + sheet.getSheetName() + ": " + protection.getEditors());
}
1 ответ
Получил помощь от коллеги. Этот подход основан на активации расширенной службы накопителя в редакторе скриптов. Чтобы включить, перейдите в Ресурсы -> Расширенные службы Google.
Он извлекает разрешения и другие сведения о каждом пользователе, имеющем любую форму доступа к файлу или папке без исключения.
Код ниже:
function getPermissionsList() {
const fileId = "<FILE, FOLDER OR SHARED DRIVE ID HERE>"; // ID of your shared drive
// THIS IS IMPORTANT! The default value is false, so the call won't
// work with shared drives unless you change this via optional arguments
const args = {
supportsAllDrives: true
};
// Use advanced service to get the permissions list for the shared drive
let pList = Drive.Permissions.list(fileId, args);
//Put email and role in an array
let editors = pList.items;
var arr = [];
for (var i = 0; i < editors.length; i++) {
let email = editors[i].emailAddress;
let role = editors[i].role;
arr.push([email, role]);
}
Logger.log(arr);
}