使用 OAuth 令牌通过 Apps 脚本连接到 GSuite 管理服务 - 范围 https://apps-apis.google.com/a/feeds/emailsettings/2.0/
Connect to GSuite Admin Service through Apps Script with OAuth token - scope https://apps-apis.google.com/a/feeds/emailsettings/2.0/
我尝试完成以下值以执行应用程序以将签名添加到 G Suite 域的所有用户:
几周前还可以,但现在我无法保存正确的值来完成配置。我希望有人知道发生了什么。
更新 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,'&');
str = str.replace(/</g,'<');
str = str.replace(/\"/g,'"');
str = str.replace(/>/g,'>');
str = str.replace(/nbsp;/g,'#160;');
return str;
}
您需要获取访问令牌才能发出 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"]
}
要获取所有其他范围,请在“文件”菜单中选择“项目属性”,然后选择“范围”选项卡。复制范围。然后在“查看”菜单中,查看清单文件。修改清单文件。
那么,当您在清单文件中设置范围时,Apps 脚本会在内部管理 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 云控制台。
我尝试完成以下值以执行应用程序以将签名添加到 G Suite 域的所有用户:
几周前还可以,但现在我无法保存正确的值来完成配置。我希望有人知道发生了什么。
更新 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,'&');
str = str.replace(/</g,'<');
str = str.replace(/\"/g,'"');
str = str.replace(/>/g,'>');
str = str.replace(/nbsp;/g,'#160;');
return str;
}
您需要获取访问令牌才能发出 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"]
}
要获取所有其他范围,请在“文件”菜单中选择“项目属性”,然后选择“范围”选项卡。复制范围。然后在“查看”菜单中,查看清单文件。修改清单文件。
那么,当您在清单文件中设置范围时,Apps 脚本会在内部管理 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 云控制台。