Autenticação

Os conectores da comunidade são compatíveis com os seguintes métodos de autenticação:

  • OAuth 2.0
  • Caminho/nome de usuário/senha
  • Caminho/chave
  • Nome de usuário/senha
  • Nome de usuário/token
  • Chave
  • Nada

Dependendo do método usado, você precisa disponibilizar funções adicionais no seu conector.

A tabela a seguir indica quais funções você deve definir dependendo do tipo de autenticação do conector.

OAUTH2 PATH_USER_PASS
PATH_KEY
USER_PASS
USER_TOKEN
KEY
NENHUMA
getAuthType() obrigatório obrigatório obrigatório
resetAuth() obrigatório obrigatório
isAuthValid() obrigatório obrigatório
authCallback() obrigatório
get3PAuthorizationUrls() obrigatório
setCredentials() obrigatório

getAuthType()

Esta função deve retornar o tipo de autenticação do conector.

data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */

function getAuthType() {
 
var cc = DataStudioApp.createCommunityConnector();
 
return cc.newAuthTypeResponse()
     
.setAuthType(cc.AuthType.OAUTH2)
     
.build();
}
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */

function getAuthType() {
 
var cc = DataStudioApp.createCommunityConnector();
 
return cc.newAuthTypeResponse()
   
.setAuthType(cc.AuthType.PATH_USER_PASS)
   
.setHelpUrl('https://www.example.org/connector-auth-help')
   
.build();
}
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */

function getAuthType() {
 
var cc = DataStudioApp.createCommunityConnector();
 
return cc.newAuthTypeResponse()
   
.setAuthType(cc.AuthType.PATH_KEY)
   
.setHelpUrl('https://www.example.org/connector-auth-help')
   
.build();
}
data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */

function getAuthType() {
 
var cc = DataStudioApp.createCommunityConnector();
 
return cc.newAuthTypeResponse()
     
.setAuthType(cc.AuthType.USER_PASS)
     
.setHelpUrl('https://www.example.org/connector-auth-help')
     
.build();
}
data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */

function getAuthType() {
 
var cc = DataStudioApp.createCommunityConnector();
 
return cc.newAuthTypeResponse()
     
.setAuthType(cc.AuthType.USER_TOKEN)
     
.setHelpUrl('https://www.example.org/connector-auth-help')
     
.build();
}
data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */

function getAuthType() {
 
var cc = DataStudioApp.createCommunityConnector();
 
return cc.newAuthTypeResponse()
     
.setAuthType(cc.AuthType.KEY)
     
.setHelpUrl('https://www.example.org/connector-auth-help')
     
.build();
}
data-studio/auth.gs
/**
 * Returns the Auth Type of this connector.
 * @return {object} The Auth type.
 */

function getAuthType() {
 
var cc = DataStudioApp.createCommunityConnector();
 
return cc.newAuthTypeResponse()
     
.setAuthType(cc.AuthType.NONE)
     
.build();
}

resetAuth()

Esta função limpará todas as credenciais do usuário armazenadas para o serviço de terceiros.

data-studio/auth.gs
/**
 * Resets the auth service.
 */

function resetAuth() {
  getOAuthService
().reset();
}
/**
 * Resets the auth service.
 */

function resetAuth() {
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.deleteProperty('dscc.path');
  userProperties
.deleteProperty('dscc.username');
  userProperties
.deleteProperty('dscc.password');
}
/**
 * Resets the auth service.
 */

function resetAuth() {
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.deleteProperty('dscc.path');
  userProperties
.deleteProperty('dscc.key');
}
data-studio/auth.gs
/**
 * Resets the auth service.
 */

function resetAuth() {
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.deleteProperty('dscc.username');
  userProperties
.deleteProperty('dscc.password');
}
data-studio/auth.gs
/**
 * Resets the auth service.
 */

function resetAuth() {
 
var userTokenProperties = PropertiesService.getUserProperties();
  userTokenProperties
.deleteProperty('dscc.username');
  userTokenProperties
.deleteProperty('dscc.password');
}
data-studio/auth.gs
/**
 * Resets the auth service.
 */

function resetAuth() {
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.deleteProperty('dscc.key');
}

isAuthValid()

