-
Notifications
You must be signed in to change notification settings - Fork 2
/
arc-auth.R
286 lines (228 loc) · 6.96 KB
/
arc-auth.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# Code flow ---------------------------------------------------------------
#' Authorization
#'
#' Authorize your R session to connect to an ArcGIS Portal. See details.
#'
#' @details
#'
#' ArcGIS Online and Enterprise Portals utilize OAuth2 authorization via their REST APIs.
#'
#' - `auth_code()` is the recommend OAuth2 workflow for interactive sessions
#' - `auth_client()` is the recommended OAuth2 workflow for non-interactive sessions
#' - `auth_user()` uses legacy username and password authorization using the `generateToken` endpoint. It is only recommended for legacy systems that do not implement OAuth2.
#' - `auth_binding()` fetches a token from the active portal set by `arcgisbinding`. Uses `arcgisbinding::arc.check_portal()` to extract the authorization token. Recommended if using arcgisbinding.
#'
#' @param client an OAuth 2.0 developer application client ID. By default uses the
#' environment variable `ARCGIS_CLIENT`.
#' @param secret an OAuth 2.0 developer application secret. By default uses the environment
#' variable `ARCGIS_SECRET`.
#' @param host default `"https://www.arcgis.com"`
#' @param expiration the duration of the token in minutes.
#'
#' @rdname auth
#' @export
#' @examples
#'
#' \dontrun{
#' auth_code()
#' auth_client()
#' auth_user()
#' auth_binding()
#' }
#' @returns an `httr2_token`
auth_code <- function(
client = Sys.getenv("ARCGIS_CLIENT"),
host = arc_host()
) {
token_url <- paste(
host,
"sharing",
"rest",
"oauth2",
"token",
sep = "/"
)
auth_url <- paste(
host,
"sharing",
"rest",
"oauth2",
"authorize",
sep = "/"
)
client <- httr2::oauth_client(
id = client,
token_url = token_url
)
auth_url <- httr2::oauth_flow_auth_code_url(
client,
auth_url = auth_url,
redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
)
# open browser
utils::browseURL(auth_url)
{
code <- readline(prompt = "Enter code: ")
}
# use the internal fucntion from httr2 to complete the token
# transfer
fx <- utils::getFromNamespace("oauth_client_get_token", "httr2")
fx(
client,
grant_type = "authorization_code",
code = code,
redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
)
}
# Client auth -------------------------------------------------------------
#' @export
#' @rdname auth
auth_client <- function(client = Sys.getenv("ARCGIS_CLIENT"),
secret = Sys.getenv("ARCGIS_SECRET"),
host = arc_host(),
expiration = 120) {
# https://developers.arcgis.com/documentation/mapping-apis-and-services/security/application-credentials/
token_url <- paste(
host,
"sharing",
"rest",
"oauth2",
"token",
sep = "/"
)
cln <- httr2::oauth_client(client, token_url, secret)
httr2::oauth_flow_client_credentials(
cln,
token_params = list(expiration = expiration)
)
}
# arcgisbinding -----------------------------------------------------------
#' @export
#' @rdname auth
auth_binding <- function() {
rlang::check_installed("arcgisbinding")
tkn <- utils::getFromNamespace("arc.check_portal", "arcgisbinding")()
httr2::oauth_token(tkn[["token"]])
}
# legacy auth -------------------------------------------------------------
# uses request ip does not support other forms
# use oauth as the recommended approach
#' @export
#' @rdname auth
#' @param username default `Sys.getenv("ARCGIS_USER")`.
#' Your username to login. **Do not** hard code this value.
#' @param password default `Sys.getenv("ARCGIS_PASSWORD")`.
#' Your password to login. **Do not** hard code this value.
auth_user <- function(
username = Sys.getenv("ARCGIS_USER"),
password = Sys.getenv("ARCGIS_PASSWORD"),
host = arc_host(),
expiration = 60
) {
if (expiration > 21600) stop("`expiration` cannot be more than 15 days (21600)")
burl <- paste0(host, "/sharing/rest/generateToken")
req <- httr2::req_body_form(
httr2::request(burl),
username = username,
password = password,
client = "requestip",
expiration = expiration,
f = "json"
)
resp <- httr2::req_perform(req)
token_raw <- httr2::resp_body_string(resp)
token <- RcppSimdJson::fparse(token_raw)
detect_errors(token)
# return the token
httr2::oauth_token(
token[["token"]],
expires_in = expiration
)
}
#' @rdname auth
#' @export
#' @param token an object of class `httr2_token` as generated by `auth_code()` or `auth_client()`.
#' @param quietly default `FALSE`. Whether function is verbose.
set_auth_token <- function(token, quietly = FALSE) {
stopifnot(inherits(token, c("httr2_token", "character")))
if (inherits(token, "httr2_token")) {
Sys.setenv("ARCGIS_TOKEN" = token[["access_token"]])
} else if (inherits(token, "character")) {
Sys.setenv("ARCGIS_TOKEN" = token[["access_token"]])
}
if (quietly) return(invisible())
cat("Token set to environment variable `ARCGIS_TOKEN`")
invisible(token)
}
# refreshment -------------------------------------------------------------
#'
#' @rdname auth
#' @export
refresh_token <- function(
token,
client = Sys.getenv("ARCGIS_CLIENT"),
host = arc_host()
) {
token_url <- paste(
host,
"sharing",
"rest",
"oauth2",
"token",
sep = "/"
)
cln <- httr2::oauth_client(client, token_url)
# get the current time
cur_time <- as.numeric(Sys.time())
if (is.null(token[["refresh_token"]])) {
stop("`token` has expired and no `refresh_token` available")
} else
# if it has a refresh check to see if refresh hasn't expired
if ((cur_time + token[["refresh_token_expires_in"]]) < cur_time) {
stop("`refresh_token` has gone past its expiry")
}
# should be able to refresh, go ahead.
httr2::oauth_flow_refresh(cln, token[["refresh_token"]])
}
#' @rdname auth
#' @export
#' @param refresh_threshold default `0`. If token expiry is within this
#' threshold (in seconds) the token will be refreshed only if a
#' `refresh_token` is available. Token refreshing is only possible with
#' `auth_code()` flow.
validate_or_refresh_token <- function(
token,
client = Sys.getenv("ARCGIS_CLIENT"),
host = arc_host(),
refresh_threshold = 0
) {
cur_time <- as.numeric(Sys.time())
# check if token is expired or expires within threshold
# the idea being if the token is going to expire soon, refresh it
if (token[["expires_at"]] - refresh_threshold <= cur_time) {
# if it is refresh the token
token <- refresh_token(client, host, token)
} else {
# if not return token
token
}
}
#' Determines Portal Host
#'
#' Returns a scalar character indicating the host to make requests to.
#'
#' By default, the host is ArcGIS Online <`https://www.arcgis.com`>. If the
#' environment variable `ARCGIS_HOST` is set, it will be returned.
#'
#' @export
#' @examples
#' arc_host()
#' @returns
#' A scalar character, `"https://www.arcgis.com"` by default.
arc_host <- function() {
host <- Sys.getenv("ARCGIS_HOST")
if (host == "") {
host <- "https://www.arcgis.com"
}
host
}