api-client.R 5.88 KB
Newer Older
Matija Obreza's avatar
Matija Obreza committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Copyright 2018 Global Crop Diversity Trust
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

.genesysEnv <- new.env(parent = emptyenv())

#' Configure package defaults
.onLoad <- function(libname, pkgname) {
  setup_production()
}

#' Setup for Genesys Production
#'
Matija Obreza's avatar
Matija Obreza committed
24
#' Use the Genesys R Client with <https://www.genesys-pgr.org> requiring \code{\link{user_login}}
Matija Obreza's avatar
Matija Obreza committed
25
26
27
28
29
30
31
32
#'
#' @export
setup_production <- function() {
  setup(server = "https://www.genesys-pgr.org", client_id = "oHgJR.NjcdJAIB175gBDbuLEK3@www.genesys-pgr.org", client_secret = "public")
}

#' Setup for Genesys Sandbox
#'
Matija Obreza's avatar
Matija Obreza committed
33
#' Use the Genesys R Client with <https://sandbox.genesys-pgr.org> requiring \code{\link{user_login}}
Matija Obreza's avatar
Matija Obreza committed
34
35
36
37
38
39
40
41
#'
#' @export
setup_sandbox <- function() {
  setup(server = "https://sandbox.genesys-pgr.org", client_id = "cCS6e.BAn9u2WkhIwgxBLxOVqZ@sandbox.genesys-pgr.org", client_secret = NULL)
}

#' Configure the Genesys environment
#'
Matija Obreza's avatar
Matija Obreza committed
42
#' @param server Server base URL (e.g. "https://www.genesys-pgr.org" or "https://sandbox.genesys-pgr.org")
Matija Obreza's avatar
Matija Obreza committed
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
#' @param client_id OAuth client ID
#' @param client_secret OAuth client secret
#'
#' @export
#' @seealso See utility methods \code{\link{setup_production}}, \code{\link{setup_sandbox}}
#'
#' @examples
#'   # Link with sandbox
#'   setup_sandbox()
#'
setup <- function(server = NULL, client_id = NULL, client_secret = NULL) {
  assign("server", server, envir = .genesysEnv)
  assign("client_id", client_id, envir = .genesysEnv)
  assign("client_secret", client_secret, envir = .genesysEnv)
}

#' Print Genesys client configuration
#'
#' @export
print_setup <- function() {
  message(paste("Genesys URL:", .genesysEnv$server))
  message(paste("Client ID:", .genesysEnv$client_id))
  message(paste("Client secret:", .genesysEnv$client_secret))
}

#' Provide OAuth2 token to use for authorization with Genesys
#'
Matija Obreza's avatar
Matija Obreza committed
70
71
72
#' @param authorization OAuth2 Authorization header obtained from somewhere else (e.g. an ENV variable)
#'
#' @seealso \code{\link{user_login}}, \code{\link{client_login}}
Matija Obreza's avatar
Matija Obreza committed
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
#' @export
authorization <- function(authorization) {
  assign("Authorization", authorization, envir = .genesysEnv)
  message(paste('Genesys Authorization:', authorization))
}

#' Login to Genesys as a user
#'
#' The authorization URL will open in a browser, ask the user to grant
#' permissions to R and the verification code must be copy-pasted after
#' you grant access to the client.
#'
#' @seealso \code{\link{setup}}
#'
#' @export
user_login <- function() {
  url <- paste0(.genesysEnv$server, "/oauth/authorize")
  browseURL(httr::modify_url(url, query = list(
    client_id = .genesysEnv$client_id, client_secret = .genesysEnv$client_secret,
    redirect_uri = "oob",
    scope = "read",
    response_type= "code"
    )))

  code <- readline("Enter the authorization code: ");

  url <- paste0(.genesysEnv$server, "/oauth/token")
  resp <- httr::POST(url, body = list(
    client_id = .genesysEnv$client_id, client_secret = .genesysEnv$client_secret,
    redirect_uri = "oob",
    grant_type = "authorization_code", code = code
    ), encode = "form")

  if (httr::http_type(resp) != "application/json" || httr::status_code(resp) != 200) {
    stop(paste("API did not return json", httr::content(resp, "text")), call. = FALSE)
  }

  parsed <- jsonlite::fromJSON(httr::content(resp, "text"), simplifyVector = FALSE)

  authorization(paste("Bearer", parsed$access_token))

  invisible(structure(
    parsed,
    class = "genesys_auth"
  ))
}


#' Login to Genesys as a service client (system-to-system)
#'
#' The client must be enabled for Client Credential grant on Genesys.
#'
#' @seealso \code{\link{setup}}
#'
#' @export
client_login <- function() {
  url <- paste0(.genesysEnv$server, "/oauth/token")
  resp <- httr::POST(url, body = list(
    client_id = .genesysEnv$client_id, client_secret = .genesysEnv$client_secret,
    grant_type = "client_credentials"
  ), encode = "form")

  if (httr::http_type(resp) != "application/json" || httr::status_code(resp) != 200) {
    stop("API did not return json", call. = FALSE)
  }

  parsed <- jsonlite::fromJSON(httr::content(resp, "text"), simplifyVector = FALSE)

  authorization(paste("Bearer", parsed$access_token))

  invisible(structure(
    parsed,
    class = "genesys_auth"
  ))
}


Matija Obreza's avatar
Matija Obreza committed
150
api_call <- function(path, method = "get") {
Matija Obreza's avatar
Matija Obreza committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
  resp <- httr::GET(api_url(path), httr::add_headers(
    Authorization = .genesysEnv$Authorization
    )
  )
  resp
  if (httr::http_type(resp) != "application/json") {
    stop("API did not return json", call. = FALSE)
  }
  # return(resp)
  parsed <- jsonlite::fromJSON(httr::content(resp, "text"), simplifyVector = FALSE)
  return(parsed)
}


#' Get full Genesys API URL for a specific path
#'
Matija Obreza's avatar
Matija Obreza committed
167
#' @param path relative path of the API endpoint (e.g. \code{/me})
Matija Obreza's avatar
Matija Obreza committed
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
#'
#' @return Absolute URL to an API call
#' @export
#'
#' @examples
#'  api_url("/me")
api_url <- function(path) {
  paste0(.genesysEnv$server, "/api/v0", path)
}

get <- function(path, query = NULL) {
  resp <- httr::GET(api_url(path), httr::add_headers(
    Authorization = .genesysEnv$Authorization
  ))
  if (httr::http_type(resp) != "application/json") {
    stop("API did not return json", call. = FALSE)
  }
  resp
}

post <- function(path, query = NULL, body) {
  resp <- httr::POST(api_url(path), httr::add_headers(
    Authorization = .genesysEnv$Authorization,
    "Content-Type" = "application/json"
  ), body = jsonlite::toJSON(body))
  if (httr::http_type(resp) != "application/json") {
    stop("API did not return json", call. = FALSE)
  }
  resp
}