-
Notifications
You must be signed in to change notification settings - Fork 3
/
synapse_authentication.R
438 lines (381 loc) · 14.4 KB
/
synapse_authentication.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# Create Package Environment ---------------------------------------------------
# set environment in which to store URL variable that persists for that session
genieBPC_env <- rlang::new_environment()
# User-facing Authorization Functions -----------------------------------------
#' Connect to 'Synapse' API
#'
#' This function sets 'Synapse' credentials for the user's current session.
#'
#' To access data, users must have a valid 'Synapse' account with permission to
#' access the data set and they must have accepted any necessary 'Terms of Use'.
#' Users must authenticate themselves in their current R session.
#' (See README 'Data Access and Authentication' at https://genie-bpc.github.io/genieBPC/ for details).
#' To set your 'Synapse' credentials during each session, call:
#' `set_synapse_credentials(username = "your_username", password = "your_password")`.
#'
#' In addition to passing your 'Synapse' username and password, you may choose to set
#' your 'Synapse' Personal Access Token (PAT) by calling:
#' `set_synapse_credentials(pat = "your_pat")`.
#'
#' If your credentials are stored as environmental variables, you do not need to call
#' `set_synapse_credentials()` explicitly each session. To store authentication
#' information in your environmental variables, add the following to your
#' .Renviron file, then restart your R session
#' (tip: you can use `usethis::edit_r_environ()` to easily open/edit this file):
#'
#' \itemize{
#' \item `SYNAPSE_USERNAME = <your-username>`
#' \item `SYNAPSE_PASSWORD = <your-password>`
#' \item `SYNAPSE_PAT = <your-pat>`
#' }
#'
#' Alternatively, you can pass your username and password or your PAT to each individual
#' data pull function if preferred, although it is recommended that you manage
#' your passwords outside of your scripts for security purposes.
#'
#' @param username 'Synapse' username. If NULL, package will search
#' environmental variables for `SYNAPSE_USERNAME`.
#' @param password 'Synapse' password. If NULL, package will search
#' environmental variables for `SYNAPSE_PASSWORD`.
#' @param pat 'Synapse' Personal Access Token. If NULL, package will search
#' environmental variables for `SYNAPSE_PAT`.
#' @return A success message if you credentials are valid for 'Synapse'
#' platform; otherwise an error
#'
#' @author Karissa Whiting
#' @export
#'
#' @examples
#' \dontrun{
#' set_synapse_credentials(
#' username = "your-username",
#' password = "your-password"
#' )
#' set_synapse_credentials(
#' pat = "your-personal-access-token"
#' )
#' }
#'
set_synapse_credentials <- function(username = NULL,
password = NULL,
pat = NULL) {
# remove any former objects in environment
suppressWarnings(
rm(list = c("password", "username", "pat"), envir = genieBPC_env))
# Use Passed Arguments First ----------------------------------------------
# * If PAT passed, use that -----------
if(!is.null(pat)) {
verify_cred_works = .get_token_by_pat(pat)
assign("pat", value = pat, envir = genieBPC_env)
cli::cli_alert_success("You are now connected to 'Synapse' with your {.field Personal Access Token} ({.code pat}) for this R session!")
return(invisible())
}
# * If no PAT but username or password --------
null_username_password <- sum(purrr::map_lgl(list(username, password), ~is.null(.x)))
if(sum(null_username_password) < 2) {
# Throw error if only username or password given but not both
if(sum(null_username_password) == 1) {
rlang::abort("User must specify either a `pat`, or BOTH a `username` & `password`.")
}
verify_cred_works = .get_token_by_username(username, password)
# assign username credentials to package environment
assign("username",
value = username,
envir = genieBPC_env
)
assign("password",
value = password,
envir = genieBPC_env
)
cli::cli_alert_success("You are now connected to 'Synapse' as
{.field {username}} for this R session!")
return(invisible())
}
# If None Passed, Use Env Arguments -------------
# Try saved PAT
pat_from_env = Sys.getenv("SYNAPSE_PAT", unset = NA)
username_from_env = Sys.getenv("SYNAPSE_USERNAME", unset = NA)
password_from_env = Sys.getenv("SYNAPSE_PASSWORD", unset = NA)
if(!is.na(pat_from_env)) {
verify_cred_works = .get_token_by_pat(pat_from_env)
assign("pat", value = pat_from_env, envir = genieBPC_env)
cli::cli_alert_success("You are now connected to 'Synapse' with your {.field Personal Access Token} ({.code SYNAPSE_PAT}) for this R session!")
return()
} else if(all(!is.na(c(username_from_env, password_from_env)))) {
verify_cred_works = .get_token_by_username(username_from_env, password_from_env)
# assign username credentials to package environment
assign("username",
value = username_from_env,
envir = genieBPC_env
)
assign("password",
value = password_from_env,
envir = genieBPC_env
)
cli::cli_alert_success("You are now connected to 'Synapse' as
{.field {username_from_env}} for this R session!")
return(invisible())
} else {
rlang::abort("No personal access token (`pat`), `username` or `password` specified and no
`SYNAPSE_PAT`, `SYNAPSE_USERNAME` or `SYNAPSE_PASSWORD` in `.Renviron`.
Try specifying `pat`, `username` or `password` arguments
or use `usethis::edit_r_environ()` to add to your global variables")
}
}
#
# set_synapse_credentials <- function(username = NULL, password = NULL) {
#
# # if no args passed, check sys environment
# resolved_username <- username %||% Sys.getenv("SYNAPSE_USERNAME", unset = NA)
# resolved_password <- password %||% Sys.getenv("SYNAPSE_PASSWORD", unset = NA)
#
# switch(any(is.na(c(resolved_username, resolved_password))),
# {
# rlang::abort("No `username` or `password` specified and no
# `SYNAPSE_USERNAME` or `SYNAPSE_PASSWORD` in `.Renviron`.
# Try specifying `username` or `password` arguments or use
# `usethis::edit_r_environ()` to add to your global variables")
# }
# )
#
# # assign credentials to package environment
# assign("username",
# value = resolved_username,
# envir = genieBPC_env
# )
#
# assign("password",
# value = resolved_password,
# envir = genieBPC_env
# )
#
# # check the credentials with a call
# x <- .get_synapse_token(
# username = resolved_username,
# password = resolved_password
# )
#
# cli::cli_alert_success("You are now connected to 'Synapse' as
# {.field {resolved_username}} for this R session!")
# }
#' Check Access to GENIE Data
#'
#' @param username 'Synapse' username. If NULL, package will search package
#' environment for "username".
#' @param password 'Synapse' password. If NULL, package will search package
#' environment for "password".
#' @param pat 'Synapse' Personal Access Token. If NULL, package will search package
#' environment for "pat".
#' @param check_consortium_access Specifies whether access to GENIE BPC consortium
#' data releases (vs. public data releases) is checked. Default is FALSE,
#' indicating that access to GENIE BPC public data releases is checked instead.
#' @return A success message if you are able to access GENIE BPC data; otherwise
#' an error
#' @author Karissa Whiting
#' @export
#'
#' @examples
#' \dontrun{
#' # if credentials are saved:
#' check_genie_access()
#' }
check_genie_access <- function(username = NULL,
password = NULL,
pat = NULL,
check_consortium_access = FALSE) {
# first get token
token <- .get_synapse_token(username = username,
password = password,
pat = pat)
# now do genie-specific test query
if(check_consortium_access) {
# private GENIE (consortium)
query_url <- "https://repo-prod.prod.sagebase.org/repo/v1/entity/syn21241322/bundle2"
} else {
# public GENIE
query_url <- "https://repo-prod.prod.sagebase.org/repo/v1/entity/syn27056172/bundle2"
}
requested_objects <- jsonlite::toJSON(list(
"includeEntity" = TRUE,
"includeAnnotations" = TRUE,
"includeFileHandles" = TRUE,
"includeRestrictionInformation" = TRUE
),
pretty = TRUE, auto_unbox = TRUE
)
res <- httr::POST(
url = query_url,
body = requested_objects,
httr::add_headers(
Authorization =
paste("Bearer ", token, sep = "")
),
httr::content_type("application/json")
)
if(check_consortium_access) {
error_message <- c("access GENIE consortium data in 'Synapse'. Consortium releases are not available to individuals outside of the AACR Project GENIE BPC Consortium. Please check you've accepted Terms of use, or try accessing a publicly available release instead.")
} else {
error_message <- c("access GENIE data in 'Synapse'. Check that you have permission to view this data")
}
httr::stop_for_status(res, error_message)
cli::cli_alert_success("{httr::http_status(res)$message}:
You are successfully connected to the GENIE database!")
}
# Utility Functions for Authorization -----------------------------------------
#' Get an object from the genieBPC package environment (`genieBPC_env`)
#'
#' @param thing_to_check
#'
#' @return The object
#' @keywords internal
#' @export
#' @examples
#' \dontrun{
#' .get_env("username")
#' }
.get_env <- function(thing_to_check) {
thing <- tryCatch(
{
get(thing_to_check,
envir = genieBPC_env
)
},
error = function(e) {
return(NULL)
}
)
thing
}
#' Retrieve a synapse token using username and password
#'
#' @inheritParams check_genie_access
#'
#' @return a 'Synapse' token. Will first look for PAT and return that if successful HTTP call, else
#' will try with username and password
#' @keywords internal
#' @export
#'
#' @examples
#' \dontrun{
#' .get_synapse_token(username = "test", password = "test")
#' }
.get_synapse_token <- function(username = NULL, password = NULL, pat = NULL) {
# check user passed pat
if(!is.null(pat)) {
token <- .get_token_by_pat(pat)
return(token)
}
# check user passed username/password
if(!is.null(username)) {
if(is.null(password)) {
rlang::abort("User must specify either a `pat`, or BOTH a `username` & `password`.")
} else {
token <- .get_token_by_username(username = username, password = password)
return(token)
}
}
# if no user passed args
resolved_pat <- pat %||% .get_env("pat")
resolved_username <- username %||% .get_env("username")
resolved_password <- password %||% .get_env("password")
# if none found in env
if(is.null(resolved_pat)) {
if(is.null(resolved_username) | is.null(resolved_password)) {
cli::cli_abort("No credentials found. Have you authenticated yourself?
Use {.code set_synapse_credentials()} to set credentials for this session, or pass a {.code pat}, or {.code username} AND {.code password}
(see README:'Data Access & Authentication' for details on authentication).")
}
}
# use package env creds
if(!is.null(resolved_pat)) {
token <- .get_token_by_pat(resolved_pat)
return(token)
} else if(is.null(resolved_pat)) {
token <- .get_token_by_username(resolved_username, resolved_password)
return(token)
}
}
#' Check Synapse Login Status & Ability to Access Data
#'
#' The `.is_connected_to_genie()` function assesses whether the
#' user is logged into 'Synapse' and confirms whether the
#' user has permission to access the GENIE BPC data. It returns TRUE or FALSE
#' @keywords internal
#' @return Returns message indicating user is logged into
#' 'Synapse' and has permission to access the GENIE BPC data.
#' @export
#' @examples
#' .is_connected_to_genie()
.is_connected_to_genie <- function(username = NULL, password = NULL,
pat = NULL,
check_consortium_access = FALSE) {
tryCatch(check_genie_access(username = username,
password = password,
pat = pat,
check_consortium_access = check_consortium_access),
error = function(e) FALSE,
message = function(m) TRUE
)
}
#' Retrieve a synapse token using username and password
#'
#' @inheritParams check_genie_access
#'
#' @return a 'Synapse' token.
#' @keywords internal
#' @export
#'
#' @examples
#' \dontrun{
#' .get_token_by_username(username = "test", password = "test")
#' }
.get_token_by_username <- function(username, password) {
# query to get token
requested_objects <- jsonlite::toJSON(list(
"email" = username,
"password" = password
), pretty = TRUE, auto_unbox = TRUE)
resp <- httr::POST("https://auth-prod.prod.sagebase.org/auth/v1/session",
body = requested_objects,
encode = "json",
httr::add_headers(`accept` = "application/json"),
httr::content_type("application/json")
)
token <- httr::content(resp, "parsed")$sessionToken
if (is.null(token) || any(token == "" | token == " ")) {
cli::cli_abort("There was an error authenticating your
username ({username}) or password.
Please make sure you can login to the 'Synapse' website
with the given credentials.")
}
return(token)
}
#' Retrieve a synapse token using personal access token
#'
#' @inheritParams check_genie_access
#'
#' @return a 'Synapse' token
#' @keywords internal
#' @export
#'
#' @examples
#' \dontrun{
#' .get_token_by_pat(pat = "test")
#' }
.get_token_by_pat <- function(pat) {
if(is.null(pat) | pat == "" | pat == " ") {
cli::cli_abort("Failed to authenticate with PAT. Please check your PAT or supply a username and password")
}
resp <- httr::GET(
paste0("https://auth-prod.prod.sagebase.org/repo/v1/userProfile"),
httr::add_headers(Authorization = paste("Bearer ",
pat,
sep = "")),
# body = requested_objects,
encode = "json",
httr::add_headers(`accept` = "application/json"),
httr::content_type("application/json")
) %>%
httr::stop_for_status("Failed to authenticate with PAT. Please check your PAT or supply a username and password")
return(pat)
}