Search code examples
google-apps-scriptpasswordspassword-protection

Password Protect Google Apps Script


so I have created a small script here for my google sheets. Since google sheets doesn't allow you to use password protection on individual sheets, I was wondering if there was a way to protect my script with a password so that only certain people can use it. Here is my code.

function onOpen() {
  SpreadsheetApp.getUi()
      .createMenu('Custom Menu')
      .addItem('Record', 'Record')
      .addItem('Cancelation', 'Cancel')
      .addToUi();
}

function Record() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Nightly Stats'),
    row = sheet.getLastRow()
    range = sheet.getRange("A3:G3");
  sheet.insertRowAfter(row);
    range.copyTo(sheet.getRange(row + 1, 1), {contentsOnly:true});
}

I would greatly appreciate any suggestions that you can provide.


Solution

  • Ok so I actually figured out how to do a password system via prompting. Here was what I did in case anyone needs this in the future.

    function Cancel() {
      var SS = SpreadsheetApp.getActiveSpreadsheet();
      var ui = SpreadsheetApp.getUi();
    
      // first prompt
      var presult = ui.prompt(
        "Please Enter the Password to Use this Feature.",
        ui.ButtonSet.OK_CANCEL);
    
      var password = "Test";
      var pbutton = presult.getSelectedButton();
      var ptext = presult.getResponseText();
    
      // User clicked "OK" on first prompt
      if (pbutton == ui.Button.CANCEL) {
        ui.alert('The Process Was Ended.');
        } else if (pbutton == ui.Button.CLOSE) {
          ui.alert('The Process Was Ended.');
        } else if (ptext != password) {
          Password();   
        } else {
          "Insert whatever action you would want them to do after the password works here"
        }
      }
    
    function Password() {
      var SS = SpreadsheetApp.getActiveSpreadsheet();
      var ui = SpreadsheetApp.getUi();
      var response = ui.alert("The Password is Incorrect. Retry?",
          ui.ButtonSet.OK_CANCEL);
    
      if (response == ui.Button.CANCEL) {
        ui.alert("The Process Was Ended.");
      } else if (response == ui.Button.CLOSE) {
        ui.alert("The Process Was ended.");
      } else {
        Cancel();
      }
    }
    

    I only gave a piece of the code so sorry if it looks a little weird. I just didn't want to give the whole code and make you search for everything. Hope that helps :)