Web App Development with Google Apps Script/authentication
Why authenticate?
editQuite 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:
- Who has access (who can get to the page)?
- Just you
- Anyone in your domain (hamline.edu for me)
- Anyone
- Which account is being used to run the script?
- Yours (even when other people access)
- 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?
editFor 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?
editOnce 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:
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