Apparently the script would work for anyone having an email id in the same workspace domain, but it would not work for users with generic @gmail.com email ids.
Session.getActiveuser.getEmail() has the problem that it would need the script to run as the user who is logging in (and not as the creator of the script). Apparently this restriction does not apply for users within the same google workspace -
"the user's email address is not available in any context that allows a script to run without that user's authorization, like a simple onOpen(e) or onEdit(e) trigger, a custom function in Google Sheets, or a web app deployed to "execute as me" (that is, authorized by the developer instead of the user). However, these restrictions generally do not apply if the developer runs the script themselves or belongs to the same Google Workspace domain as the user."
So, made a workaround - first, a script which will run as the user who is logging in, which will get the email - and then POST it to the second script, which will run as the creator of the script, which will process the information. At the POST step, we could add our own authentication using some salted hash etc.
The first script would be something like -
function doGet(e) {
let userEmail = Session.getActiveUser().getEmail();
let targetUrl = "https://script.google.com/macros/s/AKfycbyx4CbCNIpgmLd2iaWF4buFh_WZtIyOY3vpwdht_Gillycyflpgu1C2bN-j77P2CD3j/exec"; // Replace with your other script's URL
let html = `
<!DOCTYPE html>
<html>
<body>
<p>You are signed in as <b>${userEmail}</b></p>
<form method="post" action="${targetUrl}" target="_blank">
<input type="hidden" name="userEmail" value="${userEmail}">
<!-- add other hidden inputs with salted hash or whatever for extra authentication -->
<button type="submit">Proceed</button>
</form>
</body>
</html>
`;
return HtmlService.createHtmlOutput(html);
}
// With deployment access to "Anyone with a Google account"
// Execute As "The User accessing the web app"
And the second script would have a doPost() like -
function doPost(e) {
// e.parameter contains form fields
let userEmail = e.parameter.userEmail;
// do whatever other parameter checks for extra authentication
// Call your function to fetch data
let result = getData(userEmail);
let html;
if (result && result.found) {
let data = result.data;
html = `
<!DOCTYPE html>
<html>
<body>
<h3>Data Details</h3>
<p><b>Data1:</b> ${data.Namefield1}</p>
<p><b>Data Num:</b> ${data.Num}</p>
<p><b>Data Program:</b> ${data.Program}</p>
</body>
</html>
`;
} else {
html = `
<!DOCTYPE html>
<html>
<body>
<p>No data found for <b>${userEmail}</b></p>
</body>
</html>
`;
}
return HtmlService.createHtmlOutput(html);
}
No comments:
Post a Comment