Kinjal Vora
May 26, 2021

Setting up Domain wide delegation on Gsuite

Setting up Domain wide delegation on gsuite with DronaHQ Low Code If you are building internal tools you would come across scenarios where you would want the internal tool to send emails from a user account or access their specific files in their drive account via APIs. >

For example in the CRM tool you would want to build a feature to let users send email using their email address and you even see them in the outbox, look at the thread and reply to the specific email in the thread. This scenario means the apps must have a mechanism to let the user authorise using their account to achieve the use cases like sending emails or accessing drive. In DronaHQ’s low code world – we have infrastructure to work with server side authentication.

So in order to achieve our use case we will have to follow the below steps:

  1. Open an appscript in Gsuite
  2. Add library oauth2
  3. Create a domain wide authentication servicefunction getDomainWideDelegationService(serviceName, scope, email) { Logger.log(‘starting getDomainWideDelegationService for email: ‘ + email); return OAuth2.createService(serviceName + email)

    // Set the endpoint URL.
    //.setTokenUrl(‘https://accounts.google.com/o/oauth2/token’)
    .setTokenUrl(‘https://www.googleapis.com/oauth2/v4/token’)
    //.setAuthorizationBaseUrl(‘https://accounts.google.com/o/oauth2/auth’) // Set the private key and issuer.
    .setPrivateKey(JSON_1.private_key)
    //.setIssuer(OAUTH2_SERVICE_ACCOUNT_CLIENT_EMAIL)
    .setIssuer(JSON_1.client_email)
    .setSubject(email) // Set the name of the user to impersonate. This will only work for
    // Google Apps for Work/EDU accounts whose admin has setup domain-wide
    // delegation:
    // https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority
    //.setSubject(email) // Set the property store where authorized tokens should be persisted.
    .setPropertyStore(PropertiesService.getScriptProperties()) // Set the scope. This must match one of the scopes
    onfigured during the
    // setup of domain-wide delegation.
    .setScope(scope);}

    or use the documentation here to setup the scripts

  4. Build gsuite services to send email/access drive/etc. Here is the snippet to send email –function sendEmail(email,toEmail,fromName,toName,subject,body) { //var email= “jinen@dronahq.com”; Logger.log(‘starting setSignature’); var signatureSetSuccessfully = false; var service = getDomainWideDelegationService(‘Gmail: ‘, ‘ https://mail.google.com/ https://www.googleapis.com/auth/script.external_request https://www.googleapis.com/auth/script.send_mail https://www.googleapis.com/auth/spreadsheets’, email); if (!service.hasAccess()) { Logger.log(‘failed to authenticate as user ‘ + email); Logger.log(service.getLastError()); signatureSetSuccessfully = service.getLastError(); return signatureSetSuccessfully; } else Logger.log(‘successfully authenticated as user ‘ + email); var username = email.split(“@”)[0]; var pl= messg(toName,toEmail,subject,body,fromName,email);
    var jsonMessage={
    “raw”: pl,
    “mimeType”: “text/html; charset=utf-8”
    }; var RequestUrl = “https://www.googleapis.com/gmail/v1/users/”+email+”/messages/send”;var RequestArguments = {
    headers: {Authorization: ‘Bearer ‘ + service.getAccessToken()},
    method: “post”,
    contentType: “application/json”,
    payload: JSON.stringify(jsonMessage)
    }; try{
    var result = UrlFetchApp.fetch(RequestUrl,RequestArguments);
    var data = result.getContentText();
    var json = JSON.parse(data);
    Logger.log(result);
    }
    catch(e)
    {
    Logger.log(‘semail sending issue: ‘ + e);
    }
    service.reset();
    return json;
    }

    Now you are all set to use the “sendEmail” service from your scripts.

  5. Publish the script as an api executable and and enable gsuite APIs. (Follow the guide here to set up the gsuite authentication client)
  6. Create a REST API oAuth 2 service in DronaHQ and register gsuite service and test & save to let your API service be now available to the studio.
Copyright © Deltecs Infotech Pvt Ltd. All Rights Reserved