api-client.R 7.39 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
# 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())

Matija Obreza's avatar
Matija Obreza committed
17
18
19
20
#' Configure package defaults on load
#' 
#' @param libname Library name
#' @param pkgname Package name
21
#' @keywords internal
Matija Obreza's avatar
Matija Obreza committed
22
23
24
25
26
27
.onLoad <- function(libname, pkgname) {
  setup_production()
}

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

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

#' Configure the Genesys environment
#'
46
#' @param server Server base URL (e.g. "https://api.genesys-pgr.org" or "https://api.sandbox.genesys-pgr.org")
Matija Obreza's avatar
Matija Obreza committed
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
#' @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
74
75
76
#' @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
77
78
79
80
81
82
#' @export
authorization <- function(authorization) {
  assign("Authorization", authorization, envir = .genesysEnv)
  message(paste('Genesys Authorization:', authorization))
}

83
#' Ensure that environment has OAuth token
84
#' @keywords internal
Matija Obreza's avatar
Matija Obreza committed
85
.check_auth <- function() {
86
  if (is.null(.genesysEnv$Authorization)) {
87
    warning("You must first authorize with Genesys with user_login() or client_login(...).");
88
89
90
  }
}

Matija Obreza's avatar
Matija Obreza committed
91
92
93
94
95
96
97
98
#' 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}}
#'
Matija Obreza's avatar
Matija Obreza committed
99
#' @importFrom utils browseURL
Matija Obreza's avatar
Matija Obreza committed
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
#' @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"
  ))
}


163
#' @keywords internal
Matija Obreza's avatar
Matija Obreza committed
164
165
.api_call <- function(path, method = "get") {
  .check_auth()
Matija Obreza's avatar
Matija Obreza committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
  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
182
#' @param path relative path of the API endpoint (e.g. \code{/me})
Matija Obreza's avatar
Matija Obreza committed
183
184
185
186
187
188
189
#'
#' @return Absolute URL to an API call
#' @export
#'
#' @examples
#'  api_url("/me")
api_url <- function(path) {
Matija Obreza's avatar
Matija Obreza committed
190
  paste0(.genesysEnv$server, "/api/v1", path)
Matija Obreza's avatar
Matija Obreza committed
191
192
}

193
194
195
196
197
198
199
200
201
202
203
204
205
206
207

#' Get full Genesys API v1 URL for a specific path
#'
#' @param path relative path of the API v1 endpoint (e.g. \code{/me})
#'
#' @return Absolute URL to an API call
#' @export
#'
#' @examples
#'  api1_url("/me")
api1_url <- function(path) {
  paste0(.genesysEnv$server, "/api/v1", path)
}

#' @keywords internal
Matija Obreza's avatar
Matija Obreza committed
208
209
.get <- function(path, query = NULL) {
  .check_auth()
210
  resp <- httr::GET(api_url(path), query = query, httr::add_headers(
Matija Obreza's avatar
Matija Obreza committed
211
212
213
214
215
216
217
218
    Authorization = .genesysEnv$Authorization
  ))
  if (httr::http_type(resp) != "application/json") {
    stop("API did not return json", call. = FALSE)
  }
  resp
}

219
220
221
222
223
#' HTTP POST method
#'
#' @param path API path
#' @param query query string parameters
#' @param body request body (will be serialized to JSON)
Matija Obreza's avatar
Matija Obreza committed
224
#' @param content.type Content-Type of the body
225
226
#'
#' @return httr response
227
#' @keywords internal
Matija Obreza's avatar
Matija Obreza committed
228
229
.post <- function(path, query = NULL, body = NULL, content.type = "application/json") {
  .check_auth()
230
231
232
233
234
235
236
  content <- jsonlite::toJSON(body)
  if (! is.null(body) && length(body) == 0) {
    # If body is provided, but has length of 0
    content <- "{}"
  }
  # print(paste("Body is:", content))
  resp <- httr::POST(api_url(path), query = query, httr::add_headers(
Matija Obreza's avatar
Matija Obreza committed
237
    Authorization = .genesysEnv$Authorization,
238
239
    "Content-Type" = content.type
  ), body = content)
Matija Obreza's avatar
Matija Obreza committed
240
241
242
  if (httr::status_code(resp) != 200) {
    stop("Genesys responded with HTTP status code ", httr::status_code(resp), ". Expected 200. See response content:\n", httr::content(resp), call. = FALSE)
  }
Matija Obreza's avatar
Matija Obreza committed
243
  if (httr::http_type(resp) != "application/json") {
Matija Obreza's avatar
Matija Obreza committed
244
    stop("API did not return JSON, but Content-Type: ", httr::content(resp), ". See response content:\n", httr::content(resp), call. = FALSE)
Matija Obreza's avatar
Matija Obreza committed
245
246
247
  }
  resp
}