Esta função é chamada para determinar se a autenticação do serviço de terceiros é válida. Se a autenticação for válida, espera-se que as chamadas para getData() e getSchema() não vão falhar devido a acesso não autorizado. Caso contrário, o usuário poderá receber uma notificação para iniciar o fluxo de autorização.

data-studio/auth.gs
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */

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

function isAuthValid() {
 
var userProperties = PropertiesService.getUserProperties();
 
var path = userProperties.getProperty('dscc.path');
 
var userName = userProperties.getProperty('dscc.username');
 
var password = userProperties.getProperty('dscc.password');
 
// This assumes you have a validateCredentials function that
 
// can validate if the path, userName and password are correct.
 
return validateCredentials(path, userName, password);
}
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */

function isAuthValid() {
 
var userProperties = PropertiesService.getUserProperties();
 
var path = userProperties.getProperty('dscc.path');
 
var key = userProperties.getProperty('dscc.key');
 
// This assumes you have a validateCredentials function that
 
// can validate if the path and key are correct.
 
return validateCredentials(path, key);
}
data-studio/auth.gs
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */

function isAuthValid() {
 
var userProperties = PropertiesService.getUserProperties();
 
var userName = userProperties.getProperty('dscc.username');
 
var password = userProperties.getProperty('dscc.password');
 
// This assumes you have a validateCredentials function that
 
// can validate if the userName and password are correct.
 
return validateCredentials(userName, password);
}
data-studio/auth.gs
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */

function isAuthValid() {
 
var userProperties = PropertiesService.getUserProperties();
 
var userName = userProperties.getProperty('dscc.username');
 
var token = userProperties.getProperty('dscc.token');
 
// This assumes you have a validateCredentials function that
 
// can validate if the userName and token are correct.
 
return validateCredentials(userName, token);
}
data-studio/auth.gs
/**
 * Returns true if the auth service has access.
 * @return {boolean} True if the auth service has access.
 */

function isAuthValid() {
 
var userProperties = PropertiesService.getUserProperties();
 
var key = userProperties.getProperty('dscc.key');
 
// This assumes you have a validateKey function that can validate
 
// if the key is valid.
 
return validateKey(key);
}

OAUTH2

Adicionar e configurar o OAuth2 para a biblioteca do Apps Script

Siga as instruções de configuração da biblioteca do OAuth2 para Apps Script para adicioná-la ao seu projeto de conector. Depois, siga a primeira etapa guia de uso para criar um serviço OAuth2 no seu conector projeto. O serviço do OAuth2 pode ter qualquer nome de função válido. No entanto, use o mesmo nome ao fazer referência ao serviço do OAuth2 no seu código.

Por exemplo, um serviço do OAuth2 chamado exampleService:

data-studio/auth.gs
/**
 * Returns the configured OAuth Service.
 * @return {Service} The OAuth Service
 */

function getOAuthService() {
 
return OAuth2.createService('exampleService')
     
.setAuthorizationBaseUrl('...')
     
.setTokenUrl('...')
     
.setClientId('...')
     
.setClientSecret('...')
     
.setPropertyStore(PropertiesService.getUserProperties())
     
.setCallbackFunction('authCallback')
     
.setScope('...');
};

authCallback()

Esta função é chamada para concluir o fluxo do OAuth 2.0. A resposta de retorno de chamada do serviço de autenticação de terceiros é disponibilizada como um argumento e deve ser tratada por essa função.

Exemplo de tratamento do retorno de chamada do OAuth 2.0 usando a biblioteca do OAuth2 para Apps Script:

data-studio/auth.gs
/**
 * The OAuth callback.
 * @param {object} request The request data received from the OAuth flow.
 * @return {HtmlOutput} The HTML output to show to the user.
 */

function authCallback(request) {
 
var authorized = getOAuthService().handleCallback(request);
 
if (authorized) {
   
return HtmlService.createHtmlOutput('Success! You can close this tab.');
 
} else {
   
return HtmlService.createHtmlOutput('Denied. You can close this tab');
 
};
};

get3PAuthorizationUrls()

Esta função é chamada para visualizar o URL que é necessário para iniciar o fluxo de autenticação do serviço de terceiros. Se isAuthValid retornar false, então o URL retornados serão exibidos ao usuário como um botão ou link para que ele possa autorizar o acesso ao serviço de terceiros. Consulte a referência para get3PAuthorizationUrls().

