通过带有OAuth令牌的应用脚本连接到GSuite管理服务 - 范围https://apps-apis.google.com/a/feeds/emailsettings/2.0/

时间:2018-03-05 23:56:12

标签: google-apps-script oauth access-token gsuite

我尝试完成以下值,以便执行将签名放入G Suite域的所有用户的应用程序:

enter image description here

enter image description here

几周前,没关系,但现在我无法保存正确的值来完成配置。我希望有人知道发生了什么。提前致谢。 的问候,

更新1:

AdminOauth2.gs

function getAdminService() {

return OAuth2.createService('AdminEmail')
  .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth')
  .setTokenUrl('https://accounts.google.com/o/oauth2/token')
  .setClientId(PropertiesService.getScriptProperties()
               .getProperty("clientId"))
  .setClientSecret(PropertiesService.getScriptProperties()
               .getProperty("clientSecret"))
  .setCallbackFunction('authCallback')
  .setPropertyStore(PropertiesService.getUserProperties())
  .setScope('https://apps-apis.google.com/a/feeds/emailsettings/2.0/')
  .setParam('login_hint', Session.getActiveUser().getEmail())
  .setParam('access_type', 'offline')
  .setParam('approval_prompt', 'force');
 }

function showAuthWindow() {
  var adminService = getAdminService();
  if (!adminService.hasAccess()) {
     var authorizationUrl = adminService.getAuthorizationUrl();
     var template = HtmlService.createTemplate(
    '<a href="<?= authorizationUrl ?>" target="_blank">Authorize</a> ');
    template.authorizationUrl = authorizationUrl;
    var page = template.evaluate();
    return page;
 } else {
  return HtmlService.createHtmlOutput("You have already authorized this service");
 }
}

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

function clearService(){
  OAuth2.createService('AdminEmail')
  .setPropertyStore(PropertiesService.getUserProperties())
  .reset();
}

codigo.gs

/*AdminOauth2*/
function doGet(){
 return showAuthWindow();
}

function authScript(){
  return true;
}

var KEY = "midominio.com"; // Dominio

var USERSHEETNAME  = "Usuarios"
var ADMINSHEETNAME = "Administración";

var USUARIOCOL   = "Nombre de usuario";
var ESDITIMECOL  = "Marca temporal";

function updateAllSignatures(){
   Logger.log('[updateAllSignatures]');
   var allDatas = getAllDatas();
   var recover = allDatas.admin.sheet.getRange(1, 1, 1, 1).getValues();
   var i;
   if (recover[0][0] == ""){
      i = 0;
   }else {
      i = recover;
   }

  var status;
  for (i ; i < allDatas.user.values.length ; i++){
    //Logger.log(allDatas.user.values.length);
  if (i > 0){
    var col = allDatas.user.titles[USUARIOCOL];
    var userValues = allDatas.user.values;
    var user = userValues[i][col];

  //generate signature for each users
   var signature = generateSignature(allDatas, user);
   status = updateSignature(user, signature);
   if (status != 200){
     return;
   }

  allDatas.admin.sheet.getRange(1, 1, 1, 1).setValues([[i]]);
  }
 }
 allDatas.admin.sheet.getRange(1, 1, 1, 1).setValues([[""]]);
 if (status == "200"){
   Logger.log("El script se ejecutó en su totalidad");
  }
  return;
}


function generateSignature(allDatas, userName){
  var signTplt = "";
  var user = userName.split("@")[0];
  var domain = userName.split("@")[1];


  var column=0;
  var i;
  for (i in allDatas.admin.values[0]){
    if (allDatas.admin.values[0][i] == domain ){
    column = i;
    }
  }
 if (column>0){
   signTplt = allDatas.admin.values[1][column];

   var userLine = allDatas.user.line[userName];
   var userData = allDatas.user.values[userLine];
   var titleData = allDatas.user.values[0];

 // foreach columns in data
 for (j in userData){
  if (userData[j] != ""){
    for (k in allDatas.admin.values){
      if (allDatas.admin.values[k][0] == titleData[j]+"_"){
        if (signTplt.split("["+allDatas.admin.values[k][0]+"]")[1] != null){
          signTplt = signTplt.split("["+allDatas.admin.values[k][0]+"]")[0]+allDatas.admin.values[k][column]+signTplt.split("["+allDatas.admin.values[k][0]+"]")[1];
        }//else{
          //signTplt = signTplt.split("["+allDatas.admin.values[k][0]+"]")[0]+signTplt.split("["+allDatas.admin.values[k][0]+"]")[1];
        //}
      }
    }
    if (signTplt.split("["+titleData[j]+"]")[1] != null){
      signTplt = signTplt.split("["+titleData[j]+"]")[0]+userData[j]+signTplt.split("["+titleData[j]+"]")[1];
    }
  }else{
    switch (titleData[j]){
      case "Cel Phone":
      default:
        if (signTplt.split("["+titleData[j]+"]")[1] != null){
          signTplt = signTplt.split("["+titleData[j]+"]")[0]+signTplt.split("["+titleData[j]+"]")[1];
        }
        if (signTplt.split("["+titleData[j]+"_]")[1] != null){
          signTplt = signTplt.split("["+titleData[j]+"_]")[0]+signTplt.split("["+titleData[j]+"_]")[1];
        }

        break;
    }

  }
  var temp=0
  }
 }
 return signTplt;
}

