FirestoreGoogleAppsScript icon indicating copy to clipboard operation
FirestoreGoogleAppsScript copied to clipboard

README Properties Service key retrieval error

Open gskll opened this issue 1 year ago • 4 comments

Is your feature request related to a problem?

In README.md#configuration-template when talking about using Properties Service to retrieve the configuration data, specifically the private_key.

If the key is set programatically through PropertiesService.getScriptProperties().setProperty() there is no issue. But if the key is set manually through the script settings then it gives an error on retrieval.

This is related to this issue where newline characters aren't correctly converted and has to be done manually upon retrieval.

For example

 // if script property set manually
 const props = PropertiesService.getScriptProperties();
  const [email, key, projectId] = [
    props.getProperty("client_email"),
    props.getProperty("private_key").replace(/\\n/g, "\n"), // Solution from issue linked above
    props.getProperty("project_id"),
  ];
  const firestore = FirestoreApp.getFirestore(email, key, projectId);

Describe the solution you'd like

To clarify this in the documentation to avoid confusion when setting the private_key in this way.

gskll avatar May 03 '23 10:05 gskll

When saving the key manually.. are you adding the escape characters for the newline? You should probably play with that, and don't use .replace when fetching the data back.

LaughDonor avatar May 03 '23 14:05 LaughDonor

So I tried escaping the newline characters but there's no way around it, it seems because the key/value has to be valid json and there's no way of encoding newline characters in it. The only way around it with manual setting that I found was using the replace above

gskll avatar Jun 09 '23 09:06 gskll

You seem to be having an isolated issue. I tried my best to provide as close to literal example in the README. I'm fine to help you with ideas if you can debug what you are sending and retreiving from the Property Service.

LaughDonor avatar Jun 13 '23 19:06 LaughDonor

This comment gives an actual clean way of extracting credentials from the JSON of the service account while avoiding that issue. I've implemented it for myself. If you don't use service account for Oauth then the workaround with string.replace(/\\n/g, '\n') may be necessary.

function getOAuthCreds() {
  try {
    const scriptProperties = PropertiesService.getScriptProperties();
    return JSON.parse(scriptProperties.getProperty('SERVICE_ACCOUNT_CREDS'));
  } catch (err) {
    // TODO (developer) - Handle exception
    return null;
  }
}

Then retrieve the private key, email etc with the returned object:

getOAuthCreds().private_key

zouritre avatar Mar 03 '24 22:03 zouritre