googleworkspace / apps-script-samples

Apps Script samples for Google Workspace products.
https://developers.google.com/apps-script
Apache License 2.0
4.54k stars 1.85k forks source link

data-studio/auth.gs doesn't guarantee authorisation. #184

Open wiktor-cobry opened 3 years ago

wiktor-cobry commented 3 years ago

It's this method in question.

Expected Behavior

The code sample should either:

  1. State that the hasAccess() method does not guarantee authorisation as it states in the documentation.
  2. Include an additional code example that probes the API, and returns the authorisation state from the response code.

Description: This code sample suggests that calling the hasAccess() method guarantees authorisation. This isn't true.

/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */
function isAuthValid() {
  return getOAuthService().hasAccess();
}

Actual Behavior

The response code needs to be handled to fully confirm authorisation state, or the documentation should suggest that the hasAccess() method doesn't guarantee authorisation. Similar to the way the call is handled in the Google Workspace Addons Documentation

lewis-conroy commented 3 years ago

Here's a suggestion as to what that function could look like

/**
 * Returns true if the token is accepted by the API.
 * Returns false if the API responds with a 401 status code (i.e. it was rejected)
 * @return {boolean} True if the token is accepted by the API.
*/
function isTokenValid() {
  var token = getOauthService().getAccessToken();
  var apiEndpoint = "your endpoint here";
  var apiResponse = UrlFetchApp.fetch(`${apiEndpoint}`, {
    headers: {
      'Authorization': `Bearer ${token}`
    },
    muteHttpExceptions: true
  });
  var jsonResponse = JSON.parse(apiResponse);
  if (jsonResponse.status == "401") {
    return false;
  }
  else {
    return true;
  }
}