0

I want to create a google slide presentation from a non-interactive R script.

I got this to work interactively with the following setup and functions:


# setup:
# create a .secrets/ directory in the working directory, which contains a JSON file
# with the google client info ".secrets/MyApp_OAuth2_web_client_secret.json"
# this file was generated manually:
# log in to google cloud services with the your service google account
# go to the credentials page https://console.cloud.google.com/apis/credentials?authuser=2&project=fcexplorer&supportedpurview=project
# click the project for which credentials were created, in my case MyApp_OAuth2_web_client
# towards the top, click DOWNLOAD JSON


get_gslides_token <- function(){

  # get google client ID and secret from JSON file
  google_client <- gargle::gargle_oauth_client_from_json(".secrets/MyApp_OAuth2_web_client_secret.json")

  # configure the MyApp app. This points the token to the service google account
  app <- httr::oauth_app(appname = "MyApp", key = google_client$id, secret = google_client$secret)
  endpoint <- httr::oauth_endpoints("google")

  # generate token to access google drive and google presentations
  token <- httr::oauth2.0_token(endpoint = endpoint, app = app,
                                scope = c("https://www.googleapis.com/auth/presentations",
                                          "https://www.googleapis.com/auth/drive"),
                                #type= "access_type='offline'",
                                cache = ".secrets/httr-oauth")

  return(token)

}


new_gslide <- function(title){

  res <- httr::POST(url = "https://slides.googleapis.com/v1/presentations",
                    config = httr::config(token=get_gslides_token()),
                    httr::accept_json(),
                    body = list(title=title),
                    encode = "json")

# ...

}


When I run new_gslide("slidesTitle"), the httr::oauth2.0_token() function will send me to the access page, where I grant my app access to google slides and google drive. It then caches the token in the .secrets/httr-oauth file.

Once this cache file is there, I can run the app non-interactively until the token expires, which is only 1h...

I read in a very old thread that I can add type= "access_type='offline'" in the oauth2.0_token call, which supposedly requests a refresh token in the token object, but this did not work.

What changes must I make to be able to use a token for longer than 1h, or to refresh it non-interactively?

mandmeier
  • 355
  • 5
  • 16

1 Answers1

0

I found an answer to this!

The trick is to select "Desktop app" when creating a OAuth2 client ID on the google cloud. This will also include a refresh token in the token object.

I posted the working code to the other thread here.

mandmeier
  • 355
  • 5
  • 16