|
| 1 | +#' @title Auth Class |
| 2 | +#' |
| 3 | +#' @description |
| 4 | +#' Authorization |
| 5 | +#' |
| 6 | +#' @importFrom R6 R6Class |
| 7 | +#' @importFrom magrittr %>% |
| 8 | +#' @export |
| 9 | +Auth <- R6::R6Class("Auth", # nolint: object_name_linter. |
| 10 | + public = list( |
| 11 | + |
| 12 | + #' @description |
| 13 | + #' This function initializes a new instance of the `Auth` class with the specified parameters. |
| 14 | + #' |
| 15 | + #' @param user A character string representing the username for authentication. |
| 16 | + #' @param password A character string representing the password for authentication. |
| 17 | + #' |
| 18 | + #' @return An instance of the `Auth` class. |
| 19 | + #' @export |
| 20 | + initialize = function(user = NULL, password = NULL) { |
| 21 | + private$user <- user |
| 22 | + private$password <- password |
| 23 | + }, |
| 24 | + |
| 25 | + #' @description |
| 26 | + #' This function retrieves a previously generated token. |
| 27 | + #' |
| 28 | + #' @return A character string representing the retrieved token. |
| 29 | + #' @export |
| 30 | + token = function() { |
| 31 | + if (is.null(private$token_value)) { |
| 32 | + self$get_token() |
| 33 | + } |
| 34 | + private$token_value |
| 35 | + }, |
| 36 | + |
| 37 | + #' @description |
| 38 | + #' This function generates a unique token for authentication or other purposes. |
| 39 | + #' |
| 40 | + #' @return A character string representing the generated token. |
| 41 | + #' @export |
| 42 | + get_token = function() { |
| 43 | + url <- paste0(private$apiUrl, "/gettoken") |
| 44 | + |
| 45 | + params <- list( |
| 46 | + "username" = private$user, |
| 47 | + "password" = private$password |
| 48 | + ) |
| 49 | + req <- httr2::request(url) %>% |
| 50 | + httr2::req_method("POST") %>% |
| 51 | + httr2::req_body_json(params) |
| 52 | + |
| 53 | + try(req %>% httr2::req_perform()) |
| 54 | + resp <- httr2::last_response() |
| 55 | + |
| 56 | + if (resp$status_code == 200) { |
| 57 | + resp_body <- resp %>% httr2::resp_body_json() |
| 58 | + private$token_value <- resp_body$access_token |
| 59 | + return(private$token_value) |
| 60 | + } |
| 61 | + |
| 62 | + private$token_value <- NULL |
| 63 | + stop(resp$detail) |
| 64 | + } |
| 65 | + ), |
| 66 | + private = list( |
| 67 | + apiUrl = "https://gateway.prod.wekeo2.eu/hda-broker", |
| 68 | + token_value = NULL, |
| 69 | + user = NULL, |
| 70 | + password = NULL |
| 71 | + ) |
| 72 | +) |
0 commit comments