/**
* updateSignature(usuario, signature) //update the signature of user
**/
function updateSignature(usuario, signature) {
  var userName = usuario.split("@")[0]
  var domain = usuario.split("@")[1]
  var scope = 'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
  var xmlRaw = '<?xml version="1.0" encoding="utf-8"?>'+
'<atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006">'+
  '<apps:property name="signature" value="'+htmlEncode(signature)+'" />'+
    '</atom:entry>'
  var name = 'signature'

  var base="https://apps-apis.google.com/a/feeds/emailsettings/2.0/";
  var url = base + domain + '/' + userName + '/signature';

  var options = {
                 "method":"PUT",
                 "headers": {"authorization": "Bearer " + getAdminService().getAccessToken()},
                 "payload":xmlRaw,
                 "contentType":"application/atom+xml"
                }

  var url = scope+domain+'/'+userName+'/signature'
  var urlFetch
  var results
  var status = ""

  try{
    results =  UrlFetchApp.fetch(url, options);
    Logger.log(results)

    status = results.getResponseCode()

    Logger.log(status)

    if (status != "200") {
      Logger.log("imposible to apply signature for this domain : " + status)
      Logger.log("Un error occurio. Verificar que el usuario : " + usuario + " esta valido verifica la cuenta principal del usuario en el panel de administracion Google Apps o aplica la firma para todos una vez")
    }
  }catch (e){
    Logger.log("El usuario " + usuario + " no existe. Error detail:" + e)
    return 200;
   }
return status;
}

 /**
 * htmlEncode(str) //replace element to comply with html code
 **/
function htmlEncode(str){
 str = str.replace(/&/g,'&#38;');
 str = str.replace(/</g,'&#60;');
 str = str.replace(/\"/g,'&#34;');
 str = str.replace(/>/g,'&#62;');
 str = str.replace(/nbsp;/g,'#160;');
 return str;
}

1 个答案:

答案 0 :(得分:1)

您需要获取访问令牌才能发出PUT请求:getAdminService().getAccessToken()

选项:

var options = {
             "method":"PUT",
             "headers": {"authorization": "Bearer " + getAdminService().getAccessToken()},
             "payload":xmlRaw,
             "contentType":"application/atom+xml"
            }

访问令牌被链接到getAdminService()

看起来你需要的范围是:

'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'

您可以尝试直接在清单文件中设置该范围:

appsscript.json

{
  "timeZone": "Your time zone here",
  "exceptionLogging": "STACKDRIVER",
  "oauthScopes": ["https://apps-apis.google.com/a/feeds/emailsettings/2.0/",
              "All",
              "Your", 
              "Other", 
              "Scopes"]
}

要获取所有其他范围,请在“文件”菜单中选择“项目属性”,然后选择“范围”选项卡。复制范围。然后在“视图”菜单中,查看清单文件。修改清单文件。

因此,当您在清单文件中设置范围时,应用程序脚本在内部管理OAuth内容。您可能不需要图书馆。

然后您可以使用:var token = ScriptApp.getOAuthToken();

获取令牌

所以,你最终会得到:

var token = ScriptApp.getOAuthToken();

var options = {
             "method":"PUT",
             "headers": {"authorization": "Bearer " + token},
             "payload":xmlRaw,
             "contentType":"application/atom+xml"
            }

如果您使用的是HTML服务和网络应用,并回拨只是为了获取OAuth令牌,那么您就不需要这些,甚至不需要使用Google云控制台。