google-apps-scriptgoogle-drive-api

How To Set File Access Just For User In Domain, With Apps Script


I have some file and folder in Google Drive. I want to set access with Apps Script. I put access setting in sheetDatabase, Cell 'K3' with Data Validation option : 'ARRANGED' and 'UNREGULATED'. The Domain my organization is guru.smk.belajar.id ( and I hope I can change it later ), I place it in Cell 'K4' .

To set file / folder Access, I create Apps Script, but I Can't set user acces with domain address restrictions. It is possible to set user acces with domain ( @sampledomain.com ) address restrictions ( not just user ( user@sampledomain.com ) ?

 function updatePermissions() {

    var domainSetting = sheetDatabase.getRange('K3').getValue();
    var domain        = sheetDatabase.getRange('K4').getValue(); // As a sample, my domain was @guru.smk.belajar.id

    Logger.log("Domain "+domain)

 // Set Folder Share Access  
    var folderAplikasiPklID = sheetSetting.getRange(6, 3).getValue(); //  Folder ID
    var folder = DriveApp.getFolderById(folderAplikasiPklID);

 // Set Spreadsheet Share Access
    var spreadsheetID = sheetSetting.getRange(7, 3).getValue(); // Spreadsheet ID
    var ssJurnalPKL = DriveApp.getFileById(spreadsheetID);

   if (domainSetting === 'ARRANGED') {
// Set folder to view only by domain users
  folder.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.VIEW);
  folder.addViewers(domain);

// Set file to edit only by users in the specified domain
 ssJurnalPKL.setSharing(DriveApp.Access.PRIVATE, DriveApp.Permission.VIEW); // Restrict to private first
 var viewers = ssJurnalPKL.getViewers();
 for (var i = 0; i < viewers.length; i++) {
     ssJurnalPKL.removeViewer(viewers[i]);
 }
 var editors = ssJurnalPKL.getEditors();
     for (var i = 0; i < editors.length; i++) {
     ssJurnalPKL.removeEditor(editors[i]);
 }
 ssJurnalPKL.addEditors(domain); // Give Editor Access to User in  domain

  } else if (domainSetting === 'UNREGULATED') {
// Set file to edit by anyone with the link
   ssJurnalPKL.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.EDIT);
 }

  Logger.log('Permissions updated successfully.');
  };

Solution

  • In order to give permission to a domain, Drive API is used. The sample script is as follows.

    Sample script:

    Before you test this script, please enable Drive API v3 at Advanced Google services.

    const fileId = "###"; // <--- Please set your file ID.
    const resource = {
      role: "writer",
      type: "domain",
      domain: "###" // <--- Please set your domain.
    };
    Drive.Permissions.create(resource, fileId, { supportsAllDrives: true });
    

    Reference: