Title: | Authenticate and Create Google APIs |
---|---|
Description: | Create R functions that interact with OAuth2 Google APIs <https://developers.google.com/apis-explorer/> easily, with auto-refresh and Shiny compatibility. |
Authors: | Mark Edmondson [aut] , Erik Grönroos [cre], Jennifer Bryan [ctb], Johann deBoer [ctb], Neal Richardson [ctb], David Kulp [ctb], Joe Cheng [ctb] |
Maintainer: | Erik Grönroos <[email protected]> |
License: | MIT + file LICENSE |
Version: | 2.0.2 |
Built: | 2024-11-19 04:56:12 UTC |
Source: | https://github.com/markedmondson1234/googleauthr |
This function generates other functions for use with Google APIs
gar_api_generator( baseURI, http_header = c("GET", "POST", "PUT", "DELETE", "PATCH"), path_args = NULL, pars_args = NULL, data_parse_function = NULL, customConfig = NULL, simplifyVector = getOption("googleAuthR.jsonlite.simplifyVector"), checkTrailingSlash = TRUE )
gar_api_generator( baseURI, http_header = c("GET", "POST", "PUT", "DELETE", "PATCH"), path_args = NULL, pars_args = NULL, data_parse_function = NULL, customConfig = NULL, simplifyVector = getOption("googleAuthR.jsonlite.simplifyVector"), checkTrailingSlash = TRUE )
baseURI |
The stem of the API call. |
http_header |
Type of http request. |
path_args |
A named list with name=folder in request URI, value=the function variable. |
pars_args |
A named list with name=parameter in request URI, value=the function variable. |
data_parse_function |
A function that takes a request response, parses it and returns the data you need. |
customConfig |
list of httr options such as use_proxy or add_headers that will be added to the request. |
simplifyVector |
Passed to fromJSON for response parsing |
checkTrailingSlash |
Default TRUE will append a trailing slash to baseURI if missing |
path_args and pars_args add default values to the baseURI. NULL entries are removed. Use "" if you want an empty argument.
You don't need to supply access_token for OAuth2 requests in pars_args, this is dealt with in gar_auth()
Add custom configurations to the request in this syntax:
customConfig = list(httr::add_headers("From" = "[email protected]")
A function that can fetch the Google API data you specify
## Not run: library(googleAuthR) ## change the native googleAuthR scopes to the one needed. options("googleAuthR.scopes.selected" = "email") get_email <- function(){ f <- gar_api_generator("https://openidconnect.googleapis.com/v1/userinfo", "POST", data_parse_function = function(x) x$email, checkTrailingSlash = FALSE) f() } To use the above functions: library(googleAuthR) # go through authentication flow gar_auth() s <- get_email() s ## End(Not run)
## Not run: library(googleAuthR) ## change the native googleAuthR scopes to the one needed. options("googleAuthR.scopes.selected" = "email") get_email <- function(){ f <- gar_api_generator("https://openidconnect.googleapis.com/v1/userinfo", "POST", data_parse_function = function(x) x$email, checkTrailingSlash = FALSE) f() } To use the above functions: library(googleAuthR) # go through authentication flow gar_auth() s <- get_email() s ## End(Not run)
A helper function to help with the common task of paging through large API results.
gar_api_page( f, page_f = function(x) x$nextLink, page_method = c("url", "param", "path", "body"), page_arg = NULL, body_list = NULL )
gar_api_page( f, page_f = function(x) x$nextLink, page_method = c("url", "param", "path", "body"), page_arg = NULL, body_list = NULL )
f |
a function created by gar_api_generator |
page_f |
A function that will extract the next page information from |
page_method |
Method of paging: |
page_arg |
If |
body_list |
If |
The page_f
function operates on the object returned from the data_parse_function
of the function f
If using page_method="url"
then then page_f
function needs to return the URL that will fetch the next page of results. The default finds this via x$nextLink
. This is the easiest to implement if available and is recommended.
If using page_method = "param"
, then page_f
needs to extract the parameter specified in page_arg
that will fetch the next page of the results, or NULL if no more pages are required.
e.g. if response is x, page_f
should extract the next value for the parameter of page_arg
that fetches the next results. It should also return NULL
if no (more) paging is necessary. See examples.
Remember to add the paging argument (e.g. start-index
) to the generated function too, so it can be modified.
A list of the API page responses, that you may need to process further into one object.
## Not run: # demos the two methods for the same function. # The example is for the Google Analytics management API, # you need to authenticate with that to run them. # paging by using nextLink that is returned in API response ga_segment_list1 <- function(){ # this URL will be modified by using the url_override argument in the generated function segs <- gar_api_generator("https://www.googleapis.com/analytics/v3/management/segments", "GET", pars_args = list("max-results"=10), data_parse_function = function(x) x) gar_api_page(segs, page_method = "url", page_f = function(x) x$nextLink) } # paging by looking for the next start-index parameter ## start by creating the function that will output the correct start-index paging_function <- function(x){ next_entry <- x$startIndex + x$itemsPerPage # we have all results e.g. 1001 > 1000 if(next_entry > x$totalResults){ return(NULL) } next_entry } ## remember to add the paging argument (start-index) to the generated function too, ## so it can be modified. ga_segment_list2 <- function(){ segs <- gar_api_generator("https://www.googleapis.com/analytics/v3/management/segments", "GET", pars_args = list("start-index" = 1, "max-results"=10), data_parse_function = function(x) x) gar_api_page(segs, page_method = "param", page_f = paging_function, page_arg = "start-index") } identical(ga_segment_list1(), ga_segment_list2()) ## End(Not run)
## Not run: # demos the two methods for the same function. # The example is for the Google Analytics management API, # you need to authenticate with that to run them. # paging by using nextLink that is returned in API response ga_segment_list1 <- function(){ # this URL will be modified by using the url_override argument in the generated function segs <- gar_api_generator("https://www.googleapis.com/analytics/v3/management/segments", "GET", pars_args = list("max-results"=10), data_parse_function = function(x) x) gar_api_page(segs, page_method = "url", page_f = function(x) x$nextLink) } # paging by looking for the next start-index parameter ## start by creating the function that will output the correct start-index paging_function <- function(x){ next_entry <- x$startIndex + x$itemsPerPage # we have all results e.g. 1001 > 1000 if(next_entry > x$totalResults){ return(NULL) } next_entry } ## remember to add the paging argument (start-index) to the generated function too, ## so it can be modified. ga_segment_list2 <- function(){ segs <- gar_api_generator("https://www.googleapis.com/analytics/v3/management/segments", "GET", pars_args = list("start-index" = 1, "max-results"=10), data_parse_function = function(x) x) gar_api_page(segs, page_method = "param", page_f = paging_function, page_arg = "start-index") } identical(ga_segment_list1(), ga_segment_list2()) ## End(Not run)
To be placed within .onAttach to auto load an authentication file from an environment variable.
gar_attach_auto_auth(required_scopes, environment_var = "GAR_AUTH_FILE")
gar_attach_auto_auth(required_scopes, environment_var = "GAR_AUTH_FILE")
required_scopes |
A character vector of minimum required scopes for this API library |
environment_var |
The name of the environment variable where the file path to the authentication file is kept This function works with gar_auto_auth. It is intended to be placed within the .onAttach hook so that it loads when you load your library. For auto-authentication to work, the environment variable needs to hold a file path to an existing auth file such as created via gar_auth or a JSON file file download from the Google API console. |
Invisible, used for its side effects of calling auto-authentication.
Other authentication functions:
gar_auth()
,
gar_auth_service()
,
gar_auto_auth()
,
gar_gce_auth()
,
get_google_token()
,
should_skip_token_checks()
,
token_exists()
## Not run: .onAttach <- function(libname, pkgname){ googleAuthR::gar_attach_auto_auth("https://www.googleapis.com/auth/urlshortener", "US_AUTH_FILE") } ## will only work if you have US_AUTH_FILE environment variable pointing to an auth file location ## .Renviron example US_AUTH_FILE="/home/mark/auth/urlshortnerauth.json" ## End(Not run)
## Not run: .onAttach <- function(libname, pkgname){ googleAuthR::gar_attach_auto_auth("https://www.googleapis.com/auth/urlshortener", "US_AUTH_FILE") } ## will only work if you have US_AUTH_FILE environment variable pointing to an auth file location ## .Renviron example US_AUTH_FILE="/home/mark/auth/urlshortnerauth.json" ## End(Not run)
googleAuthR
Wrapper of token_fetch
gar_auth( token = NULL, email = NULL, scopes = getOption("googleAuthR.scopes.selected"), app = gar_oauth_app(), cache = gargle::gargle_oauth_cache(), use_oob = gargle::gargle_oob_default(), package = "googleAuthR" )
gar_auth( token = NULL, email = NULL, scopes = getOption("googleAuthR.scopes.selected"), app = gar_oauth_app(), cache = gargle::gargle_oauth_cache(), use_oob = gargle::gargle_oob_default(), package = "googleAuthR" )
token |
an actual token object or the path to a valid token stored as an
|
email |
An existing gargle cached email to authenticate with or TRUE to authenticate with the only email available. |
scopes |
Scope of the request |
app |
app as specified by gar_auth_configure |
cache |
Where to store authentication tokens |
use_oob |
Whether to use OOB browserless authentication |
package |
The name of the package authenticating |
an OAuth token object, specifically a
Token2.0
, invisibly
Other authentication functions:
gar_attach_auto_auth()
,
gar_auth_service()
,
gar_auto_auth()
,
gar_gce_auth()
,
get_google_token()
,
should_skip_token_checks()
,
token_exists()
## Not run: # sets GCP project to auth through gar_auth_configure(path="path/to/gcp-client.json") # starts auth process with defaults gar_auth() # switching between auth scopes # first time new scope manual auth, then auto if supplied email gar_auth(email = "[email protected]", scopes = "https://www.googleapis.com/auth/drive") # ... query Google Drive functions ... gar_auth(email = "[email protected]", scopes = "https://www.googleapis.com/auth/bigquery") # ..query BigQuery functions ... ## End(Not run)
## Not run: # sets GCP project to auth through gar_auth_configure(path="path/to/gcp-client.json") # starts auth process with defaults gar_auth() # switching between auth scopes # first time new scope manual auth, then auto if supplied email gar_auth(email = "[email protected]", scopes = "https://www.googleapis.com/auth/drive") # ... query Google Drive functions ... gar_auth(email = "[email protected]", scopes = "https://www.googleapis.com/auth/bigquery") # ..query BigQuery functions ... ## End(Not run)
These functions give more control over and visibility into the auth configuration than [gar_auth()] does. 'gar_auth_configure()' lets the user specify their own: * OAuth client, which is used when obtaining a user token. * API key. If googleAuthR is de-authorized via [gar_deauth()], all requests are sent with an API key in lieu of a token.
See the 'vignette("get-api-credentials", package = "gargle")' for more. If the user does not configure these settings, internal defaults are used.
'gar_oauth_client()' and 'gar_api_key()' retrieve the currently configured OAuth client and API key, respectively.
gar_auth_configure(app, path, api_key) gar_api_key() gar_oauth_app()
gar_auth_configure(app, path, api_key) gar_api_key() gar_oauth_app()
app |
A Google OAuth client, presumably constructed via gargle_oauth_client_from_json. Note, however, that it is preferred to specify the client with JSON, using the 'path' argument. |
path |
JSON downloaded from Google Cloud Console, containing a client id and secret, in one of the forms supported for the |
api_key |
API key. |
* 'gar_auth_configure()': An object of R6 class [gargle::AuthState], invisibly. * 'gar_oauth_client()': the current user-configured OAuth client. * 'gar_api_key()': the current user-configured API key.
Other auth functions:
gar_deauth()
# see and store the current user-configured OAuth app (probaby `NULL`) (original_app <- gar_oauth_app()) # see and store the current user-configured API key (probaby `NULL`) (original_api_key <- gar_api_key()) if (require(httr)) { # bring your own app via client id (aka key) and secret google_app <- httr::oauth_app( "my-awesome-google-api-wrapping-package", key = "123456789.apps.googleusercontent.com", secret = "abcdefghijklmnopqrstuvwxyz" ) google_key <- "the-key-I-got-for-a-google-API" gar_auth_configure(app = google_app, api_key = google_key) # confirm the changes gar_oauth_app() gar_api_key() } ## Not run: ## bring your own app via JSON downloaded from Google Developers Console gar_auth_configure( path = "/path/to/the/JSON/you/downloaded/from/google/dev/console.json" ) ## End(Not run) # restore original auth config gar_auth_configure(app = original_app, api_key = original_api_key)
# see and store the current user-configured OAuth app (probaby `NULL`) (original_app <- gar_oauth_app()) # see and store the current user-configured API key (probaby `NULL`) (original_api_key <- gar_api_key()) if (require(httr)) { # bring your own app via client id (aka key) and secret google_app <- httr::oauth_app( "my-awesome-google-api-wrapping-package", key = "123456789.apps.googleusercontent.com", secret = "abcdefghijklmnopqrstuvwxyz" ) google_key <- "the-key-I-got-for-a-google-API" gar_auth_configure(app = google_app, api_key = google_key) # confirm the changes gar_oauth_app() gar_api_key() } ## Not run: ## bring your own app via JSON downloaded from Google Developers Console gar_auth_configure( path = "/path/to/the/JSON/you/downloaded/from/google/dev/console.json" ) ## End(Not run) # restore original auth config gar_auth_configure(app = original_app, api_key = original_api_key)
As well as OAuth2 authentication, you can authenticate without user interaction via Service accounts. This involves downloading a secret JSON key with the authentication details.
To use, go to your Project in the https://console.developers.google.com/apis/credentials/serviceaccountkey
and select JSON Key type. Save the file
to your computer and call it via supplying
the file path to the json_file
parameter.
Navigate to it via: Google Dev Console > Credentials > New credentials > Service account Key > Select service account > Key type = JSON
gar_auth_service(json_file, scope = getOption("googleAuthR.scopes.selected"))
gar_auth_service(json_file, scope = getOption("googleAuthR.scopes.selected"))
json_file |
the JSON file downloaded from Google Developer Console |
scope |
Scope of the JSON file auth if needed |
(Invisible) Sets authentication token
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
https://developers.google.com/identity/protocols/OAuth2ServiceAccount
Other authentication functions:
gar_attach_auto_auth()
,
gar_auth()
,
gar_auto_auth()
,
gar_gce_auth()
,
get_google_token()
,
should_skip_token_checks()
,
token_exists()
This helper function lets you use environment variables to auto-authenticate on package load, intended for calling by gar_attach_auto_auth
gar_auto_auth(required_scopes, environment_var = "GAR_AUTH_FILE")
gar_auto_auth(required_scopes, environment_var = "GAR_AUTH_FILE")
required_scopes |
Required scopes needed to authenticate - needs to match at least one |
environment_var |
Name of environment var that contains auth file path The authentication file can be a You can use this in your code to authenticate from a file location specified in file, but it is mainly intended to be called on package load via gar_attach_auto_auth.
|
an OAuth token object, specifically a
Token2.0
, invisibly
Help files for .onAttach
Other authentication functions:
gar_attach_auto_auth()
,
gar_auth()
,
gar_auth_service()
,
gar_gce_auth()
,
get_google_token()
,
should_skip_token_checks()
,
token_exists()
Turn a list of gar_fetch_functions into batch functions
gar_batch( function_list, ..., batch_endpoint = getOption("googleAuthR.batch_endpoint", default = "https://www.googleapis.com/batch") )
gar_batch( function_list, ..., batch_endpoint = getOption("googleAuthR.batch_endpoint", default = "https://www.googleapis.com/batch") )
function_list |
a list of functions from |
... |
further arguments passed to the data parse function of f |
batch_endpoint |
the batch API endpoint to send to |
This function will turn all the individual Google API functions into one POST request to /batch.
If you need to pass multiple data parse function arguments its probably best to do it in separate batches to avoid confusion.
A list of the Google API responses
https://developers.google.com/webmaster-tools/v3/how-tos/batch
Documentation on doing batch requests for the search console API. Other Google APIs are similar.
Walk through API calls changing parameters using gar_batch_walk
Other batch functions:
gar_batch_walk()
## Not run: ## usually set on package load options(googleAuthR.batch_endpoint = "https://www.googleapis.com/batch/urlshortener/v1") ## from goo.gl API 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) } ## from goo.gl API user_history <- function(){ f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url/history", "GET", data_parse_function = function(x) x$items) f() } gar_batch(list(shorten_url("http://markedmondson.me"), user_history())) ## End(Not run)
## Not run: ## usually set on package load options(googleAuthR.batch_endpoint = "https://www.googleapis.com/batch/urlshortener/v1") ## from goo.gl API 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) } ## from goo.gl API user_history <- function(){ f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url/history", "GET", data_parse_function = function(x) x$items) f() } gar_batch(list(shorten_url("http://markedmondson.me"), user_history())) ## End(Not run)
Convenience function for walking through data in batches
gar_batch_walk( f, walk_vector, gar_pars = NULL, gar_paths = NULL, the_body = NULL, pars_walk = NULL, path_walk = NULL, body_walk = NULL, batch_size = 10, batch_function = NULL, data_frame_output = TRUE, ..., batch_endpoint = getOption("googleAuthR.batch_endpoint", default = "https://www.googleapis.com/batch") )
gar_batch_walk( f, walk_vector, gar_pars = NULL, gar_paths = NULL, the_body = NULL, pars_walk = NULL, path_walk = NULL, body_walk = NULL, batch_size = 10, batch_function = NULL, data_frame_output = TRUE, ..., batch_endpoint = getOption("googleAuthR.batch_endpoint", default = "https://www.googleapis.com/batch") )
f |
a function from |
walk_vector |
a vector of the parameter or path to change |
gar_pars |
a list of parameter arguments for f |
gar_paths |
a list of path arguments for f |
the_body |
a list of body arguments for f |
pars_walk |
a character vector of the parameter(s) to modify for each walk of f |
path_walk |
a character vector of the path(s) to modify for each walk of f |
body_walk |
a character vector of the body(s) to modify for each walk of f |
batch_size |
size of each request to Google /batch API |
batch_function |
a function that will act on the result list of each batch API call |
data_frame_output |
if the list of lists are dataframes, you can bind them all by setting to TRUE |
... |
further arguments passed to the data parse function of f |
batch_endpoint |
the batch API endpoint to send |
You can modify more than one parameter or path arg,
but it must be the same walked vector e.g. start = end = x
Many Google APIs have batch_size
limits greater than 10, 1000 is common.
The 'f' function needs to be a 'gar_api_generator()' function that uses one of 'path_args', 'pars_args' or 'body_args' to construct the URL (rather than say using 'sprintf()' to create the API URL).
You don't need to set the headers in the Google docs for batching API functions - those are done for you.
The argument 'walk_vector' needs to be a vector of the values of the arguments to walk over, which you indicate will walk over the pars/path or body arguments on the function via on of the '*_walk' arguments e.g. if walking over id=1, id=2, for a path argument then it would be 'path_walk="id"' and 'walk_vector=c(1,2,3,4)'
The 'gar_*' parameter is required to pass intended for other arguments to the function 'f' you may need to pass through.
'gar_batch_walk()' only supports changing one value at a time, for one or multiple arguments (I think only changing the 'start-date', 'end-date' example would be the case when you walk through more than one per call)
'batch_size' should be over 1 for batching to be of any benefit at all
The 'batch_function' argument gives you a way to operate on the parsed output of each call
if data_frame_output is FALSE: A list of lists. Outer list the length of number of batches required, inner lists the results from the calls
if data_frame_output is TRUE: The list of lists will attempt to rbind all the results
Other batch functions:
gar_batch()
## Not run: # get a webproperty per account getAccountInfo <- gar_api_generator( "https://www.googleapis.com/analytics/v3/management/accounts", "GET", data_parse_function = function(x) unique(x$items$id)) getWebpropertyInfo <- gar_api_generator( "https://www.googleapis.com/analytics/v3/management/", # don't use sprintf to construct this "GET", path_args = list(accounts = "default", webproperties = ""), data_parse_function = function(x) x$items) walkData <- function(){ # here due to R lazy evaluation accs <- getAccountInfo() gar_batch_walk(getWebpropertyInfo, walk_vector = accs, gar_paths = list("webproperties" = ""), path_walk = "accounts", batch_size = 100, data_frame_output = FALSE) } # do the walk walkData() # to walk body data, be careful to modify a top level body name: changed_emails <- lapply(email, function(x){userRef = list(email = x)}) batched <- gar_batch_walk(users, walk_vector = changed_emails, the_body = list( permissions = list( local = list(permissions) ), userRef = list( email = email[[1]] ) ), body_walk = "userRef", batch_size = 300, data_frame_output = FALSE) ## End(Not run)
## Not run: # get a webproperty per account getAccountInfo <- gar_api_generator( "https://www.googleapis.com/analytics/v3/management/accounts", "GET", data_parse_function = function(x) unique(x$items$id)) getWebpropertyInfo <- gar_api_generator( "https://www.googleapis.com/analytics/v3/management/", # don't use sprintf to construct this "GET", path_args = list(accounts = "default", webproperties = ""), data_parse_function = function(x) x$items) walkData <- function(){ # here due to R lazy evaluation accs <- getAccountInfo() gar_batch_walk(getWebpropertyInfo, walk_vector = accs, gar_paths = list("webproperties" = ""), path_walk = "accounts", batch_size = 100, data_frame_output = FALSE) } # do the walk walkData() # to walk body data, be careful to modify a top level body name: changed_emails <- lapply(email, function(x){userRef = list(email = x)}) batched <- gar_batch_walk(users, walk_vector = changed_emails, the_body = list( permissions = list( local = list(permissions) ), userRef = list( email = email[[1]] ) ), body_walk = "userRef", batch_size = 300, data_frame_output = FALSE) ## End(Not run)
To cache to a file system use memoise::cache_filesystem("cache_folder")
,
suitable for unit testing and works between R sessions.
The cached API calls do not need authentication to be active, but need this function to set caching first.
gar_cache_get_loc() gar_cache_empty() gar_cache_setup( mcache = memoise::cache_memory(), invalid_func = function(req) { tryCatch(req$status_code == 200, error = function(x) FALSE) } )
gar_cache_get_loc() gar_cache_empty() gar_cache_setup( mcache = memoise::cache_memory(), invalid_func = function(req) { tryCatch(req$status_code == 200, error = function(x) FALSE) } )
mcache |
A cache method from memoise. |
invalid_func |
A function that takes API response, and returns |
TRUE
if successful.
## Not run: # demo function to cache within shorten_url_cache <- function(url){ body = list(longUrl = url) f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url", "POST", data_parse_function = function(x) x) f(the_body = body) } ## only cache if this URL gar_cache_setup(invalid_func = function(req){ req$content$longUrl == "http://code.markedmondson.me/" }) # authentication gar_auth() ## caches shorten_url_cache("http://code.markedmondson.me") ## read cache shorten_url("http://code.markedmondson.me") ## ..but dont cache me shorten_url_cache("http://blahblah.com") ## End(Not run)
## Not run: # demo function to cache within shorten_url_cache <- function(url){ body = list(longUrl = url) f <- gar_api_generator("https://www.googleapis.com/urlshortener/v1/url", "POST", data_parse_function = function(x) x) f(the_body = body) } ## only cache if this URL gar_cache_setup(invalid_func = function(req){ req$content$longUrl == "http://code.markedmondson.me/" }) # authentication gar_auth() ## caches shorten_url_cache("http://code.markedmondson.me") ## read cache shorten_url("http://code.markedmondson.me") ## ..but dont cache me shorten_url_cache("http://blahblah.com") ## End(Not run)
Useful for debugging authentication issues
gar_check_existing_token(token = .auth$cred)
gar_check_existing_token(token = .auth$cred)
token |
A token to check, default current live session token |
Will compare the passed token's settings and compare to set options. If these differ, then reauthentication may be needed.
FALSE
if the options and current token do not match, TRUE
if they do.
Create the API objects from the Discovery API
gar_create_api_objects(filename, api_json, format = TRUE)
gar_create_api_objects(filename, api_json, format = TRUE)
filename |
File to write the objects to |
api_json |
The json from gar_discovery_api |
format |
If TRUE will use tidy_eval on content |
TRUE if successful, side-effect creating filename
Other Google Discovery API functions:
gar_create_api_skeleton()
,
gar_create_package()
,
gar_discovery_api()
,
gar_discovery_apis_list()
This will create a file with the skeleton of the API functions for the specified library
gar_create_api_skeleton(filename, api_json, format = TRUE)
gar_create_api_skeleton(filename, api_json, format = TRUE)
filename |
R file to write skeleton to |
api_json |
The json from gar_discovery_api |
format |
If TRUE will use tidy_eval on content |
TRUE if successful, side effect will write a file
Other Google Discovery API functions:
gar_create_api_objects()
,
gar_create_package()
,
gar_discovery_api()
,
gar_discovery_apis_list()
Create a Google API package
gar_create_package( api_json, directory, rstudio = TRUE, check = FALSE, github = FALSE, format = TRUE, overwrite = TRUE )
gar_create_package( api_json, directory, rstudio = TRUE, check = FALSE, github = FALSE, format = TRUE, overwrite = TRUE )
api_json |
json from gar_discovery_api |
directory |
Where to build the package |
rstudio |
Passed to create_package, creates RStudio project file |
check |
Perform a check on the package once done |
github |
If TRUE will upload package to your github |
format |
If TRUE will use tidy_eval on content |
overwrite |
Whether to overwrite an existing directory if it exists |
For github upload to work you need to have your github PAT setup. See use_github.
Uses usethis to create a package structure then gar_create_api_skeleton and gar_create_api_objects to create starting files for a Google API package.
If check is TRUE, the results of the CRAN check, else FALSE
https://developers.google.com/discovery/v1/reference/apis/list
A Github repository with 154 R packages examples generated by this function.
Other Google Discovery API functions:
gar_create_api_objects()
,
gar_create_api_skeleton()
,
gar_discovery_api()
,
gar_discovery_apis_list()
Put googleAuthR into a de-authorized state. Instead of sending a token, googleAuthR will send an API key. This can be used to access public resources for which no Google sign-in is required. This is handy for using googleAuthR in a non-interactive setting to make requests that do not require a token. It will prevent the attempt to obtain a token interactively in the browser. The user can configure their own API key via [gar_auth_configure()] and retrieve that key via [gar_api_key()]. In the absence of a user-configured key, a built-in default key is used.
gar_deauth()
gar_deauth()
Other auth functions:
gar_auth_configure()
## Not run: gar_deauth() ## End(Not run)
## Not run: gar_deauth() ## End(Not run)
Read the diagnostic object returned on API parse errors.
gar_debug_parsing(filename = "gar_parse_error.rds")
gar_debug_parsing(filename = "gar_parse_error.rds")
filename |
The file created from API errors, usually called |
When googleAuthR API parsing fails, it will write a file called gar_parse_error.rds to the directory. Feed that file into this function to help diagnose the problem.
Download the discovery document for an API
gar_discovery_api(api, version, a_url = NULL)
gar_discovery_api(api, version, a_url = NULL)
api |
The API to fetch |
version |
The API version to fetch |
a_url |
Supply your own discovery URL, for private APIs only |
Details of the API
https://developers.google.com/discovery/v1/getting_started
Other Google Discovery API functions:
gar_create_api_objects()
,
gar_create_api_skeleton()
,
gar_create_package()
,
gar_discovery_apis_list()
Does not require authentication
gar_discovery_apis_list()
gar_discovery_apis_list()
List of Google APIs and their resources
https://developers.google.com/discovery/v1/reference/apis/list
Other Google Discovery API functions:
gar_create_api_objects()
,
gar_create_api_skeleton()
,
gar_create_package()
,
gar_discovery_api()
This takes the metadata auth token in a Google Compute Engine instance as authentication source
gar_gce_auth( service_account = "default", scopes = "https://www.googleapis.com/auth/cloud-platform" )
gar_gce_auth( service_account = "default", scopes = "https://www.googleapis.com/auth/cloud-platform" )
service_account |
Specify a different service account from the |
scopes |
Scopes for the authentication |
service_account
is default
or the service account email
e.g. "[email protected]"
Google Compute Engine instances come with their own authentication tokens.
It has no refresh token so you need to call for a fresh token after approx. one hour. The metadata token will refresh itself when it has about 60 seconds left.
You can only use for scopes specified when creating the instance.
If you want to use them make sure their service account email is added to accounts you want to get data from.
Use options(gargle.gce.use_ip = TRUE)
to activate this upon kubernetes for instance using federated identity
A token
Other authentication functions:
gar_attach_auto_auth()
,
gar_auth()
,
gar_auth_service()
,
gar_auto_auth()
,
get_google_token()
,
should_skip_token_checks()
,
token_exists()
This allows you to take gcloud's application-default login token and turns it into one that can be used by R
gar_gce_auth_default( scopes = getOption("googleAuthR.scopes.selected", "https://www.googleapis.com/auth/cloud-platform") )
gar_gce_auth_default( scopes = getOption("googleAuthR.scopes.selected", "https://www.googleapis.com/auth/cloud-platform") )
scopes |
The scope you created the access_token with |
When authenticating on Google Cloud Platform services, if you are using services that take the cloud scopes you can use gar_gce_auth to generate authentication.
However, for other services that require a user login (such as Google Analytics API), you need a method of authentication where you can use your own email login. You have two options - create a token offline and upload it to the instance, or gcloud
allows you to generate your own token online via gcloud auth application-default login && gcloud auth application-default print-access-token
This function will then take the returned access token and put it within R so it can be used as normal with googleAuthR
functions.
## Not run: ## in the terminal, issue this gcloud command specifying the scopes to authenticate with gcloud auth application-default login \ --scopes=https://www.googleapis.com/auth/analytics.readonly ## access the URL, login and create a verification code, paste in console. ## view then copy-paste the access token, to be passed into the R function gcloud auth application-default print-access-token ## In R: gar_gce_auth_default(<token-copy-pasted>, scopes = 'https://www.googleapis.com/auth/analytics.readonly', cache_file = 'my_ga.auth') # use token to authenticate as you would normally with library ## End(Not run)
## Not run: ## in the terminal, issue this gcloud command specifying the scopes to authenticate with gcloud auth application-default login \ --scopes=https://www.googleapis.com/auth/analytics.readonly ## access the URL, login and create a verification code, paste in console. ## view then copy-paste the access token, to be passed into the R function gcloud auth application-default print-access-token ## In R: gar_gce_auth_default(<token-copy-pasted>, scopes = 'https://www.googleapis.com/auth/analytics.readonly', cache_file = 'my_ga.auth') # use token to authenticate as you would normally with library ## End(Not run)
Get the service email via GCE metadata
gar_gce_auth_email(service_account = "default")
gar_gce_auth_email(service_account = "default")
service_account |
Specify a different service account from the Useful if you don't know the default email and need it for other uses |
the email address character string
Reports whether googleAuthR has stored a token, ready for use in downstream requests.
gar_has_token()
gar_has_token()
Logical.
Other low-level API functions:
gar_token()
gar_has_token()
gar_has_token()
Helper for working with scopes
gar_scope_config(required_scopes)
gar_scope_config(required_scopes)
required_scopes |
character vector of scopes to add |
These functions let you create a service JSON key from an OAuth2 login. You can then assign it roles and do a one time download of a service account key to use for authentication in other Google APIs
gar_service_create( accountId, projectId, serviceName = "googleAuthR::gar_service_create", serviceDescription = "A service account created via googleAuthR" ) gar_service_grant_roles( accountIds, roles, projectId, type = c("serviceAccount", "user", "group") ) gar_service_get_roles( projectId, accountId = NULL, type = c("serviceAccount", "user", "group") ) gar_service_key( accountId, projectId, file = paste0(accountId, "-auth-key.json") ) gar_service_key_list(accountId, projectId) gar_service_list(projectId) gar_service_get(accountId, projectId)
gar_service_create( accountId, projectId, serviceName = "googleAuthR::gar_service_create", serviceDescription = "A service account created via googleAuthR" ) gar_service_grant_roles( accountIds, roles, projectId, type = c("serviceAccount", "user", "group") ) gar_service_get_roles( projectId, accountId = NULL, type = c("serviceAccount", "user", "group") ) gar_service_key( accountId, projectId, file = paste0(accountId, "-auth-key.json") ) gar_service_key_list(accountId, projectId) gar_service_list(projectId) gar_service_get(accountId, projectId)
accountId |
The service accountId |
projectId |
The projectId containing the service account |
serviceName |
Name of service account |
serviceDescription |
Description of service account |
accountIds |
A vector of accountIds in the form |
roles |
A character vector of roles to give the accountIds e.g. |
type |
The type of accountId to add role for - e.g. |
file |
The file to download the private JSON key to |
It will download the existing roles, and append the role you add to it here.
If you supply an accountId to gar_service_get_roles
then it will return only those roles that accountId has.
If it already exists, returns it via gar_service_get, else creates the service key
Combine these functions to provision emails in one step with gar_service_provision
https://cloud.google.com/resource-manager/reference/rest/v1/projects/setIamPolicy
https://cloud.google.com/resource-manager/reference/rest/v1/projects/setIamPolicy
https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts.keys/create
Other IAM functions:
gar_service_provision()
## Not run: # all roles projectId <- gar_set_client( json = Sys.getenv("GAR_CLIENT_JSON"), scopes = "https://www.googleapis.com/auth/cloud-platform") gar_service_get_roles(projectId) # roles for one accountId gar_service_get_roles( projectId, accountId = "[email protected]") ## End(Not run) ## Not run: library(googleAuthR) gar_set_client(scopes = "https://www.googleapis.com/auth/cloud-platform") gar_auth() gar_service_create("test12345678", "my-project") gar_service_get("[email protected]", projectId = "my-project") gar_service_grant_roles("[email protected]", role = "roles/editor", projectId = "my-project") gar_service_key("test12345678", "my-project", "my-auth.json") gar_service_list("my-project") gar_service_key_list("test12345678", "my-project") ## End(Not run)
## Not run: # all roles projectId <- gar_set_client( json = Sys.getenv("GAR_CLIENT_JSON"), scopes = "https://www.googleapis.com/auth/cloud-platform") gar_service_get_roles(projectId) # roles for one accountId gar_service_get_roles( projectId, accountId = "[email protected]") ## End(Not run) ## Not run: library(googleAuthR) gar_set_client(scopes = "https://www.googleapis.com/auth/cloud-platform") gar_auth() gar_service_create("test12345678", "my-project") gar_service_get("[email protected]", projectId = "my-project") gar_service_grant_roles("[email protected]", role = "roles/editor", projectId = "my-project") gar_service_key("test12345678", "my-project", "my-auth.json") gar_service_list("my-project") gar_service_key_list("test12345678", "my-project") ## End(Not run)
This uses all the gar_service_create functions to enable creating service account roles more easily
gar_service_provision( accountId, roles, json = Sys.getenv("GAR_CLIENT_JSON"), file = paste0(accountId, "-auth-key.json"), email = Sys.getenv("GARGLE_EMAIL") )
gar_service_provision( accountId, roles, json = Sys.getenv("GAR_CLIENT_JSON"), file = paste0(accountId, "-auth-key.json"), email = Sys.getenv("GARGLE_EMAIL") )
accountId |
The service accountId |
roles |
A character vector of roles to give the accountIds e.g. |
json |
The file location of an OAuth 2.0 client ID json file |
file |
The file to download the private JSON key to |
email |
An existing gargle cached email to authenticate with or TRUE to authenticate with the only email available. |
You will need the OAuth2.0 Client ID JSON from your GCP project via
menu icon > APIs & Services > Credentials > Create Credentials > OAuth client ID
You need to authenticate with a user with permission iam.serviceAccounts.create
for the project. Most often the user is an Owner/Editor
Other IAM functions:
gar_service_create()
## Not run: gar_service_provision("my-service-account", c("roles/viewer", "roles/bigquery.jobUser")) ## End(Not run)
## Not run: gar_service_provision("my-service-account", c("roles/viewer", "roles/bigquery.jobUser")) ## End(Not run)
Help setup the client ID and secret with the OAuth 2.0 clientID. Do not confuse with Service account keys.
gar_set_client( json = Sys.getenv("GAR_CLIENT_JSON"), web_json = Sys.getenv("GAR_CLIENT_WEB_JSON"), scopes = NULL, activate = c("offline", "web") )
gar_set_client( json = Sys.getenv("GAR_CLIENT_JSON"), web_json = Sys.getenv("GAR_CLIENT_WEB_JSON"), scopes = NULL, activate = c("offline", "web") )
json |
The file location of an OAuth 2.0 client ID json file |
web_json |
The file location of client ID json file for web applications |
scopes |
A character vector of scopes to set |
activate |
Which credential to activate |
This function helps set the options(googleAuthR.client_id)
,
options(googleAuthR.client_secret)
and
options(googleAuthR.scopes.selected)
for you.
You can also set the web application client IDs that are used in Shiny authentication,
that are set via the options options(googleAuthR.webapp.client_id)
,
options(googleAuthR.webapp.client_secret)
Note that if you authenticate with a cache token with different values it will overwrite them.
For successful authentication, the API scopes can be browsed via the googleAuthR RStudio addin or the Google API documentation.
Do not confuse this JSON file with the service account keys, that are used to authenticate a service email. This JSON only sets up which app you are going to authenticate with - use gar_auth_service with the Service account keys JSON to perform the actual authentication.
By default the JSON file will be looked for in the location specified by the
"GAR_CLIENT_JSON"
environment argument, or via "GAR_CLIENT_WEB_JSON"
for webapps.
The project-id
the app has been set for
Idea via @jennybc and @jimhester from gargle and gmailr
libraries.
https://console.cloud.google.com/apis/credentials
## Not run: gar_set_client("google-client.json", scopes = "http://www.googleapis.com/auth/webmasters") gar_auth_service("google-service-auth.json") ## End(Not run)
## Not run: gar_set_client("google-client.json", scopes = "http://www.googleapis.com/auth/webmasters") gar_auth_service("google-service-auth.json") ## End(Not run)
Check service key works via environment argument
gar_setup_auth_check( env_arg = "GCE_AUTH_FILE", scope = "https://www.googleapis.com/auth/cloud-platform" )
gar_setup_auth_check( env_arg = "GCE_AUTH_FILE", scope = "https://www.googleapis.com/auth/cloud-platform" )
env_arg |
The authentication environment argument |
scope |
The scope of the GCP request |
Other setup functions:
gar_setup_auth_key()
,
gar_setup_clientid()
,
gar_setup_edit_renviron()
,
gar_setup_env_check()
,
gar_setup_menu()
,
gar_setup_menu_do()
This will use your Google OAuth2 user to create a suitable service account
gar_setup_auth_key( email = Sys.getenv("GARGLE_EMAIL"), file = "googleauthr-auth-key.json", session_user = NULL, client_json = "GAR_CLIENT_JSON", roles = NULL, default_key = "googleauthr" )
gar_setup_auth_key( email = Sys.getenv("GARGLE_EMAIL"), file = "googleauthr-auth-key.json", session_user = NULL, client_json = "GAR_CLIENT_JSON", roles = NULL, default_key = "googleauthr" )
email |
What email to open OAuth2 with |
file |
Where to save the authentication file |
session_user |
1 for user level, 2 for project level, leave |
client_json |
The location of the env arg holding client json |
roles |
Whether to assign roles to the service key |
default_key |
The default name of the service key |
TRUE if the file is ready to be setup, FALSE if need to stop
Other setup functions:
gar_setup_auth_check()
,
gar_setup_clientid()
,
gar_setup_edit_renviron()
,
gar_setup_env_check()
,
gar_setup_menu()
,
gar_setup_menu_do()
Check for a client JSON
gar_setup_clientid(session_user = NULL, client_json = "GAR_CLIENT_JSON")
gar_setup_clientid(session_user = NULL, client_json = "GAR_CLIENT_JSON")
session_user |
1 for user level, 2 for project level, leave |
client_json |
The environment argument to be used for client_id/secret |
TRUE is client_id is ready, FALSE if it is not
Other setup functions:
gar_setup_auth_check()
,
gar_setup_auth_key()
,
gar_setup_edit_renviron()
,
gar_setup_env_check()
,
gar_setup_menu()
,
gar_setup_menu_do()
Setup wizard help - asking users to edit .Renviron
gar_setup_edit_renviron(to_paste, session_user) gar_setup_check_session(session_user = NULL)
gar_setup_edit_renviron(to_paste, session_user) gar_setup_check_session(session_user = NULL)
to_paste |
The line to paste into .Renviron |
session_user |
whether its a 1 = user level or 2=project level .Renviron file Intended to get user input from a menu, 1 indicating user level, 2 project level gar_setup_check_session creates a menu for the user to choose which |
Other setup functions:
gar_setup_auth_check()
,
gar_setup_auth_key()
,
gar_setup_clientid()
,
gar_setup_env_check()
,
gar_setup_menu()
,
gar_setup_menu_do()
## Not run: choice <- gar_setup_check_session() gar_setup_edit_renviron("ENV_ARG=blah", session_user = choice) ## End(Not run)
## Not run: choice <- gar_setup_check_session() gar_setup_edit_renviron("ENV_ARG=blah", session_user = choice) ## End(Not run)
Setup wizard help - check if environment argument is set
gar_setup_env_check(env_arg, set_to, edit_option = FALSE, session_user)
gar_setup_env_check(env_arg, set_to, edit_option = FALSE, session_user)
env_arg |
The environment argument to check |
set_to |
NULL or a string to set in .Renviron |
edit_option |
Pass edit_option = FALSE to edit an existing environment arg |
session_user |
1=user, 2=project scope of .Renviron |
Pass edit_option = FALSE to edit an existing environment arg, TRUE will check if it exists, and will pass if its present.
TRUE once changes made
Other setup functions:
gar_setup_auth_check()
,
gar_setup_auth_key()
,
gar_setup_clientid()
,
gar_setup_edit_renviron()
,
gar_setup_menu()
,
gar_setup_menu_do()
Setup wizard helper - add authentication file to .Renviron
gar_setup_get_authenv(env_arg = "GCE_AUTH_FILE", ...)
gar_setup_get_authenv(env_arg = "GCE_AUTH_FILE", ...)
env_arg |
The environment argument to set |
... |
Other arguments passed to gar_setup_auth_key |
A string to paste into an .Renviron, or NULL
This can be used at the top of the server function for authentication when you have used gar_shiny_ui to create a login page for your ui function.
In some platforms the URL you are authenticating from will not match the Docker container the script is running in (e.g. shinyapps.io or a kubernetes cluster) - in that case you can manually set it via 'options(googleAuthR.redirect = http://your-shiny-url'). In other circumstances the Shiny app should be able to detect this itself.
gar_shiny_auth(session)
gar_shiny_auth(session)
session |
Shiny session argument |
If using gar_shiny_ui, put this at the top of your server.R function
Based on a gist by Joe Cheng, RStudio
Other pre-load shiny authentication:
gar_shiny_auth_url()
,
gar_shiny_login_ui()
,
gar_shiny_ui()
,
silent_auth()
## Not run: library(shiny) library(googleAuthR) gar_set_client() fileSearch <- function(query) { googleAuthR::gar_api_generator("https://www.googleapis.com/drive/v3/files/", "GET", pars_args=list(q=query), data_parse_function = function(x) x$files)() } ## ui.R ui <- fluidPage(title = "googleAuthR Shiny Demo", textInput("query", label = "Google Drive query", value = "mimeType != 'application/vnd.google-apps.folder'"), tableOutput("gdrive") ) ## server.R server <- function(input, output, session){ # this is not reactive, no need as you only reach here authenticated gar_shiny_auth(session) output$gdrive <- renderTable({ req(input$query) # no need for with_shiny() fileSearch(input$query) }) } # gar_shiny_ui() needs to wrap the ui you have created above. shinyApp(gar_shiny_ui(ui), server) ## End(Not run)
## Not run: library(shiny) library(googleAuthR) gar_set_client() fileSearch <- function(query) { googleAuthR::gar_api_generator("https://www.googleapis.com/drive/v3/files/", "GET", pars_args=list(q=query), data_parse_function = function(x) x$files)() } ## ui.R ui <- fluidPage(title = "googleAuthR Shiny Demo", textInput("query", label = "Google Drive query", value = "mimeType != 'application/vnd.google-apps.folder'"), tableOutput("gdrive") ) ## server.R server <- function(input, output, session){ # this is not reactive, no need as you only reach here authenticated gar_shiny_auth(session) output$gdrive <- renderTable({ req(input$query) # no need for with_shiny() fileSearch(input$query) }) } # gar_shiny_ui() needs to wrap the ui you have created above. shinyApp(gar_shiny_ui(ui), server) ## End(Not run)
Set this within your login_ui where you need the Google login.
gar_shiny_auth_url( req, state = getOption("googleAuthR.securitycode"), client.id = getOption("googleAuthR.webapp.client_id"), client.secret = getOption("googleAuthR.webapp.client_secret"), scope = getOption("googleAuthR.scopes.selected"), access_type = c("online", "offline"), prompt = c("consent", "select_account", "both", "none") )
gar_shiny_auth_url( req, state = getOption("googleAuthR.securitycode"), client.id = getOption("googleAuthR.webapp.client_id"), client.secret = getOption("googleAuthR.webapp.client_secret"), scope = getOption("googleAuthR.scopes.selected"), access_type = c("online", "offline"), prompt = c("consent", "select_account", "both", "none") )
req |
a Rook request, do not set as this will be used by Shiny to generate URL |
state |
URL state |
client.id |
client.id |
client.secret |
client.secret |
scope |
API scopes |
access_type |
whether to keep the token |
prompt |
Auto-login if user is recognised or always force signin |
Other pre-load shiny authentication:
gar_shiny_auth()
,
gar_shiny_login_ui()
,
gar_shiny_ui()
,
silent_auth()
An alternative to the immediate login provided by default by gar_shiny_ui
gar_shiny_login_ui(req, title = "googleAuthR Login Demo")
gar_shiny_login_ui(req, title = "googleAuthR Login Demo")
req |
Passed to gar_shiny_auth_url to generate login URL |
title |
The title of the page |
Use gar_shiny_auth_url to create the login URL. You must leave the first argument free as this is used to generate the login, but you can pass other arguments to customise your UI.
Other pre-load shiny authentication:
gar_shiny_auth()
,
gar_shiny_auth_url()
,
gar_shiny_ui()
,
silent_auth()
A function that will turn your ui object into one that will look for Google authentication before loading the main app. Use together with gar_shiny_auth
gar_shiny_ui(ui, login_ui = silent_auth)
gar_shiny_ui(ui, login_ui = silent_auth)
ui |
A Shiny ui object |
login_ui |
A UI or HTML template that is seen before the main app and contains a login in link generated by gar_shiny_auth_url |
Put this at the bottom of your ui.R or pass into shinyApp wrapping your created ui.
Based on this gist by Joe Cheng, RStudio
Other pre-load shiny authentication:
gar_shiny_auth()
,
gar_shiny_auth_url()
,
gar_shiny_login_ui()
,
silent_auth()
## Not run: library(shiny) library(googleAuthR) gar_set_client() fileSearch <- function(query) { googleAuthR::gar_api_generator("https://www.googleapis.com/drive/v3/files/", "GET", pars_args=list(q=query), data_parse_function = function(x) x$files)() } ## ui.R ui <- fluidPage(title = "googleAuthR Shiny Demo", textInput("query", label = "Google Drive query", value = "mimeType != 'application/vnd.google-apps.folder'"), tableOutput("gdrive") ) ## server.R server <- function(input, output, session){ # this is not reactive, no need as you only reach here authenticated gar_shiny_auth(session) output$gdrive <- renderTable({ req(input$query) # no need for with_shiny() fileSearch(input$query) }) } # gar_shiny_ui() needs to wrap the ui you have created above. shinyApp(gar_shiny_ui(ui), server) ## End(Not run)
## Not run: library(shiny) library(googleAuthR) gar_set_client() fileSearch <- function(query) { googleAuthR::gar_api_generator("https://www.googleapis.com/drive/v3/files/", "GET", pars_args=list(q=query), data_parse_function = function(x) x$files)() } ## ui.R ui <- fluidPage(title = "googleAuthR Shiny Demo", textInput("query", label = "Google Drive query", value = "mimeType != 'application/vnd.google-apps.folder'"), tableOutput("gdrive") ) ## server.R server <- function(input, output, session){ # this is not reactive, no need as you only reach here authenticated gar_shiny_auth(session) output$gdrive <- renderTable({ req(input$query) # no need for with_shiny() fileSearch(input$query) }) } # gar_shiny_ui() needs to wrap the ui you have created above. shinyApp(gar_shiny_ui(ui), server) ## End(Not run)
For internal use or for those programming around the Google API. Returns a token pre-processed with [httr::config()]. Most users do not need to handle tokens "by hand" or, even if they need some control, [gar_auth()] is what they need. If there is no current token, [gar_auth()] is called to either load from cache or initiate OAuth2.0 flow. If auth has been deactivated via [gar_deauth()], 'gar_token()' returns 'NULL'.
gar_token()
gar_token()
A 'request' object (an S3 class provided by [httr][httr::httr]).
Other low-level API functions:
gar_has_token()
## Not run: req <- request_generate( "drive.files.get", list(fileId = "abc"), token = gar_token() ) req ## End(Not run)
## Not run: req <- request_generate( "drive.files.get", list(fileId = "abc"), token = gar_token() ) req ## End(Not run)
Get details on the current active auth token to help debug issues
gar_token_info(detail_level = getOption("googleAuthR.verbose", default = 3))
gar_token_info(detail_level = getOption("googleAuthR.verbose", default = 3))
detail_level |
How much info to show |
Get more details on the googleAuthR website.
These are the default options that you can override via options()
googleAuthR.batch_endpoint = "https://www.googleapis.com/batch"
googleAuthR.rawResponse = FALSE
googleAuthR.httr_oauth_cache = ".httr-oauth"
googleAuthR.verbose = 3
googleAuthR.client_id = NULL
googleAuthR.client_secret = NULL
googleAuthR.webapp.client_id = NULL
googleAuthR.webapp.client_secret = NULL
googleAuthR.webapp.port = 1221
googleAuthR.jsonlite.simplifyVector = TRUE
googleAuthR.scopes.selected = NULL
googleAuthR.skip_token_checks = FALSE
googleAuthR.ok_content_types=c("application/json; charset=UTF-8", ("text/html; charset=UTF-8"))
googleAuthR.securitycode = paste0(sample(c(1:9, LETTERS, letters), 20, replace = T), collapse='')
googleAuthR.tryAttempts = 5
Maintainer: Erik Grönroos [email protected]
Authors:
Mark Edmondson [email protected] (ORCID)
Other contributors:
Jennifer Bryan [email protected] [contributor]
Johann deBoer [email protected] [contributor]
Neal Richardson [email protected] [contributor]
David Kulp [email protected] [contributor]
Joe Cheng [email protected] [contributor]
Useful links:
Report bugs at https://github.com/MarkEdmondson1234/googleAuthR/issues
Shiny Module for use with googleSignInUI. Use when you don't need to call APIs, but would like a login to Shiny.
googleSignIn(input, output, session)
googleSignIn(input, output, session)
input |
shiny input (must contain |
output |
shiny output (passed by shiny but not used) |
session |
shiny session |
Call via shiny::callModule(googleSignIn, "your_id")
.
A reactive list with values $id
, $name
, $email
,
$image
and $signed_in
.
Based on original code by David Kulp
Shiny Module for use with googleSignIn. If you just want a login to a Shiny app, without API tokens.
googleSignInUI(id, logout_name = "Sign Out", logout_class = "btn-danger")
googleSignInUI(id, logout_name = "Sign Out", logout_class = "btn-danger")
id |
Shiny id. |
logout_name |
Character. Custom name of the logout button. |
logout_class |
Character. Bootstrap class name for buttons, e.g. "btn-info", "btn-dark". |
Shiny UI
Based on original code by David Kulp
https://github.com/dkulp2/Google-Sign-In
The default for logging in via gar_shiny_ui, this creates no login page and just takes you straight to authentication on Shiny app load.
silent_auth(req)
silent_auth(req)
req |
What Shiny uses to check the URL parameters |
Other pre-load shiny authentication:
gar_shiny_auth()
,
gar_shiny_auth_url()
,
gar_shiny_login_ui()
,
gar_shiny_ui()
Use within tests to skip if a local authentication file isn't available through an environment variable.
skip_if_no_env_auth(env_arg)
skip_if_no_env_auth(env_arg)
env_arg |
The name of the environment argument pointing to the auth file |