rcrontidyversegooglesheets4

R cron job cannot edit googlesheet - authorization issue


I have a cron job which edits a googlesheet using functions range_clear and sheet_write from the googlesheets4 package. Here is how i set up the permissions:

library(googlesheets4)

# Set authentication token to be stored in a folder called `.secrets`
options(gargle_oauth_cache = ".secrets")

# Authenticate manually
gs4_auth()

# If successful, the previous step stores a token file.
# Check that a file has been created with:
list.files(".secrets/")

# Check that the non-interactive authentication works by first deauthorizing:
gs4_deauth()

# Authenticate using token. If no browser opens, the authentication works.
gs4_auth(cache = ".secrets", email = "my.email@gmail.com")

It ran well daily for about a month until it started failing to edit the gsheet, for the reason detailed here i think under 'Why my approach failed'. I then decided to re-install the googlesheets4 package as explained in the link (devtools::install_github("tidyverse/googlesheets4")) so i could benefit from the retry feature. I set up again the permissions exactly as explained above. The script runs fine locally (and uses retry) but the job itself systematically fails throwing this error:

i The googlesheets4 package is using a cached token for
  'my.email@gmail.com'.
Error in `gs4_get_impl_()`:
! Client error: (403) PERMISSION_DENIED
* Client does not have sufficient permission. This can happen because the OAuth
  token does not have the right scopes, the client doesn't have permission, or
  the API has not been enabled for the client project.
* Request had insufficient authentication scopes.

Error details:
* reason: ACCESS_TOKEN_SCOPE_INSUFFICIENT

Any tips on how i should proceed?


Solution

  • I resolved it by adding this snippet directly at the beginning of the cron job:

    gs4_auth(cache = ".secrets", email = "my.email@gmail.com")