Skip to content

Instantly share code, notes, and snippets.

@pfelipm
Last active October 3, 2022 15:59
Show Gist options
  • Save pfelipm/3a0c07424b62d00a4b15dc664a997b0e to your computer and use it in GitHub Desktop.
Save pfelipm/3a0c07424b62d00a4b15dc664a997b0e to your computer and use it in GitHub Desktop.
/**
* Demo authorization workflow that checks whether the current user can run this Apps Script, uses
* the Admin SDK Directory Advanced Service
* Twitter thread here: https://twitter.com/pfelipm/status/1576954653425618945
* @pfelipm (OCT/22)
*
* @OnlyCurrentDoc
*/
// Generates the proper script's menu depending on the activation status for current user
function onOpen(e) {
const status = PropertiesService.getScriptProperties()
.getProperty(Session.getActiveUser().getEmail());
buildMenu(JSON.parse(status));
}
// Builds the script's menu, 3 possibilites:
// (1) status === true → real menu
// (2) status === false → fake menu with a warning
// (3) status === null → Only displays an activation command
function buildMenu(status) {
const ui = SpreadsheetApp.getUi();
switch (status) {
case true:
ui.createMenu('My script')
.addItem('Run automation', 'run')
.addToUi();
break;
case false:
ui.createMenu('My script')
.addItem('⛔ Sorry, you should not attempt to use this script', 'doNothing')
.addToUi();
break;
case null:
ui.createMenu('My script')
.addItem('🚨 Activate script first (run twice!)', 'activate')
.addToUi();
break;
}
}
// Script activation
function activate() {
const userEmail = Session.getActiveUser().getEmail();
const canRun = checkRun(userEmail);
PropertiesService.getScriptProperties()
.setProperty(userEmail, JSON.stringify(canRun));
buildMenu(canRun);
}
// Check function to decide if the current user should attempt to run the script
// (e.g., if Google Workspace Admin)
function checkRun(userEmail) {
let isAdmin = false;
try {
isAdmin = AdminDirectory.Users.get(userEmail, { viewType: 'admin_view' }).isAdmin;
} catch {}
return isAdmin;
}
// Does nothing (when invoked from a dummy menu command)
function doNothing() {
SpreadsheetApp.getUi().alert(`No, you shouldn't, right?`);
}
// Actual script's code comes in here...
function run() {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment