Categories
Code

How to Check if the Google User has a G Suite Account

This Google Apps Script will help your add-on determine whether the current logged-in user is on GSuite (Google Apps) or if they are using the consumer (free) Google Account. G Suite users have higher email sending limits and have more storage space in Google Drive vis-a-vis free accounts.

The code snippet is courtesy +FaustinoRodriguez.

function isGSuiteUser() {
  
  var url = "https://www.googleapis.com/oauth2/v2/userinfo";
  var oAuthToken = ScriptApp.getOAuthToken();
  
  var params = {
    "method": "GET",
    "headers": {
      "Authorization": "Bearer " + oAuthToken
    },
    muteHttpExceptions: true
  };
  
  var response = UrlFetchApp.fetch(url, params);  
  var userInfo = JSON.parse(response);
  
  if (userInfo.hasOwnProperty("hd")) {
    return userInfo.email + " is using GSuite";
  }
  
  return userInfo.name + " is not using G Suite";

}

G Suite (Google Apps) users will have the hd attribute set to true while is not available for consumer account. One more thing – you’ll only know if a user belongs to G Suite domain, it won’t saying anything about the version of G Suite that a user has subscribed to.

A user could be part of basic GSuite (or the legacy version of Google Apps) or they could be on G Suite enterprise, the response would be the same.

Categories
Code

List All Users of a Google Apps Domain in Google Spreadsheets

The enterprise editions of Google Drive Auditor and Gmail Address Extractor use the Google Apps Admin SDK (Directory API) with Google Apps Script to create a list of all users that are part of a G Suite (Google Apps) domain.

The Google Scripts gets the name and email address of users in the organization and saves the list inside a Google Spreadsheet. This script can only be executed by the domain administrator.

function getDomainUsersList() {
  
  var users = [];
  var options = {
    domain: "ctrlq.org",     // Google Apps domain name
    customer: "my_customer",
    maxResults: 100,
    projection: "basic",      // Fetch basic details of users
    viewType: "domain_public",
    orderBy: "email"          // Sort results by users
  }
  
  do {
    var response = AdminDirectory.Users.list(options);
    response.users.forEach(function(user) {
      users.push([user.name.fullName, user.primaryEmail]);
    });
    
    // For domains with many users, the results are paged
    if (response.nextPageToken) {
      options.pageToken = response.nextPageToken;
    }
  } while (response.nextPageToken);
  
  // Insert data in a spreadsheet
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Users") || ss.insertSheet("Users", 1);
  sheet.getRange(1,1,users.length, users[0].length).setValues(users);
  
}

Remember to replace ctrlq.org with your own domain address. You will need to enable the Admin Directory API under Resources > Advanced Google Services.

Then go to Resources > Cloud Platform Project, click the Project name to open the Google Developer console associated with your Apps Script project. Switch to the Library section, search for Admin SDK and enable the API.

Categories
Code

Using Google Service Accounts with Google Apps Script

This sample code shows how to use OAuth in Google Apps Script using Service Accounts. The G Suite admin can access the Google Drive files of any user – the username or email address of the user you are trying to impersonate specified with the method setSubject.

For this code to work, you need to create a Google Service account with domain-wide delegation, substitute the private key and client client email with the actual values and also add the Client Id to your Google Apps admin console with the Drive API Scope. The OAuth 2.0 access tokens are stored in the Script Properties.


var JSON = {
    "private_key": "Your Private Key",
    "client_email": "serviceacount@project-ctrlq.iam.gserviceaccount.com",
    "client_id": "1234567890",
    "user_email": "amit@labnol.org"
};

function getOAuthService(user) {
    return OAuth2.createService("Service Account")
        .setTokenUrl('https://accounts.google.com/o/oauth2/token')
        .setPrivateKey(JSON.private_key)
        .setIssuer(JSON.client_email)
        .setSubject(JSON.user_email)
        .setPropertyStore(PropertiesService.getScriptProperties())
        .setParam('access_type', 'offline')
        .setScope('https://www.googleapis.com/auth/drive');
}

function getUserFiles() {
    var service = getOAuthService();
    service.reset();
    if (service.hasAccess()) {
        var url = 'https://www.googleapis.com/drive/v2/files?pageSize=1';
        var response = UrlFetchApp.fetch(url, {
            headers: {
                Authorization: 'Bearer ' + service.getAccessToken()
            }
        });
        Logger.log(response.getContentText());
    }
}

function reset() {
    var service = getOAuthService();
    service.reset();
}

It is important to specify the user’s email on behalf of whom you wish to run this application else you’ll get a “Not Authorized to access this resource/api” error.

Also, if you are getting the 403 Insufficient permission error, it is likely because the application is request access to API scopes that are not authorized in the Google Apps admin console. The invalid_grant error is likely due to incorrect date and time settings of the server that is hosting the application.

Categories
Docs

Google Add-ons Not Working for Google Apps

If your Google Add-ons are not working as expected or if you are unable to install Google Docs add-ons from the Chrome store, it is likely that your Google Apps admin has disabled the setting that allows domain users to use add-ons.

Google Apps Add-ons

Here’s how they can enable add-ons for your Google Account from the Google Apps admin dashboard.

Step 1 – Login to your Google Apps admin console at admin.google.com

Step 2 – Go to Apps -> Google Apps -> Drive and make sure the status is “ON” for everyone.

Step 3 – Go to Apps -> Google Apps -> Settings for Google Drive -> Data Access and enable the following settings.

– Drive SDK (Allow users to install Google Drive apps)
Google Drive apps allow users to open their files in web apps installed from the Chrome Web Store.

– Add-Ons (Allow users to install Google Docs add-ons from add-ons store)
Docs add-ons allow users to use Docs features built by other developers.

The Admin console setting for add-ons controls Docs, Sheets, and Forms; there are not separate settings for each document type.