Web App Development with Google Apps Script/authentication

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Why authenticate?[edit | edit source]

Quite often you'll want to protect your web app to ensure only certain people can use it. When you publish your page you have a few options in two major categories:

  1. Who has access (who can get to the page)?
    1. Just you
    2. Anyone in your domain (hamline.edu for me)
    3. Anyone
  2. Which account is being used to run the script?
    1. Yours (even when other people access)
    2. Theirs (won't work with "anyone" above)

Those are useful but they're a little coarse grained. Sometimes you'll want only certain people to either have access and/or be able to do certain things.

Who is accessing?[edit | edit source]

For this section we'll assume you've set "who has access" to "anyone in your domain." If you do then you can determine who is accessing like this:

var email = Session.getActiveUser().getEmail();

Are they allowed?[edit | edit source]

Once you have the user's email, you can check it against a sheet in your spreadsheet that has allowed users and perhaps other information about them, like what things they're allowed to do. Let's assume you have a sheet that looks like this:

"my users" sheet
email name role
arundquist@hamline.edu Andy Rundquist admin
test1@hamline.edu Testy McTesterson student
test2@hamline.edu Tess Tesserson faculty

Then we could authenticate the user like this:

var email = Session.getActiveUser().getEmail();
var usersData=SpreadsheetApp.getActive().getSheetByName("my users").getDataRange().getValues();
usersData.shift() // gets rid of headers row
var user = usersData.find(r=>r[0]==email);
if (!user) {
   return HtmlService.createHtmlOutput("sorry, nothing for you here");
// now do something cool with the user
var role=user[2]; // not 3, remember how array numbering works
if (role == 'admin') {
   // do cool things here
// etc