GAS userProperties not behaving as expected - google-apps-script

In the guide to Properties Service, it is stated that the User Properties is for data specific to the current user of a script. I have a stand alone app deployed for the user accessing the app. I have used PropertiesService.getUserProperties() to set some values. And I expect those values be specific to each user; however, every time a user opens the app, the values for that user overwrites the ones for other users. Is this a bug or expected behavior?
Minimal Reproducible Example:
function doGet(e) {
const userProps = PropertiesService.getUserProperties();
let userData = JSON.parse(userProps.getProperty('userData'));
if (!('foo' in userData)) {
userData = {foo: e.parameters.userData}
userProps.setProperty('userData', JSON.stringify(userData));
}
return HtmlService.createHtmlOutput(`<p>Expected data specific to ${Session.getActiveUser().getEmail();}:</p><p>${userData.foo}`);
}
Expected behavior:
When deployed as a stand-alone app configured to execute for user accessing the web app, the displayed data must be specific to the user.
Observed behavior:
When a new user runs the app, previous users see the data set by the new user, as if the new user's setting has overwritten theirs.

Related

Why is doGet() failing without posting logs?

I suppose my question is twofold: doGet() in the following context will just fail after 0.1~0.2 seconds without posting logs, so I have no idea how to troubleshoot it by myself. Additionally, if I'm having the script execute on my behalf, do I have to push a request with my authorization token to a more "pertinent" area than just the sheet name, such as within the iteration itself? Read further for more details:
I have a source spreadsheet where I am cross-referencing user inputted data to validate the information we have "on file". Most of our clients are over the age of 55, so I am trying to reduce end-user complexity by having the script run on my behalf whenever they need to use it (to bypass the Authorization screen, with the big scary "This application could be unsafe!" message). The way I've read to accomplish this seems to be with doGet(), so I set up a low-level HTTP Get request that just pushes a doGet() with my OAuth token, returning the sheet name. I also set up a masking function specifically to do this, and linked it to the button originally used for the iteration logic. The doGet() looks like this:
const doGet = e => {
Logger.log(`Recieved HTTP request.`);
const content = ContentService.createTextOutput(iterator(e));
Logger.log(content);
return content;
}
and the button that uses UrlFetchApp looks like:
const runMask = () => {
const active = SpreadsheetApp.getActiveSheet().getSheetName();
const v4 = 'https://script.google.com/macros/s/<scriptid>/dev' // ScriptApp.getService().getUrl() posts 404
UrlFetchApp.fetch(`${v4}?sheetName='${active}'`, {
headers: { Authorization: `Bearer ${ScriptApp.getOAuthToken()}` },
});
I have some logs set up within the real runMask() that proceed all the way to the end of the program, giving me real URLs and OAuth tokens, so I know it's making it through runMask() without an issue. However, the doGet() log doesn't post anything, even at the top of the function. I can see that it's executing the trigger in my execution log, but the log itself remains empty.
I've tried:
using ScriptApp.getService().getUrl() in place of v4: posts 404 in the log w/ truncated server response
replacing ${active} with the name of the sheet: same issue; logging ${active} also returns the correct name of the sheet.
Beyond this, I'm not even sure what to do. I have everything scoped correctly (auth/spreadsheets.currentonly, auth/script.external_request, and auth/userinfo.email), and I have no issues about operational security (as both the spreadsheet and script are written by me, the clients have no need to grant access to their entire drive). Before trying to implement doGet() and bypass the authorization screen, the iterator itself worked just fine. As such, I have chosen not to include it here, as it's hardly relevant (the function that executes the iteration function never makes it to that point).
I understand this has been quite the deluge of information; I'd be happy to provide more information or context as needed.
Getting ReferenceError: iterator is not defined (line 12, file "ag2")
With this:
const doGet = e => {
Logger.log(`Recieved HTTP request.`);
const content = ContentService.createTextOutput(iterator(e));
Logger.log(content);
return content;
}
Issued with url/exec?option=A
It runs with
const doGet = e => {
Logger.log(`Recieved HTTP request.`);
const content = ContentService.createTextOutput(JSON.stringify(e));
Logger.log(content);
return content;
}
and returns the appropriate stringified object
Only use the test URL (/dev) for testing the web app from a web browser.
Before doGet from a web browser using a versioned deployment (/exec) remember to publish a new version.
Assign a Google Cloud Project to your Google Apps Script project. For details see https://developers.google.com/apps-script/guides/cloud-platform-projects.
To make it easier to debug your avoid calling functions from a Google Apps Script method like createTextOutput, instead, assign the function result to a variable and use it as the method parameter, i.e. replace
const content = ContentService.createTextOutput(iterator(e));
by
const something = iterator(e);
const content = ContentService.createTextOutput(something);
For debugging purposes, create a function to call your doGet function, and check that it hasn't any problem to run, i.e.
function __test__doGet(){
const e = {
parameter: {}
}
doGet(e);
}
Related
Exception handling in google apps script web apps
Issue:
When I saw your question, I'm worried about I have everything scoped correctly (auth/spreadsheets.currentonly, auth/script.external_request, and auth/userinfo.email).
If you are using only the following scopes at oauthScopes of appsscript.json,
https://www.googleapis.com/auth/spreadsheets.currentonly
https://www.googleapis.com/auth/script.external_request
https://www.googleapis.com/auth/userinfo.email
Unfortunately, these scopes cannot be used for access to Web Apps. Although I'm not sure about the method for running your function of runMask, I thought that this might be the reason for your issue.
Solution:
If you want to access Web Apps of https://script.google.com/macros/s/<scriptid>/dev using the access token retrieved by ScriptApp.getOAuthToken(), please include the following scope.
https://www.googleapis.com/auth/drive.readonly
or
https://www.googleapis.com/auth/drive
After you include the above scope, please reauthorize the scopes, and test it again. When your function of iterator has already been declared and the script worked, by running runMask, you can see the log of Logger.log(Recieved HTTP request.) and Logger.log(content) at the log.
Reference:
Taking advantage of Web Apps with Google Apps Script

Gmail API in GAS: Refreshing Interface on State Change?

I'm currently writing using Google-Apps-Scripts to do change labels on threads and messages. When the script completes, the payloads are moved, but the display on the user frontend does not change until the user interacts with Gmail.
Is there a way to push a refresh command to Gmail? How can I gracefully display "job's done" to the user so they know that messages are now appropriately labeled?
I am working directly against the Gmail API, not GmailApp. I discovered ActionResponseBuilder.setStateChanged(), but the problem is I am currently not working with any sort of frontend interface. This is all in the background.
Here is an abbreviated example of some of the code I'm using to grab messages to modify (as requested):
function changeLabel(ids,oldLabel,newLabel) {
Gmail.Users.Messages.batchModify({
"ids":ids,
"addLabelIds":oldLabel,
"removeLabelIds":newLabel
},"me");
}
function start() {
// Labels to work with
const FOO = "Label_5095729546757874255";
const BAR = "Label_5102306845672214551";
// API call to retrieve list of messages by Label
var msgIdsByLabel = new MessageIndex(FOO);
// API call to retrieve message contents
var payloadMessages = new Messages(msgIdsByLabel);
var manifestMessagesToMove = [];
for (var i=0;i < Object.keys(payloadMessages.response).length; i++) {
// Criteria for selecting messages to move goes here
manifestMessagesToMove[i] = payloadMessages.response[i].id;
}
// Change labels of Message Ids
changeLabel(manifestMessagesToMove,FOO,BAR);
// ??? Refresh Gmail Interface ???
}
Unfortunately this isn't possible.
The Gmail UI can't be refreshed from Apps Script as it is run in the cloud as a separate session to that which is being viewed in the web browser by a user. The two aren't connected - and the same goes for the Gmail API.
If you don't have a front-end interface (aka a Gmail Add-on utilising CardService) then there is not a way of displaying a message to the user, either. The refresh will have to be done manually.

Previously working Google App Script now produces permission error

I cannot find anything about Google having updated policies on April 2022. This script was working without any issues before, then in the middle of the day, permissions needed to be re-added. Even with said permissions granted, Google still says access is denied. It was later discovered that the macro has not ran successfully since March 31st.
var newJobFile = DriveApp.getFileById(newJobID);
newJobFile.AddEditors(['group#gmail.com','admin#gmail.com');
newJobFile.setOwner('admin#gmail.com');
The last line is what generates the error. When debugging, I can see as the variable gets created, I cannot see any information about it. For example, if I add a "Filecreated.getName();" before the line with the error, the variable menu remains blank. I am not sure if this is normal. The "newid" variable is confirmed to have the spreadsheet ID. I can copy it into the URL and it takes me to the page. Why is this suddenly an issue and how can I fix it? I did not have a appscripts.json file before with OAuthScopes and it worked fine then. I've added it with the proper permissions, but it does not change anything. I've added several permission scopes to try to resolve this but none of them do. Any advice?
"oauthScopes": [
"https://www.googleapis.com/auth/drive",
"https://www.googleapis.com/auth/spreadsheets"
]
EDIT: I am still having this issue. Even with everything controlled under one account, I cannot transfer ownership to 'Central_account#gmail.com' due to 'Exception : Access Denied : DriveApp'. I have found just one other person experiencing this same issue on the Google App Script group page. Is anyone else not having issues with transferring ownership starting in April on a regular, non-work account?
EDIT 2: Sorry for not uploading my code earlier, I had to clean it up first.
function onOpen(e) {
SpreadsheetApp.getUi()
.createMenu('Add') //creates toolbar entry to the right of 'Help'
.addItem('Capital project','newProject')
.addToUi();
}
function newProject(){
var dashboard = SpreadsheetApp.getActiveSpreadsheet(); //Stores dashboard into a variable for later
var template = SpreadsheetApp.openById('xxxxxx') //Opens the project sheet template in the backend
var nameEntry = getName(); //Prompts user for the name of the new job file
if (nameEntry == null){
return;
}
SpreadsheetApp.setActiveSpreadsheet(template); //Template is now the active sheet
var newJobID = copySheet(nameEntry); //Creates a copy of the New Project template
var newJobFile = DriveApp.getFileById(newJobID);
newJobFile.AddEditors(['group#gmail.com','admin#gmail.com');
newJobFile.setOwner('admin#gmail.com');
}
function getName(){
var ui = SpreadsheetApp.getUi();
var name = ui.prompt( //Prompts the user for an input name
'',
'?????-? Project Description',
ui.ButtonSet.OK_CANCEL);
var cancelCheck = name.getSelectedButton();
if (cancelCheck == ui.Button.CANCEL || cancelCheck == ui.Button.CLOSE) {
return null;
}
var sheetName = name.getResponseText();
return sheetName;
}
function copySheet(name) {
var activeSS = SpreadsheetApp.getActive();
var newFile = activeSS.copy(name) //Creates a copy of the New Project template
SpreadsheetApp.setActiveSpreadsheet(newFile); //Resets active spreadsheet to the recent copy
activeSS = SpreadsheetApp.getActive();
activeSS.getRange('A1').activateAsCurrentCell();
activeSS.getCurrentCell().setValue(name); //Set cell A1 to the name of the file
var newHyperlink = '=HYPERLINK("' + activeSS.getUrl() + '#gid=15580246",A1)';
activeSS.getRange('A2').activateAsCurrentCell();
activeSS.getCurrentCell().setValue(newHyperlink);
return activeSS.getId();
}
With logs, I can see that everything works as intended except for the .setOwner() method. It returns the Access Denied error. I have checked all google accounts and each has enabled CustomScripts to access their drive. Has .setOwner() been deprecated for non workspace accounts?
I've updated my original snippets to match my code.
Apparently the process to transfer file ownership between consumer accounts has changed. According to this guide, the prospective new owner needs to accept the transfer request. See example below:
And I found this article where you can see that the process was different a few months ago, you could set a new owner immediately without sending invitation.
I tested the setOwner() method with a Google Workspace account and it works as within Google Workspace you can directly transfer file ownership between users within the same organization, then I tested the same script with a Gmail account and tried to set another Gmail account as the new owner and I got the same error message: "Exception: Access denied: DriveApp".
Based on all the information, it seems that this behavior is expected as the process to change a file ownership for Gmail accounts is different now, you can’t set a new owner directly, the person you invite to own the file must accept your request to complete the transfer.
I don't have enough reputation to comment, but I'd second what Lorena Gomez said that it's likely an issue with your OAuthScopes. According to the Apps Script documentation, the setOwner() method on the File class requires the /auth/drive authorization scope.
It looks like you have both the /auth/drive and the /auth/drive.file scope configured, and I think the /auth/drive.file scope, which is narrower, is overriding the broader /auth/drive scope, which is required to call setOwner().
Have you tried removing the /auth/drive.file scope and running the script only with /auth/drive?

Setting G Suite user properties with App Script and the Admin SDK

I'm trying to set a user's OU from an App Script inside App Maker.
(user is a variable with an email address)
function getUser(user) {
var x = AdminDirectory.Users.update(
{
orgUnitPath: "/",
userKey: user,
});
console.log("function ran");
}
This code errors with:
Exception: Invalid number of arguments provided. Expected 2-3 only at getUser (ServerScripts:107)
Invalid number of arguments provided. Expected 2-3 only
at getUser (ServerScripts:107)
at getUser (ClientHandoff:21:21)
at TestMoveOU.Panel1.Button1.onClick:1:1
What am I doing wrong here? Looking at the docs, you only need to provide the properties you're changing.
The Apps Script documentation says the following:
For detailed information on this service, see the reference documentation for the Admin SDK Directory API. Like all advanced services in Apps Script, the Admin SDK Directory service uses the same objects, methods, and parameters as the public API.
Therefore, we need to consult the documentation to get clarification on how to achieve this.
The method requires at least two parameters: that means that the the first parameter is a user object resource and the second parameter is the email address of the user: AdminDirectory.Users.update(resource, userKey). So you need to do this:
function getUser(user) {
var userResource = {
orgUnitPath: "/"
};
var updated = AdminDirectory.Users.update(userResource, user);
console.log(updated.primaryEmail);
}
So why do you need to specify the user email in the method when it is already being specified in the userResource object? Well, the email address in the userResource object would be the new value, in case you want to change the email address.
P.S. Perhaps you might wanna change the name of the function to something that is more of a match; updateUser() perhaps? I hope this helps!

Is endpoint unique for device in AWS Pinpoint?

I am new to Pinpoint and trying to understand how endpoint/endpointId works in Pinpoint semantics. From the aws doc:
When a user starts a session (for example, by launching your mobile app), your mobile or web application can automatically register (or update) an endpoint with Amazon Pinpoint.
Does that mean each time of the app launching, there is a new endpoint/endpointId? Will it register a new endpoint if the current session ends or the user kill and relaunch the app?
Is there a way I can get the endpoint/endpointId in the app programmatically?
Yes, the endpoint is the same for each unique device, email, etc. It needs to be the same so that Amazon knows where to send push notifications, for example, if you run a targeted campaign. If the user kills and relaunches the app, then the same endpoint is used. This goes for both authenticated and unauthenticated users. Thus, I would have reason to believe that if the current session ends (i.e. the user has to re-authenticate), then they have the same endpoint. This makes sense because every device (the device itself) needs a unique identifier. In order to better answer your question, I have personally tested the below and confirmed:
If one user logs out, and another logs in [on the same device], the endpoint ID remains the same. The purpose of the code below registers a user ID with a specific endpoint. You can also modify the code below to print the endpoint ID, as you requested.
At the top of your AppDelegate, put this, assuming you're using Swift and AWS Cognito for user authentication:
var pinpoint: AWSPinpoint?
... in didFinishLaunching, put this:
self.pinpoint = AWSPinpoint(configuration:AWSPinpointConfiguration.defaultPinpointConfiguration(launchOptions: launchOptions))
if let targetingClient = pinpoint?.targetingClient {
if let username = AppDelegate.defaultUserPool().currentUser()?.username {
let endpoint = targetingClient.currentEndpointProfile()
// Create a user and set its userId property
let user = AWSPinpointEndpointProfileUser()
user.userId = username
// Assign the user to the endpoint
endpoint.user = user
// Update the endpoint with the targeting client
targetingClient.update(endpoint)
print("Assigned user ID \(user.userId ?? "nil") to endpoint \(endpoint.endpointId).\n")
}
}