Skip to content

Instantly share code, notes, and snippets.

Last active October 3, 2022 15:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
* Demo authorization workflow that checks whether the current user can run this Apps Script, uses
* the Admin SDK Directory Advanced Service
* Twitter thread here:
* @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()
// 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')
case false:
ui.createMenu('My script')
.addItem('⛔ Sorry, you should not attempt to use this script', 'doNothing')
case null:
ui.createMenu('My script')
.addItem('🚨 Activate script first (run twice!)', 'activate')
// Script activation
function activate() {
const userEmail = Session.getActiveUser().getEmail();
const canRun = checkRun(userEmail);
.setProperty(userEmail, JSON.stringify(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