-
Notifications
You must be signed in to change notification settings - Fork 4
/
edl_s3_token.R
76 lines (71 loc) · 2.46 KB
/
edl_s3_token.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#' Receive and set temporary AWS Tokens for S3 access
#'
#' Note that these S3 credentials will only work:
#'
#' - On AWS instance in the `us-west-2` region
#' - Only for one hour before they expire
#' - Only on the DAAC requested
#'
#' Please consider using [edl_netrc()] to avoid these limitations
#'
#' @param daac the base URL for the DAAC
#' @param username EarthDataLogin user
#' @param password EarthDataLogin Password
#' @param prompt_for_netrc Often netrc is preferable, so this function will by
#' default prompt the user to switch. Set to FALSE to silence this.
#' @return list of access key, secret key, session token and expiration,
#' invisibly. Also sets the corresponding AWS environmental variables.
#'
#' @examplesIf interactive()
#' edl_s3_token()
#' @export
edl_s3_token <- function(daac = "https://data.lpdaac.earthdatacloud.nasa.gov",
username = default("user"),
password = default("password"),
prompt_for_netrc = interactive()) {
if (prompt_for_netrc) {
done <- we_prefer_netrc(username, password)
if (done) return(invisible(TRUE))
}
p <- edl_api(endpoint = "/s3credentials",
username = username,
password = password,
base = daac)
Sys.setenv(AWS_ACCESS_KEY_ID = p$accessKeyId)
Sys.setenv(AWS_SECRET_ACCESS_KEY = p$secretAccessKey)
Sys.setenv(AWS_SESSION_TOKEN = p$sessionToken)
invisible(p)
}
#' Replace https URLs with S3 URIs
#' @param href a https URL from an EarthData Cloud address
#' @param prefix the preferred s3 prefix, e.g. `s3://` (understood by gdalcubes),
#' or `/vsis3`, for terra/stars/sf or other GDAL-based interfaces.
#' @return a URI that strips basename and protocol and appends prefix
#' @export
#' @examples
#' href <- lpdacc_example_url()
#' edl_as_s3(href)
edl_as_s3 <- function(href, prefix = "s3://") {
p <- httr::parse_url(href)
paste0(prefix, p$path)
}
#' Unset AWS S3 Environment Variables
#'
#' This function unsets the AWS S3-related environment variables:
#' \code{AWS_ACCESS_KEY_ID}, \code{AWS_SECRET_ACCESS_KEY}, and \code{AWS_SESSION_TOKEN}.
#'
#' @description
#' The function uses \code{Sys.unsetenv()} to remove the specified environment variables.
#'
#' @seealso
#' \code{\link{Sys.unsetenv}}
#'
#' @examplesIf interactive()
#' edl_unset_s3()
#'
#' @export
edl_unset_s3 <- function() {
Sys.unsetenv("AWS_ACCESS_KEY_ID")
Sys.unsetenv("AWS_SECRET_ACCESS_KEY")
Sys.unsetenv("AWS_SESSION_TOKEN")
}