diff --git a/DESCRIPTION b/DESCRIPTION index 9dd9a45..cb477ae 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -23,6 +23,7 @@ Imports: lifecycle, rlang (>= 1.0.0) Suggests: + connectcreds, covr, knitr, rmarkdown, diff --git a/NEWS.md b/NEWS.md index af36324..5c9cc60 100644 --- a/NEWS.md +++ b/NEWS.md @@ -4,6 +4,9 @@ * `gh()` now uses a cache provided by httr2. This cache lives in `tools::R_user_dir("gh", "cache")`, maxes out at 100 MB, and can be disabled by setting `options(gh_cache = FALSE)` (#203). * Removes usage of mockery (@tanho63, #197) +* `gh_token()` can now pick up on the viewer's GitHub credentials (if any) when + running on Posit Connect (@atheriel, #217). + # gh 1.4.1 * `gh_next()`, `gh_prev()`, `gh_first()` and `gh_last()` diff --git a/R/gh_token.R b/R/gh_token.R index 48dbd32..094a59d 100644 --- a/R/gh_token.R +++ b/R/gh_token.R @@ -46,8 +46,16 @@ gh_token <- function(api_url = NULL) { api_url <- api_url %||% default_api_url() stopifnot(is.character(api_url), length(api_url) == 1) + host_url <- get_hosturl(api_url) + # Check for credentials supplied by Posit Connect. + if (is_installed("connectcreds")) { + if (connectcreds::has_viewer_token(host_url)) { + token <- connectcreds::connect_viewer_token(host_url) + return(gh_pat(token$access_token)) + } + } token <- tryCatch( - gitcreds::gitcreds_get(get_hosturl(api_url)), + gitcreds::gitcreds_get(host_url), error = function(e) NULL ) gh_pat(token$password %||% "") @@ -56,15 +64,7 @@ gh_token <- function(api_url = NULL) { #' @export #' @rdname gh_token gh_token_exists <- function(api_url = NULL) { - api_url <- api_url %||% default_api_url() - tryCatch( - { - token <- gitcreds::gitcreds_get(get_hosturl(api_url)) - gh_pat(token$password) - TRUE - } , - error = function(e) FALSE - ) + tryCatch(nzchar(gh_token(api_url)), error = function(e) FALSE) } gh_auth <- function(token) { diff --git a/tests/testthat/test-gh_token.R b/tests/testthat/test-gh_token.R index 460947e..89b0f70 100644 --- a/tests/testthat/test-gh_token.R +++ b/tests/testthat/test-gh_token.R @@ -163,3 +163,11 @@ test_that("get_apiurl() works", { expect_equal(get_apiurl("https://github.acme.com/OWNER/REPO"), x) expect_equal(get_apiurl("https://github.acme.com/api/v3"), x) }) + +test_that("tokens can be requested from a Connect server", { + skip_if_not_installed("connectcreds") + + token <- strrep("a", 40) + connectcreds::local_mocked_connect_responses(token = token) + expect_equal(gh_token(), gh_pat(token)) +})