I try to complete the following values in order to execute an application to put signatures to all users of a G Suite domain:
Some weeks ago, it was ok, but now I can't save the correct values to finish the configuration. I hope someone knows what is happening.
UPDATE 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;
}
You need to get an access token to make the PUT request: getAdminService().getAccessToken()
The Options:
var options = {
"method":"PUT",
"headers": {"authorization": "Bearer " + getAdminService().getAccessToken()},
"payload":xmlRaw,
"contentType":"application/atom+xml"
}
The access token is being chained to getAdminService()
And it looks like the scope that you need is:
'https://apps-apis.google.com/a/feeds/emailsettings/2.0/'
You could try setting that scope directly in the manifest file:
{
"timeZone": "Your time zone here",
"exceptionLogging": "STACKDRIVER",
"oauthScopes": ["https://apps-apis.google.com/a/feeds/emailsettings/2.0/",
"All",
"Your",
"Other",
"Scopes"]
}
To get all your other scopes, in the File menu, choose Project Properties, and then choose the Scopes tab. Copy out the scopes. Then in the View menu, view the manifest file. Modify the manifest file.
So, what that does, when you set the scopes in the manifest file, is that Apps Script manages the OAuth stuff internally. You may not need a library.
Then you can just get the token with: var token = ScriptApp.getOAuthToken();
So, you would end up with:
var token = ScriptApp.getOAuthToken();
var options = {
"method":"PUT",
"headers": {"authorization": "Bearer " + token},
"payload":xmlRaw,
"contentType":"application/atom+xml"
}
If you are using the HTML Service, and web app, and call back just to get the OAuth token, then you don't need any of that, and you don't even need to use the Google Cloud console.