Basic

Once setup, then you should go through the Google login flow in your browser when you run this command:

googleAuthR::gar_auth()

If you ever need to authenticate with a new user, use:

googleAuthR::gar_auth(new_user=TRUE)

Authentication token is cached in a hidden file called .httr-oauth in the working directory.

Authentication with no browser

If for some reason you need authentication without access to a browser (for example when using Shiny Server), then you can authenticate locally and upload the .httr-oauth file to the folder of your script.

Authentication within Shiny

If you want to create a Shiny app just using your data, upload the app with your own .httr-oauth.

If you want to make a multi-user Shiny app, where users login to their own Google account and the app works with their data, googleAuthR provides these functions to help make the Google login process as easy as possible.

As of 0.3.0 googleAuthR uses Shiny Modules. This means less code and the ability to have multiple login buttons on the same app.

Shiny authentication example

This is the example deployed to shinyapps.io here

## in global.R
library(googleAuthR)
library(shiny)
options(googleAuthR.scopes.selected = "https://www.googleapis.com/auth/urlshortener")
options(googleAuthR.webapp.client_id = "YOUR_PROJECT_KEY")
options(googleAuthR.webapp.client_secret = "YOUR_CLIENT_SECRET")
shorten_url <- function(url){

  body = list(
    longUrl = url
  )

  f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
                         "POST",
                         data_parse_function = function(x) x$id)

  f(the_body = body)

}
## server.R
source("global.R")
server <- function(input, output, session){

  ## Create access token and render login button
  access_token <- callModule(googleAuth, "loginButton")

  short_url_output <- eventReactive(input$submit, {
    ## wrap existing function with_shiny
    ## pass the reactive token in shiny_access_token
    ## pass other named arguments
    with_shiny(f = shorten_url, 
               shiny_access_token = access_token(),
               url=input$url)

  })

  output$short_url <- renderText({

    short_url_output()

  })
}
## ui.R
ui <- fluidPage(
  googleAuthUI("loginButton"),
  textInput("url", "Enter URL"),
  actionButton("submit", "Shorten URL"),
  textOutput("short_url")
)
### If the above global.R, server.R and ui.R files are in folder "test" like so:
## /home
##    |->/test/
##            /global.R
##            /ui.R
##            /server.R
##
## Port 1221 has been set in your Google Project options as the port to listen to
## as explained in authentication setup section
## run below in /home directory
shiny::runApp("./test/", launch.browser=T, port=1221)

Authentication with a JSON file via Service Accounts

You can also authenticate single users via a server side JSON file rather than going through the online OAuth2 flow. The end user could supply this JSON file, or you can upload your own JSON file to your applications.

This involves downloading a secret JSON key with the authentication details. More details are available from Google here: Using OAuth2.0 for Server to Server Applications[https://developers.google.com/identity/protocols/OAuth2ServiceAccount]

To use, go to your Project in the Google Developement Console and select JSON Key type. Save the JSON file to your computer and supply the file location to the function gar_auth_service()

Navigate to the JSON file from the Google Developer Console via: Credentials > New credentials > Service account Key > Select service account > Key type = JSON

An example using a service account JSON file for authentication is shown below:

library(googleAuthR)
service_token <- gar_auth_service(json_file="~/location/of/the/json/secret.json")
analytics_url <- function(shortUrl, 
                          timespan = c("allTime", "month", "week","day","twoHours")){

  timespan <- match.arg(timespan)

  f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url",
                         "GET",
                         pars_args = list(shortUrl = "shortUrl",
                                          projection = "FULL"),
                         data_parse_function = function(x) { 
                           a <- x$analytics 
                           return(a[timespan][[1]])
                         })

  f(pars_arguments = list(shortUrl = shortUrl))
}
analytics_url("https://goo.gl/2FcFVQbk")

Authentication via RStudio Addin

From version 0.3.0 a RStudio Addin is available via the RStudio Addin menu once you load the package, or via googleAuthR:::gar_gadget()

It lets you set the scopes and then saves you some typing by calling the Google authentication flow for you.

Authentication in RMarkdown via JavaScript

From version 0.4.0 there are two functions that can be called from within RMarkdown for authentication. They use JavaScript, rather than R/Shiny to authenticate, as an RMarkdown document can not read the URL tokens.

A demo and example are available here: https://mark.shinyapps.io/googleAuthRMarkdown/

RMarkdown authentication - Setup

The RMarkdown document YAML needs runtime shiny and to be a HTML document:

output: html_document
runtime: shiny

Locally, you have to run the RMarkdown document on the specified port configured in Google console (1221 for the default shared project of googleAuthR), configured via options(shiny.port = 1221)

This means you shouldn’t launch the RMarkdown via the Run button in RStudio as that starts a new R session without your set options.

Instead set the options and run via rmarkdown::run("myfile.Rmd")

options(shiny.port = 1221)
options(googleAuthR.scopes.selected = "https://www.googleapis.com/auth/plus.me")
rmarkdown::run("googleAuthRMarkdown.Rmd")

When publishing, you also need to add the domain to the Javascript origins in the Google API console. Use 127.0.0.1:XXX where XXX is your chosen Shiny port for local testing.

Example of RMarkdown authentication

Below creates a button that when clicked makes a popup for Google authentication:

library(googleAuthR)

gar_auth_jsUI("auth_demo", login_text = "Click Me")

The authentication token is available via the server side module command:

auth <- callModule(gar_auth_js, "auth_demo")

Pass the auth token to API functions. Below example using googleID to return G+ user info.

# devtools::install_github("MarkEdmondson1234/googleID")
library(googleID)

user_info <- reactive({

  req(auth())

  with_shiny(get_user_info,
             shiny_access_token = auth())

})

You can now output the user data taken from the G+ API:

## creates an output
renderUI({

  req(user_info())

  h1("Hello ", user_info()$displayName)

})

Auto-authentication

From version 0.4.0 auto-authentication can be performed upon a package load.

This requires the setup of environment variables either in your .Renviron file or via Sys.setenv() to point to a previously created authentication file. This file can be either a .httr-oauth file created via gar_auth() or a Google service account JSON downloaded from the Google API console.

This file will then be used for authentication via gar_auth_auto. You can call this function yourself in scripts or R sessions, but its main intention is to be called in the .onAttach function via gar_attach_auth_auto, so that you will authenticate right after you load the library via library(yourlibrary)

An example from googleCloudStorageR is shown below:

.onAttach <- function(libname, pkgname){

  googleAuthR::gar_attach_auto_auth("https://www.googleapis.com/auth/devstorage.full_control",
                                    environment_var = "GCS_AUTH_FILE")
}

..which calls an environment variable set in ~/.Renvion:

GCS_AUTH_FILE="/Users/mark/auth/my_auth_file.json"

Revoking Authentication

For local use, delete the .httr-oauth file.

For service level accounts delete the JSON file.

For a Shiny app, a cookie is left by Google that will mean a faster login next time a user uses the app with no Authorization screen that they get the first time through. To force this every time, activate the parameter revoke=TRUE within the googleAuth function.



yinscapital/googleAuthR-reference documentation built on May 3, 2019, 4:31 p.m.