Exemplo de devolução do URL de autorização usando a biblioteca do OAuth2 para Apps Script:

data-studio/auth.gs
/**
 * Gets the 3P authorization URL.
 * @return {string} The authorization URL.
 * @see https://developers.google.com/apps-script/reference/script/authorization-info
 */

function get3PAuthorizationUrls() {
 
return getOAuthService().getAuthorizationUrl();
}
.

USER_PASS, USER_TOKEN, KEY, PATH_USER_PASS e PATH_KEY

Os dados a seguir só são necessários para USER_PASS, USER_TOKEN, KEY PATH_USER_PASS e PATH_KEY.

setCredentials()

setCredentials é chamado depois que o usuário insere a credencial na página de configuração do conector da comunidade. Use o método Serviço de propriedades para salvar as credenciais por usuário usando UserProperties.

/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */

function setCredentials(request) {
 
var creds = request.pathUserPass;
 
var path = creds.path;
 
var username = creds.username;
 
var password = creds.password;

 
// Optional
 
// Check if the provided path, username and password are valid through
 
// a call to your service. You would have to have a `checkForValidCreds`
 
// function defined for this to work.
 
var validCreds = checkForValidCreds(path, username, password);
 
if (!validCreds) {
   
return {
      errorCode
: 'INVALID_CREDENTIALS'
   
};
 
}
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.setProperty('dscc.path', path);
  userProperties
.setProperty('dscc.username', username);
  userProperties
.setProperty('dscc.password', password);
 
return {
    errorCode
: 'NONE'
 
};
}
/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */

function setCredentials(request) {
 
var creds = request.pathKey;
 
var path = creds.path;
 
var key = creds.key;

 
// Optional
 
// Check if the provided path and key are valid through
 
// a call to your service. You would have to have a `checkForValidCreds`
 
// function defined for this to work.
 
var validCreds = checkForValidCreds(path, key);
 
if (!validCreds) {
   
return {
      errorCode
: 'INVALID_CREDENTIALS'
   
};
 
}
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.setProperty('dscc.path', path);
  userProperties
.setProperty('dscc.key', key);
 
return {
    errorCode
: 'NONE'
 
};
}
data-studio/auth.gs
/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */

function setCredentials(request) {
 
var creds = request.userPass;
 
var username = creds.username;
 
var password = creds.password;

 
// Optional
 
// Check if the provided username and password are valid through a
 
// call to your service. You would have to have a `checkForValidCreds`
 
// function defined for this to work.
 
var validCreds = checkForValidCreds(username, password);
 
if (!validCreds) {
   
return {
      errorCode
: 'INVALID_CREDENTIALS'
   
};
 
}
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.setProperty('dscc.username', username);
  userProperties
.setProperty('dscc.password', password);
 
return {
    errorCode
: 'NONE'
 
};
}
data-studio/auth.gs
/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */

function setCredentials(request) {
 
var creds = request.userToken;
 
var username = creds.username;
 
var token = creds.token;

 
// Optional
 
// Check if the provided username and token are valid through a
 
// call to your service. You would have to have a `checkForValidCreds`
 
// function defined for this to work.
 
var validCreds = checkForValidCreds(username, token);
 
if (!validCreds) {
   
return {
      errorCode
: 'INVALID_CREDENTIALS'
   
};
 
}
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.setProperty('dscc.username', username);
  userProperties
.setProperty('dscc.token', token);
 
return {
    errorCode
: 'NONE'
 
};
}
data-studio/auth.gs
/**
 * Sets the credentials.
 * @param {Request} request The set credentials request.
 * @return {object} An object with an errorCode.
 */

function setCredentials(request) {
 
var key = request.key;

 
// Optional
 
// Check if the provided key is valid through a call to your service.
 
// You would have to have a `checkForValidKey` function defined for
 
// this to work.
 
var validKey = checkForValidKey(key);
 
if (!validKey) {
   
return {
      errorCode
: 'INVALID_CREDENTIALS'
   
};
 
}
 
var userProperties = PropertiesService.getUserProperties();
  userProperties
.setProperty('dscc.key', key);
 
return {
    errorCode
: 'NONE'
 
};
}