google-apps-scriptgoogle-drive-apigoogle-drive-shared-drive

Appscript API for fetching access permissions of team drive


I am trying to generate a report of all access permissions currently various users have in Team Drive. Is there any API in Appscript to Fetch this data?


Solution

  • There doesn't seem to be any method for getting Drive permissions sorted by username, so you will need to implement this business logic yourself. According to the documentation, sending a GET request to the API endpoint below will get you the list of permissions for the Team Drive (use Team Drive ID instead of file id):

    https://www.googleapis.com/drive/v3/files/fileId/permissions

    I don't have any Team Drives set up - the example below is based on getting permissions for a single file using Drive REST API. Before the code can be executed, you must prove your identity by including API key in URL parameters and passing OAuth token in the headers of your 'GET'request. The API key can be obtained from Google Cloud console. Enable the Drive API and click the key icon in the left menu to set up credentials. Choose "API key" from the drop-down and copy the value.

    Your script must pass the token that includes all required authorization scopes to the API endpoint. OAuth scopes are set explicitly in the manifest file. In Script Editor, select "View - Show manifest file" and add relevant scopes. Scopes used in my manifest file are for accessing Drive Files and calling external services via UrlFetchApp:

     "oauthScopes": [
      "https://www.googleapis.com/auth/drive",
      "https://www.googleapis.com/auth/script.external_request"]
    

    Finally, get the list of permissions for the file:

      var fileId = "FILE_ID";
        var apiKey = "API_KEY";
    
        var apiUrl = "https://www.googleapis.com/drive/v3/files/fileId/permissions";
    
        var token = ScriptApp.getOAuthToken();
        var header = {"Authorization":"Bearer " + token};
    
        var options = {
        "method":"GET",
        "headers": header,
        "muteHttpExceptions": true
        };
    
        var res = UrlFetchApp.fetch(apiUrl.replace("fileId", fileId) + "?key=" + apiKey, options)
                             .getContentText();
    
            var permissions = JSON.parse(res);
            Logger.log(permissions);