diff --git a/DESCRIPTION b/DESCRIPTION
index ba5429097..e7a3f886d 100644
--- a/DESCRIPTION
+++ b/DESCRIPTION
@@ -29,7 +29,8 @@ Imports:
promises (>= 1.1.0),
sodium,
swagger (> 3.20.3),
- magrittr
+ magrittr,
+ lifecycle
LazyData: TRUE
ByteCompile: TRUE
Suggests:
@@ -82,3 +83,4 @@ Collate:
'utils-pipe.R'
'validate_api_spec.R'
'zzz.R'
+RdMacros: lifecycle
diff --git a/NAMESPACE b/NAMESPACE
index e6d8bccb9..a6320d331 100644
--- a/NAMESPACE
+++ b/NAMESPACE
@@ -16,6 +16,7 @@ export(do_remove_api)
export(do_remove_forward)
export(forward)
export(getCharacterSet)
+export(get_character_set)
export(include_file)
export(include_html)
export(include_md)
@@ -57,7 +58,7 @@ export(pr_set_parsers)
export(pr_set_serializer)
export(pr_set_ui)
export(pr_set_ui_callback)
-export(randomCookieKey)
+export(random_cookie_key)
export(register_parser)
export(register_serializer)
export(register_ui)
@@ -87,12 +88,14 @@ export(serializer_tsv)
export(serializer_unboxed_json)
export(serializer_yaml)
export(sessionCookie)
+export(session_cookie)
export(validate_api_spec)
import(R6)
import(promises)
import(stringi)
importFrom(jsonlite,parse_json)
importFrom(jsonlite,toJSON)
+importFrom(lifecycle,deprecated)
importFrom(magrittr,"%>%")
importFrom(stats,runif)
importFrom(utils,installed.packages)
diff --git a/NEWS.md b/NEWS.md
index 8bd1dd4af..31c0458b1 100644
--- a/NEWS.md
+++ b/NEWS.md
@@ -5,11 +5,11 @@ plumber 1.0.0
* Secret session cookies are now encrypted using `sodium`.
All prior `req$session` information will be lost.
- Please see `?sessionCookie` for more information.
+ Please see `?session_cookie` for more information.
(#404)
* Session cookies set the `HttpOnly` flag by default to mitigate cross-site scripting (XSS).
- Please see `?sessionCookie` for more information.
+ Please see `?session_cookie` for more information.
(#404)
* Wrap `jsonlite::fromJSON` to ensure that `jsonlite` never reads
@@ -42,6 +42,10 @@ plumber 1.0.0
* `addSerializer()` has been deprecated in favor of `register_serializer()` (#584)
+* `getCharacterSet()` has been deprecated in favor of `get_character_set()`.
+* `randomCookieKey()` has been deprecated in favor of `random_cookie_key()`.
+* `sessionCookie()` has been deprecated in favor of `session_cookie()`.
+
### New features
* Serializer functions can now return `PlumberEndpoint` `preexec` and `postexec` hooks in addition to a `serializer` function by using `endpoint_serializer()`. This allows for image serializers to turn on their corresponding graphics device before the route executes and turn the graphics device off after the route executes. (#630)
diff --git a/R/content-types.R b/R/content-types.R
index 881ddaf27..a2f2789f3 100644
--- a/R/content-types.R
+++ b/R/content-types.R
@@ -56,10 +56,10 @@ getContentType <- function(ext, defaultType='application/octet-stream') {
}
#' Request character set
-#' @param contentType Request Content-Type header
+#' @param content_type Request Content-Type header
#' @return Default to `UTF-8`. Otherwise return `charset` defined in request header.
#' @export
-getCharacterSet <- function(contentType = NULL){
- if (is.null(contentType)) return("UTF-8")
- stri_match_first_regex(paste(contentType,"; charset=UTF-8"), "charset=([^;\\s]*)")[,2]
+get_character_set <- function(content_type = NULL) {
+ if (is.null(content_type)) return("UTF-8")
+ stri_match_first_regex(paste(content_type,"; charset=UTF-8"), "charset=([^;\\s]*)")[,2]
}
diff --git a/R/deprecated.R b/R/deprecated.R
index 4437b8a4c..c164b5dbe 100644
--- a/R/deprecated.R
+++ b/R/deprecated.R
@@ -1,9 +1,39 @@
-#' Register a Serializer
-#'
-#' Use [register_serializer()] in favor of addSerializer
+#' Deprecated functions
#'
+#' @describeIn deprecated See [register_serializer()]
#' @export
#' @keywords internal
addSerializer <- function(name, serializer, verbose = TRUE) {
+ lifecycle::deprecate_warn("1.0.0", "addSerializer()", "register_serializer()")
+
register_serializer(name = name, serializer = serializer, verbose = verbose)
}
+
+#' @describeIn deprecated See [get_character_set()]
+#' @export
+getCharacterSet <- function(contentType = NULL) {
+ lifecycle::deprecate_warn("1.0.0", "getCharacterSet()", "get_character_set()")
+ get_character_set(content_type = contentType)
+}
+
+
+#' @describeIn deprecated See [session_cookie()]
+#' @export
+sessionCookie <- function(
+ key,
+ name = "plumber",
+ expiration = FALSE,
+ http = TRUE,
+ secure = FALSE,
+ sameSite = FALSE
+) {
+ lifecycle::deprecate_warn("1.0.0", "sessionCookie()", "session_cookie()")
+ session_cookie(
+ key = key,
+ name = name,
+ expiration = expiration,
+ http = http,
+ secure = secure,
+ same_site = sameSite
+ )
+}
diff --git a/R/parse-body.R b/R/parse-body.R
index 047029c19..80b235199 100644
--- a/R/parse-body.R
+++ b/R/parse-body.R
@@ -137,7 +137,7 @@ parser_picker <- function(content_type, first_byte, filename = NULL, parsers = N
#' # `content-type` header is mostly used to look up charset and adjust encoding
#' parser_dcf <- function(...) {
#' function(value, content_type = "text/x-dcf", ...) {
-#' charset <- getCharacterSet(content_type)
+#' charset <- get_character_set(content_type)
#' value <- rawToChar(value)
#' Encoding(value) <- charset
#' read.dcf(value, ...)
@@ -358,7 +358,7 @@ parser_json <- function(...) {
parser_text <- function(parse_fn = identity) {
stopifnot(is.function(parse_fn))
function(value, content_type = NULL, ...) {
- charset <- getCharacterSet(content_type)
+ charset <- get_character_set(content_type)
txt_value <- rawToChar(value)
Encoding(txt_value) <- charset
parse_fn(txt_value)
diff --git a/R/plumber-response.R b/R/plumber-response.R
index 6b26256cd..536ab0d06 100644
--- a/R/plumber-response.R
+++ b/R/plumber-response.R
@@ -22,7 +22,7 @@ PlumberResponse <- R6Class(
body <- ""
}
- charset <- getCharacterSet(h$HTTP_CONTENT_TYPE)
+ charset <- get_character_set(h$HTTP_CONTENT_TYPE)
if (is.character(body)) {
Encoding(body) <- charset
}
@@ -34,16 +34,30 @@ PlumberResponse <- R6Class(
)
},
# TODO if name and value are a vector of same length, call set cookie many times
- setCookie = function(name, value, path, expiration = FALSE, http = FALSE, secure = FALSE, sameSite=FALSE) {
- self$setHeader("Set-Cookie", cookieToStr(name, value, path, expiration, http, secure, sameSite))
+ setCookie = function(name, value, path, expiration = FALSE, http = FALSE, secure = FALSE, same_site = FALSE) {
+ self$setHeader("Set-Cookie", cookieToStr(
+ name = name,
+ value = value,
+ path = path,
+ expiration = expiration,
+ http = http,
+ secure = secure,
+ same_site = same_site
+ ))
},
- removeCookie = function(name, path, http = FALSE, secure = FALSE, sameSite = FALSE, ...) {
- self$setHeader("Set-Cookie", removeCookieStr(name, path, http, secure, sameSite))
+ removeCookie = function(name, path, http = FALSE, secure = FALSE, same_site = FALSE, ...) {
+ self$setHeader("Set-Cookie", removeCookieStr(
+ name = name,
+ path = path,
+ http = http,
+ secure = secure,
+ same_site = same_site
+ ))
}
)
)
-removeCookieStr <- function(name, path, http = FALSE, secure = FALSE, sameSite = FALSE) {
+removeCookieStr <- function(name, path, http = FALSE, secure = FALSE, same_site = FALSE) {
str <- paste0(name, "=; ")
if (!missing(path)){
str <- paste0(str, "Path=", path, "; ")
@@ -55,8 +69,8 @@ removeCookieStr <- function(name, path, http = FALSE, secure = FALSE, sameSite =
str <- paste0(str, "Secure; ")
}
- if (!missing(sameSite) && is.character(sameSite)) {
- str <- paste0(str, "SameSite=", sameSite, "; ")
+ if (!missing(same_site) && is.character(same_site)) {
+ str <- paste0(str, "SameSite=", same_site, "; ")
}
str <- paste0(str, "Expires=Thu, 01 Jan 1970 00:00:00 GMT")
@@ -71,7 +85,7 @@ cookieToStr <- function(
expiration = FALSE,
http = FALSE,
secure = FALSE,
- sameSite = FALSE,
+ same_site = FALSE,
now = Sys.time() # used for testing. Should not be used in regular code.
){
val <- httpuv::encodeURIComponent(as.character(value))
@@ -89,8 +103,8 @@ cookieToStr <- function(
str <- paste0(str, "Secure; ")
}
- if (!missing(sameSite) && is.character(sameSite)) {
- str <- paste0(str, "SameSite=", sameSite, "; ")
+ if (!missing(same_site) && is.character(same_site)) {
+ str <- paste0(str, "SameSite=", same_site, "; ")
}
if (!missing(expiration)){
diff --git a/R/plumber.R b/R/plumber.R
index 520f99f69..a34d4a88b 100644
--- a/R/plumber.R
+++ b/R/plumber.R
@@ -207,12 +207,13 @@ plumber <- R6Class(
#' @param debug Deprecated. See `$set_debug()`
#' @param swagger Deprecated. See `$set_ui(ui)` or `$set_api_spec()`
#' @param swaggerCallback Deprecated. See `$set_ui_callback()`
+ #' @importFrom lifecycle deprecated
run = function(
host = '127.0.0.1',
port = getOption('plumber.port', NULL),
- swagger = stop("deprecated"),
- debug = stop("deprecated"),
- swaggerCallback = stop("deprecated")
+ swagger = deprecated(),
+ debug = deprecated(),
+ swaggerCallback = deprecated()
) {
if (isTRUE(private$disable_run)) {
@@ -221,35 +222,31 @@ plumber <- R6Class(
# Legacy support for RStudio pro products.
# Checks must be kept for >= 2 yrs after plumber v1.0.0 release date
- if (!missing(debug)) {
- message("`$run(debug)` has been deprecated in v1.0.0 and will be removed in a coming release. Please use `$set_debug(debug)`")
+ if (lifecycle::is_present(debug)) {
+ lifecycle::deprecate_warn("1.0.0", "run(debug = )", "set_debug(debug = )")
self$set_debug(debug)
}
- if (!missing(swagger)) {
+ if (lifecycle::is_present(swagger)) {
if (is.function(swagger)) {
# between v0.4.6 and v1.0.0
- message("`$run(swagger)` has been deprecated in v1.0.0 and will be removed in a coming release. To alter the swagger spec, please use `$set_api_spec(api)`")
+ lifecycle::deprecate_warn("1.0.0", "run(swagger = )", "set_api_spec(api = )")
self$set_api_spec(swagger)
# spec is now enabled by default. Do not alter
} else {
if (isTRUE(private$ui_info$has_not_been_set)) {
# <= v0.4.6
- message("`$run(swagger)` has been deprecated in v1.0.0 and will be removed in a coming release. Please use `$set_ui(ui)`")
+ lifecycle::deprecate_warn("1.0.0", "run(swagger = )", "set_ui(ui = )")
self$set_ui(swagger)
} else {
# $set_ui() has been called (other than during initialization).
# Believe that it is the correct behavior
# Warn about updating the run method
- message(
- "`$run(swagger)` has been deprecated in v1.0.0 and will be removed in a coming release.\n",
- "The plumber UI has already been set. Ignoring `swagger` parameter.\n",
- "Please update your `$run()` method."
- )
+ lifecycle::deprecate_warn("1.0.0", "run(swagger = )", details = "The plumber UI has already been set. Ignoring `swagger` parameter.")
}
}
}
- if (!missing(swaggerCallback)) {
- message("`$run(swaggerCallback)` has been deprecated in v1.0.0 and will be removed in a coming release. Please use `$set_ui_callback(callback)`")
+ if (lifecycle::is_present(swaggerCallback)) {
+ lifecycle::deprecate_warn("1.0.0", "run(swaggerCallback = )", "set_ui_callback(callback = )")
self$set_ui_callback(swaggerCallback)
}
diff --git a/R/pr.R b/R/pr.R
index db79572ef..739384738 100644
--- a/R/pr.R
+++ b/R/pr.R
@@ -331,7 +331,7 @@ pr_hooks <- function(pr,
#' @template param_pr
#' @param key The secret key to use. This must be consistent across all R sessions
#' where you want to save/restore encrypted cookies. It should be produced using
-#' \code{\link{randomCookieKey}}. Please see the "Storing secure keys" section for more details
+#' \code{\link{random_cookie_key}}. Please see the "Storing secure keys" section for more details
#' complex character string to bolster security.
#' @param name The name of the cookie in the user's browser.
#' @param expiration A number representing the number of seconds into the future
@@ -342,10 +342,10 @@ pr_hooks <- function(pr,
#' Defaults to \code{TRUE}.
#' @param secure Boolean that adds the \code{Secure} cookie flag. This should be set
#' when the route is eventually delivered over \href{https://en.wikipedia.org/wiki/HTTPS}{HTTPS}.
-#' @param sameSite A character specifying the SameSite policy to attach to the cookie.
+#' @param same_site A character specifying the SameSite policy to attach to the cookie.
#' If specified, one of the following values should be given: "Strict", "Lax", or "None".
#' If "None" is specified, then the \code{secure} flag MUST also be set for the modern browsers to
-#' accept the cookie. An error will be returned if \code{sameSite = "None"} and \code{secure = FALSE}.
+#' accept the cookie. An error will be returned if \code{same_site = "None"} and \code{secure = FALSE}.
#' If not specified or a non-character is given, no SameSite policy is attached to the cookie.
#' @seealso \itemize{
#' \item \href{https://github.com/jeroen/sodium}{'sodium'}: R bindings to 'libsodium'
@@ -358,7 +358,7 @@ pr_hooks <- function(pr,
#' \dontrun{
#'
#' ## Set secret key using `keyring` (preferred method)
-#' keyring::key_set_with_value("plumber_api", password = plumber::randomCookieKey())
+#' keyring::key_set_with_value("plumber_api", password = plumber::random_cookie_key())
#'
#'
#' pr() %>%
@@ -382,7 +382,7 @@ pr_hooks <- function(pr,
#'
#' ## Save key to a local file
#' pswd_file <- "normal_file.txt"
-#' cat(plumber::randomCookieKey(), file = pswd_file)
+#' cat(plumber::random_cookie_key(), file = pswd_file)
#' # Make file read-only
#' Sys.chmod(pswd_file, mode = "0600")
#'
@@ -408,10 +408,10 @@ pr_cookie <- function(pr,
expiration = FALSE,
http = TRUE,
secure = FALSE,
- sameSite = FALSE) {
+ same_site = FALSE) {
validate_pr(pr)
pr$registerHooks(
- sessionCookie(key = key, name = name, expiration = expiration, http = http, secure = secure, sameSite = sameSite)
+ session_cookie(key = key, name = name, expiration = expiration, http = http, secure = secure, same_site = same_site)
)
invisible(pr)
}
diff --git a/R/session-cookie.R b/R/session-cookie.R
index 95221910e..2834a1889 100644
--- a/R/session-cookie.R
+++ b/R/session-cookie.R
@@ -29,7 +29,7 @@
#'
#' @param key The secret key to use. This must be consistent across all R sessions
#' where you want to save/restore encrypted cookies. It should be produced using
-#' \code{\link{randomCookieKey}}. Please see the "Storing secure keys" section for more details
+#' \code{\link{random_cookie_key}}. Please see the "Storing secure keys" section for more details
#' complex character string to bolster security.
#' @param name The name of the cookie in the user's browser.
#' @param expiration A number representing the number of seconds into the future
@@ -40,10 +40,10 @@
#' Defaults to \code{TRUE}.
#' @param secure Boolean that adds the \code{Secure} cookie flag. This should be set
#' when the route is eventually delivered over \href{https://en.wikipedia.org/wiki/HTTPS}{HTTPS}.
-#' @param sameSite A character specifying the SameSite policy to attach to the cookie.
+#' @param same_site A character specifying the SameSite policy to attach to the cookie.
#' If specified, one of the following values should be given: "Strict", "Lax", or "None".
#' If "None" is specified, then the \code{secure} flag MUST also be set for the modern browsers to
-#' accept the cookie. An error will be returned if \code{sameSite = "None"} and \code{secure = FALSE}.
+#' accept the cookie. An error will be returned if \code{same_site = "None"} and \code{secure = FALSE}.
#' If not specified or a non-character is given, no SameSite policy is attached to the cookie.
#' @export
#' @seealso \itemize{
@@ -57,19 +57,16 @@
#' \dontrun{
#'
#' ## Set secret key using `keyring` (preferred method)
-#' keyring::key_set_with_value("plumber_api", plumber::randomCookieKey())
+#' keyring::key_set_with_value("plumber_api", plumber::random_cookie_key())
#'
#'
#' # Load a plumber API
-#' pr <- plumb_api("plumber", "01-append")
-#'
-#' # Add cookie support and retrieve secret key using `keyring`
-#' pr$registerHooks(
-#' sessionCookie(
+#' plumb_api("plumber", "01-append") %>%
+#' # Add cookie support via `keyring`
+#' pr_cookie(
#' keyring::key_get("plumber_api")
-#' )
-#' )
-#' pr$run()
+#' ) %>%
+#' pr_run()
#'
#'
#' #### -------------------------------- ###
@@ -77,50 +74,45 @@
#'
#' ## Save key to a local file
#' pswd_file <- "normal_file.txt"
-#' cat(plumber::randomCookieKey(), file = pswd_file)
+#' cat(plumber::random_cookie_key(), file = pswd_file)
#' # Make file read-only
#' Sys.chmod(pswd_file, mode = "0600")
#'
#'
#' # Load a plumber API
-#' pr <- plumb_api("plumber", "01-append")
-#'
-#' # Add cookie support and retrieve secret key from file
-#' pr$registerHooks(
-#' sessionCookie(
+#' plumb_api("plumber", "01-append") %>%
+#' # Add cookie support and retrieve secret key from file
+#' pr_cookie(
#' readLines(pswd_file, warn = FALSE)
-#' )
-#' )
-#' pr$run()
-#'
+#' ) %>%
+#' pr_run()
#' }
-
-sessionCookie <- function(
+session_cookie <- function(
key,
name = "plumber",
expiration = FALSE,
http = TRUE,
secure = FALSE,
- sameSite = FALSE
+ same_site = FALSE
) {
if (missing(key)) {
- stop("You must define an encryption key. Please see `?sessionCookie` for more details")
+ stop("You must define an encryption key. Please see `?session_cookie` for more details")
}
key <- asCookieKey(key)
# force the args to evaluate
- list(expiration, http, secure, sameSite)
+ list(expiration, http, secure, same_site)
- # sanity check the sameSite and secure arguments
- if (is.character(sameSite)) {
- sameSite <- match.arg(sameSite, c("Strict", "Lax", "None"))
+ # sanity check the same_site and secure arguments
+ if (is.character(same_site)) {
+ same_site <- match.arg(same_site, c("Strict", "Lax", "None"))
} else {
- sameSite <- FALSE
+ same_site <- FALSE
}
- if (identical(sameSite, "None")) {
+ if (identical(same_site, "None")) {
if (!secure) {
- stop("You must set `secure = TRUE` when `sameSite = \"None\"`. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie")
+ stop("You must set `secure = TRUE` when `same_site = \"None\"`. See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie")
}
}
@@ -147,13 +139,13 @@ sessionCookie <- function(
session <- req$session
# save session in a cookie
if (!is.null(session)) {
- res$setCookie(name, encodeCookie(session, key), expiration = expiration, http = http, secure = secure, sameSite = sameSite)
+ res$setCookie(name, encodeCookie(session, key), expiration = expiration, http = http, secure = secure, same_site = same_site)
} else {
# session is null
if (!is.null(req$cookies[[name]])) {
# no session to save, but had session to parse
# remove cookie session cookie
- res$removeCookie(name, "", expiration = expiration, http = http, secure = secure, sameSite = sameSite)
+ res$removeCookie(name, "", expiration = expiration, http = http, secure = secure, same_site = same_site)
}
}
@@ -166,12 +158,12 @@ sessionCookie <- function(
#'
#' Uses a cryptographically secure pseudorandom number generator from [sodium::helpers()] to generate a 64 digit hexadecimal string. \href{https://github.com/jeroen/sodium}{'sodium'} wraps around \href{https://download.libsodium.org/doc/}{'libsodium'}.
#'
-#' Please see \code{\link{sessionCookie}} for more information on how to save the generated key.
+#' Please see \code{\link{session_cookie}} for more information on how to save the generated key.
#'
#' @return A 64 digit hexadecimal string to be used as a key for cookie encryption.
#' @export
-#' @seealso \code{\link{sessionCookie}}
-randomCookieKey <- function() {
+#' @seealso \code{\link{session_cookie}}
+random_cookie_key <- function() {
sodium::bin2hex(
sodium::random(32)
)
@@ -184,7 +176,7 @@ asCookieKey <- function(key) {
"\n",
"\n\t!! Cookie secret 'key' is `NULL`. Cookies will not be encrypted. !!",
"\n\t!! Support for unencrypted cookies is deprecated and will be removed. !!",
- "\n\t!! Please see `?sessionCookie` for details. !!",
+ "\n\t!! Please see `?session_cookie` for details. !!",
"\n"
)
return(NULL)
@@ -193,7 +185,7 @@ asCookieKey <- function(key) {
if (!is.character(key)) {
stop(
"Illegal cookie secret 'key' detected.",
- "\nPlease see `?sessionCookie` for details."
+ "\nPlease see `?session_cookie` for details."
)
}
@@ -208,7 +200,7 @@ asCookieKey <- function(key) {
"\n",
"\n\t!! Legacy cookie secret 'key' detected! !!",
"\n\t!! Support for legacy cookie secret 'key' is deprecated and will be removed. !!",
- "\n\t!! Please follow the instructions in `?sessionCookie` for creating a new secret key. !!",
+ "\n\t!! Please follow the instructions in `?session_cookie` for creating a new secret key. !!",
"\n"
)
diff --git a/inst/plumber/06-sessions/plumber.R b/inst/plumber/06-sessions/plumber.R
index 21146b45f..6b0c9d9db 100644
--- a/inst/plumber/06-sessions/plumber.R
+++ b/inst/plumber/06-sessions/plumber.R
@@ -10,9 +10,9 @@ function(req, res) {
return(paste0("This is visit #", count))
}
-#* Example using req$session. Requires adding "sessionCookie()" support to your API in order
+#* Example using req$session. Requires adding "session_cookie()" support to your API in order
#* to work:
-#* `pr <- plumb("file.R"); pr$registerHooks(sessionCookie("secret", "cookieName")); pr$run()`
+#* `pr <- plumb("file.R"); pr$registerHooks(session_cookie("secret", "cookieName")); pr$run()`
#* @get /sessionCounter
function(req){
count <- 0
diff --git a/man/addSerializer.Rd b/man/addSerializer.Rd
deleted file mode 100644
index d72ffc035..000000000
--- a/man/addSerializer.Rd
+++ /dev/null
@@ -1,12 +0,0 @@
-% Generated by roxygen2: do not edit by hand
-% Please edit documentation in R/deprecated.R
-\name{addSerializer}
-\alias{addSerializer}
-\title{Register a Serializer}
-\usage{
-addSerializer(name, serializer, verbose = TRUE)
-}
-\description{
-Use \code{\link[=register_serializer]{register_serializer()}} in favor of addSerializer
-}
-\keyword{internal}
diff --git a/man/deprecated.Rd b/man/deprecated.Rd
new file mode 100644
index 000000000..a189158d1
--- /dev/null
+++ b/man/deprecated.Rd
@@ -0,0 +1,34 @@
+% Generated by roxygen2: do not edit by hand
+% Please edit documentation in R/deprecated.R
+\name{addSerializer}
+\alias{addSerializer}
+\alias{getCharacterSet}
+\alias{sessionCookie}
+\title{Deprecated functions}
+\usage{
+addSerializer(name, serializer, verbose = TRUE)
+
+getCharacterSet(contentType = NULL)
+
+sessionCookie(
+ key,
+ name = "plumber",
+ expiration = FALSE,
+ http = TRUE,
+ secure = FALSE,
+ sameSite = FALSE
+)
+}
+\description{
+Deprecated functions
+}
+\section{Functions}{
+\itemize{
+\item \code{addSerializer}: See \code{\link[=register_serializer]{register_serializer()}}
+
+\item \code{getCharacterSet}: See \code{\link[=get_character_set]{get_character_set()}}
+
+\item \code{sessionCookie}: See \code{\link[=session_cookie]{session_cookie()}}
+}}
+
+\keyword{internal}
diff --git a/man/figures/lifecycle-archived.svg b/man/figures/lifecycle-archived.svg
new file mode 100644
index 000000000..48f72a6f3
--- /dev/null
+++ b/man/figures/lifecycle-archived.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/figures/lifecycle-defunct.svg b/man/figures/lifecycle-defunct.svg
new file mode 100644
index 000000000..01452e5fb
--- /dev/null
+++ b/man/figures/lifecycle-defunct.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/figures/lifecycle-deprecated.svg b/man/figures/lifecycle-deprecated.svg
new file mode 100644
index 000000000..4baaee01c
--- /dev/null
+++ b/man/figures/lifecycle-deprecated.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/figures/lifecycle-experimental.svg b/man/figures/lifecycle-experimental.svg
new file mode 100644
index 000000000..d1d060e92
--- /dev/null
+++ b/man/figures/lifecycle-experimental.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/figures/lifecycle-maturing.svg b/man/figures/lifecycle-maturing.svg
new file mode 100644
index 000000000..df7131014
--- /dev/null
+++ b/man/figures/lifecycle-maturing.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/figures/lifecycle-questioning.svg b/man/figures/lifecycle-questioning.svg
new file mode 100644
index 000000000..08ee0c903
--- /dev/null
+++ b/man/figures/lifecycle-questioning.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/figures/lifecycle-soft-deprecated.svg b/man/figures/lifecycle-soft-deprecated.svg
new file mode 100644
index 000000000..9f014fd19
--- /dev/null
+++ b/man/figures/lifecycle-soft-deprecated.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/figures/lifecycle-stable.svg b/man/figures/lifecycle-stable.svg
new file mode 100644
index 000000000..e015dc811
--- /dev/null
+++ b/man/figures/lifecycle-stable.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/figures/lifecycle-superseded.svg b/man/figures/lifecycle-superseded.svg
new file mode 100644
index 000000000..75f24f553
--- /dev/null
+++ b/man/figures/lifecycle-superseded.svg
@@ -0,0 +1 @@
+
\ No newline at end of file
diff --git a/man/getCharacterSet.Rd b/man/get_character_set.Rd
similarity index 66%
rename from man/getCharacterSet.Rd
rename to man/get_character_set.Rd
index 3956288a0..68a07681a 100644
--- a/man/getCharacterSet.Rd
+++ b/man/get_character_set.Rd
@@ -1,13 +1,13 @@
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/content-types.R
-\name{getCharacterSet}
-\alias{getCharacterSet}
+\name{get_character_set}
+\alias{get_character_set}
\title{Request character set}
\usage{
-getCharacterSet(contentType = NULL)
+get_character_set(content_type = NULL)
}
\arguments{
-\item{contentType}{Request Content-Type header}
+\item{content_type}{Request Content-Type header}
}
\value{
Default to \code{UTF-8}. Otherwise return \code{charset} defined in request header.
diff --git a/man/plumber.Rd b/man/plumber.Rd
index eac13a1bc..4cb953006 100644
--- a/man/plumber.Rd
+++ b/man/plumber.Rd
@@ -190,9 +190,9 @@ See also: \code{\link[=pr_run]{pr_run()}}
\if{html}{\out{
}}
}
diff --git a/man/pr_cookie.Rd b/man/pr_cookie.Rd
index 6d3e7d6c2..22f6f4f8e 100644
--- a/man/pr_cookie.Rd
+++ b/man/pr_cookie.Rd
@@ -11,7 +11,7 @@ pr_cookie(
expiration = FALSE,
http = TRUE,
secure = FALSE,
- sameSite = FALSE
+ same_site = FALSE
)
}
\arguments{
@@ -19,7 +19,7 @@ pr_cookie(
\item{key}{The secret key to use. This must be consistent across all R sessions
where you want to save/restore encrypted cookies. It should be produced using
-\code{\link{randomCookieKey}}. Please see the "Storing secure keys" section for more details
+\code{\link{random_cookie_key}}. Please see the "Storing secure keys" section for more details
complex character string to bolster security.}
\item{name}{The name of the cookie in the user's browser.}
@@ -35,10 +35,10 @@ Defaults to \code{TRUE}.}
\item{secure}{Boolean that adds the \code{Secure} cookie flag. This should be set
when the route is eventually delivered over \href{https://en.wikipedia.org/wiki/HTTPS}{HTTPS}.}
-\item{sameSite}{A character specifying the SameSite policy to attach to the cookie.
+\item{same_site}{A character specifying the SameSite policy to attach to the cookie.
If specified, one of the following values should be given: "Strict", "Lax", or "None".
If "None" is specified, then the \code{secure} flag MUST also be set for the modern browsers to
-accept the cookie. An error will be returned if \code{sameSite = "None"} and \code{secure = FALSE}.
+accept the cookie. An error will be returned if \code{same_site = "None"} and \code{secure = FALSE}.
If not specified or a non-character is given, no SameSite policy is attached to the cookie.}
}
\description{
@@ -76,7 +76,7 @@ to prevent others from reading it.
\dontrun{
## Set secret key using `keyring` (preferred method)
-keyring::key_set_with_value("plumber_api", password = plumber::randomCookieKey())
+keyring::key_set_with_value("plumber_api", password = plumber::random_cookie_key())
pr() \%>\%
@@ -100,7 +100,7 @@ pr() \%>\%
## Save key to a local file
pswd_file <- "normal_file.txt"
-cat(plumber::randomCookieKey(), file = pswd_file)
+cat(plumber::random_cookie_key(), file = pswd_file)
# Make file read-only
Sys.chmod(pswd_file, mode = "0600")
diff --git a/man/randomCookieKey.Rd b/man/random_cookie_key.Rd
similarity index 73%
rename from man/randomCookieKey.Rd
rename to man/random_cookie_key.Rd
index 37670942a..1b7695b68 100644
--- a/man/randomCookieKey.Rd
+++ b/man/random_cookie_key.Rd
@@ -1,10 +1,10 @@
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/session-cookie.R
-\name{randomCookieKey}
-\alias{randomCookieKey}
+\name{random_cookie_key}
+\alias{random_cookie_key}
\title{Random cookie key generator}
\usage{
-randomCookieKey()
+random_cookie_key()
}
\value{
A 64 digit hexadecimal string to be used as a key for cookie encryption.
@@ -13,8 +13,8 @@ A 64 digit hexadecimal string to be used as a key for cookie encryption.
Uses a cryptographically secure pseudorandom number generator from \code{\link[sodium:helpers]{sodium::helpers()}} to generate a 64 digit hexadecimal string. \href{https://github.com/jeroen/sodium}{'sodium'} wraps around \href{https://download.libsodium.org/doc/}{'libsodium'}.
}
\details{
-Please see \code{\link{sessionCookie}} for more information on how to save the generated key.
+Please see \code{\link{session_cookie}} for more information on how to save the generated key.
}
\seealso{
-\code{\link{sessionCookie}}
+\code{\link{session_cookie}}
}
diff --git a/man/register_parser.Rd b/man/register_parser.Rd
index 0abd01db7..4f8ab4567 100644
--- a/man/register_parser.Rd
+++ b/man/register_parser.Rd
@@ -56,7 +56,7 @@ Parser function structure is something like below.\if{html}{\out{
# `content-type` header is mostly used to look up charset and adjust encoding
parser_dcf <- function(...) {
function(value, content_type = "text/x-dcf", ...) {
- charset <- getCharacterSet(content_type)
+ charset <- get_character_set(content_type)
value <- rawToChar(value)
Encoding(value) <- charset
read.dcf(value, ...)
diff --git a/man/sessionCookie.Rd b/man/session_cookie.Rd
similarity index 83%
rename from man/sessionCookie.Rd
rename to man/session_cookie.Rd
index 09db4e9ab..2d26c879b 100644
--- a/man/sessionCookie.Rd
+++ b/man/session_cookie.Rd
@@ -1,22 +1,22 @@
% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/session-cookie.R
-\name{sessionCookie}
-\alias{sessionCookie}
+\name{session_cookie}
+\alias{session_cookie}
\title{Store session data in encrypted cookies.}
\usage{
-sessionCookie(
+session_cookie(
key,
name = "plumber",
expiration = FALSE,
http = TRUE,
secure = FALSE,
- sameSite = FALSE
+ same_site = FALSE
)
}
\arguments{
\item{key}{The secret key to use. This must be consistent across all R sessions
where you want to save/restore encrypted cookies. It should be produced using
-\code{\link{randomCookieKey}}. Please see the "Storing secure keys" section for more details
+\code{\link{random_cookie_key}}. Please see the "Storing secure keys" section for more details
complex character string to bolster security.}
\item{name}{The name of the cookie in the user's browser.}
@@ -32,10 +32,10 @@ Defaults to \code{TRUE}.}
\item{secure}{Boolean that adds the \code{Secure} cookie flag. This should be set
when the route is eventually delivered over \href{https://en.wikipedia.org/wiki/HTTPS}{HTTPS}.}
-\item{sameSite}{A character specifying the SameSite policy to attach to the cookie.
+\item{same_site}{A character specifying the SameSite policy to attach to the cookie.
If specified, one of the following values should be given: "Strict", "Lax", or "None".
If "None" is specified, then the \code{secure} flag MUST also be set for the modern browsers to
-accept the cookie. An error will be returned if \code{sameSite = "None"} and \code{secure = FALSE}.
+accept the cookie. An error will be returned if \code{same_site = "None"} and \code{secure = FALSE}.
If not specified or a non-character is given, no SameSite policy is attached to the cookie.}
}
\description{
@@ -73,19 +73,16 @@ to prevent others from reading it.
\dontrun{
## Set secret key using `keyring` (preferred method)
-keyring::key_set_with_value("plumber_api", plumber::randomCookieKey())
+keyring::key_set_with_value("plumber_api", plumber::random_cookie_key())
# Load a plumber API
-pr <- plumb_api("plumber", "01-append")
-
-# Add cookie support and retrieve secret key using `keyring`
-pr$registerHooks(
- sessionCookie(
+plumb_api("plumber", "01-append") \%>\%
+ # Add cookie support via `keyring`
+ pr_cookie(
keyring::key_get("plumber_api")
- )
-)
-pr$run()
+ ) \%>\%
+ pr_run()
#### -------------------------------- ###
@@ -93,22 +90,18 @@ pr$run()
## Save key to a local file
pswd_file <- "normal_file.txt"
-cat(plumber::randomCookieKey(), file = pswd_file)
+cat(plumber::random_cookie_key(), file = pswd_file)
# Make file read-only
Sys.chmod(pswd_file, mode = "0600")
# Load a plumber API
-pr <- plumb_api("plumber", "01-append")
-
-# Add cookie support and retrieve secret key from file
-pr$registerHooks(
- sessionCookie(
+plumb_api("plumber", "01-append") \%>\%
+ # Add cookie support and retrieve secret key from file
+ pr_cookie(
readLines(pswd_file, warn = FALSE)
- )
-)
-pr$run()
-
+ ) \%>\%
+ pr_run()
}
}
\seealso{
diff --git a/pkgdown/_pkgdown.yml b/pkgdown/_pkgdown.yml
index 9d3a08c98..fda47a1e0 100644
--- a/pkgdown/_pkgdown.yml
+++ b/pkgdown/_pkgdown.yml
@@ -88,7 +88,7 @@ reference:
contents:
- 'register_parser'
- 'parser_form'
- - 'getCharacterSet'
+ - 'get_character_set'
- title: Response
contents:
@@ -101,8 +101,8 @@ reference:
- title: Cookies and Filters
contents:
- 'pr_cookie'
- - 'randomCookieKey'
- - 'sessionCookie'
+ - 'random_cookie_key'
+ - 'session_cookie'
- 'forward'
- title: R6 Constructors
diff --git a/tests/testthat/files/entrypoint/entrypoint.R b/tests/testthat/files/entrypoint/entrypoint.R
index 8293ab467..229928310 100644
--- a/tests/testthat/files/entrypoint/entrypoint.R
+++ b/tests/testthat/files/entrypoint/entrypoint.R
@@ -1,4 +1,4 @@
-plumber::addSerializer("fake", function(){
+plumber::register_serializer("fake", function(){
function(val, req, res, errorHandler){
tryCatch({
json <- jsonlite::toJSON(val)
diff --git a/tests/testthat/helper-with-temp-serializers.R b/tests/testthat/helper-with-temp-serializers.R
new file mode 100644
index 000000000..517f54209
--- /dev/null
+++ b/tests/testthat/helper-with-temp-serializers.R
@@ -0,0 +1,10 @@
+
+with_tmp_serializers <- function(expr) {
+ ## Do not _actually_ register test-only serializers
+ cur_serializers <- .globals$serializers
+ on.exit({
+ .globals$serializers <- cur_serializers
+ }, add = TRUE)
+
+ force(expr)
+}
diff --git a/tests/testthat/test-content-type.R b/tests/testthat/test-content-type.R
index a23350b9f..97b684c5e 100644
--- a/tests/testthat/test-content-type.R
+++ b/tests/testthat/test-content-type.R
@@ -20,15 +20,15 @@ test_that("contentType works in files", {
})
test_that("Parses charset properly", {
- charset <- getCharacterSet("Content-Type: text/html; charset=latin1")
+ charset <- get_character_set("Content-Type: text/html; charset=latin1")
expect_equal(charset, "latin1")
- charset <- getCharacterSet("Content-Type: text/html; charset=greek8")
+ charset <- get_character_set("Content-Type: text/html; charset=greek8")
expect_equal(charset, "greek8")
})
test_that("Defaults charset when not there", {
- charset <- getCharacterSet("Content-Type: text/html")
+ charset <- get_character_set("Content-Type: text/html")
expect_equal(charset, "UTF-8")
- charset <- getCharacterSet(NULL)
+ charset <- get_character_set(NULL)
expect_equal(charset, "UTF-8")
})
diff --git a/tests/testthat/test-cookies.R b/tests/testthat/test-cookies.R
index 6aa6e2f11..e2d55a6ba 100644
--- a/tests/testthat/test-cookies.R
+++ b/tests/testthat/test-cookies.R
@@ -51,7 +51,7 @@ test_that("cookies can convert to string", {
expect_equal(cookieToStr("complex2", "forbidden:,%/"), "complex2=forbidden%3A%2C%25%2F")
expect_equal(cookieToStr("abc", 123, path="/somepath"), "abc=123; Path=/somepath")
expect_equal(cookieToStr("abc", 123, http=TRUE, secure=TRUE), "abc=123; HttpOnly; Secure")
- expect_equal(cookieToStr("abc", 123, http=TRUE, secure=TRUE, sameSite="None"), "abc=123; HttpOnly; Secure; SameSite=None")
+ expect_equal(cookieToStr("abc", 123, http=TRUE, secure=TRUE, same_site="None"), "abc=123; HttpOnly; Secure; SameSite=None")
now <- force(Sys.time())
cookieToStr_ <- function(expiration, ...) {
@@ -103,7 +103,7 @@ test_that("remove cookie string works", {
"asdf=; Path=/; HttpOnly; Secure; Expires=Thu, 01 Jan 1970 00:00:00 GMT"
)
expect_equal(
- removeCookieStr("asdf", path = "/", http = TRUE, secure = TRUE, sameSite = "None"),
+ removeCookieStr("asdf", path = "/", http = TRUE, secure = TRUE, same_site = "None"),
"asdf=; Path=/; HttpOnly; Secure; SameSite=None; Expires=Thu, 01 Jan 1970 00:00:00 GMT"
)
})
@@ -176,7 +176,7 @@ test_that("cookie encryption works", {
# check that you can't encode a NULL value
expect_equal(encodeCookie(NULL, NULL), "")
- expect_equal(encodeCookie(NULL, asCookieKey(randomCookieKey())), "")
+ expect_equal(encodeCookie(NULL, asCookieKey(random_cookie_key())), "")
xVals <- list(
list(),
@@ -186,8 +186,8 @@ test_that("cookie encryption works", {
)
keys <- list(
NULL, # no key
- asCookieKey(randomCookieKey()), # random key
- asCookieKey(randomCookieKey()) # different random key
+ asCookieKey(random_cookie_key()), # random key
+ asCookieKey(random_cookie_key()) # different random key
)
for (key in keys) {
@@ -220,25 +220,25 @@ test_that("cookie encyption fails smoothly", {
}) # error from jsonlite::parse_json()
# garbage in, key
expect_error({
- decodeCookie(garbage, asCookieKey(randomCookieKey()))
+ decodeCookie(garbage, asCookieKey(random_cookie_key()))
}, "Could not separate")
infoList <- list(
# different cookies
list(
- a = asCookieKey(randomCookieKey()),
- b = asCookieKey(randomCookieKey()),
+ a = asCookieKey(random_cookie_key()),
+ b = asCookieKey(random_cookie_key()),
error = "Failed to decrypt"
),
# not encrypted, try to decrypt
list(
a = NULL,
- b = asCookieKey(randomCookieKey()),
+ b = asCookieKey(random_cookie_key()),
error = "Could not separate"
),
# encrypted, no decryption
list(
- a = asCookieKey(randomCookieKey()),
+ a = asCookieKey(random_cookie_key()),
b = NULL
# error from jsonlite::parse_json()
)
diff --git a/tests/testthat/test-deprecated.R b/tests/testthat/test-deprecated.R
index 78c492358..7f484b64e 100644
--- a/tests/testthat/test-deprecated.R
+++ b/tests/testthat/test-deprecated.R
@@ -20,7 +20,7 @@ test_that("addFilter continues to work", {
test_that("addGlobalProcessor continues to work", {
pr <- plumber$new()
- expect_warning(pr$addGlobalProcessor(sessionCookie("secret", "cookieName")))
+ expect_warning(pr$addGlobalProcessor(session_cookie("secret", "cookieName")))
})
test_that("addAssets continues to work", {
@@ -30,3 +30,19 @@ test_that("addAssets continues to work", {
val <- pr$route(make_req("GET", "/public/test.txt"), res)
expect_true(inherits(val, "PlumberResponse"))
})
+
+test_that("getCharacterSet continues to work", {
+ expect_equal(
+ lifecycle::expect_deprecated(getCharacterSet(contentType = "foo")),
+ "UTF-8"
+ )
+})
+
+
+test_that("sessionCookie continues to work", {
+ key <- random_cookie_key()
+ cookie_hooks_old <- lifecycle::expect_deprecated(sessionCookie(key))
+ cookie_hooks_new <- expect_silent(session_cookie(key))
+
+ expect_equal(names(cookie_hooks_old), names(cookie_hooks_new))
+})
diff --git a/tests/testthat/test-plumber.R b/tests/testthat/test-plumber.R
index f1b7e02ed..580c6066f 100644
--- a/tests/testthat/test-plumber.R
+++ b/tests/testthat/test-plumber.R
@@ -87,18 +87,28 @@ test_that("plumb accepts a directory with a `plumber.R` file", {
})
test_that("plumb() a dir leverages `entrypoint.R`", {
- expect_null(.globals$serializers$fake, "This just that your Plumber environment is dirty. Restart your R session.")
- r <- plumb(dir = test_path("files/entrypoint/"))
- expect_equal(length(r$endpoints), 1)
- expect_equal(length(r$endpoints[[1]]), 1)
-
- # A global serializer was added by entrypoint.R before parsing
- expect_true(!is.null(.globals$serializers$fake))
+ with_tmp_serializers({
+ expect_false(
+ "fake" %in% registered_serializers(),
+ "This just that your Plumber environment is dirty. Restart your R session."
+ )
+
+ r <- plumb(dir = test_path("files/entrypoint/"))
+ expect_equal(length(r$endpoints), 1)
+ expect_equal(length(r$endpoints[[1]]), 1)
+
+ # A global serializer was added by entrypoint.R before parsing
+ expect_true(
+ "fake" %in% registered_serializers(),
+ "This just that your Plumber environment is dirty. Restart your R session."
+ )
+ })
- # Clean up after ourselves
- gl <- .globals
- gl$serializers["fake"] <- NULL
+ expect_false(
+ "fake" %in% registered_serializers(),
+ "This just that your Plumber environment is dirty. Restart your R session."
+ )
})
test_that("bad `entrypoint.R`s throw", {
diff --git a/tests/testthat/test-response.R b/tests/testthat/test-response.R
index 194d85780..c459f02e2 100644
--- a/tests/testthat/test-response.R
+++ b/tests/testthat/test-response.R
@@ -40,7 +40,7 @@ test_that("can set multiple same-named headers", {
test_that("response properly sets cookies with multiple options", {
res <- PlumberResponse$new()
- res$setCookie("abc", "two words", http=TRUE, secure=TRUE, sameSite="None")
+ res$setCookie("abc", "two words", http=TRUE, secure=TRUE, same_site="None")
head <- res$toResponse()$headers
expect_equal(head[["Set-Cookie"]], "abc=two%20words; HttpOnly; Secure; SameSite=None")
})
diff --git a/tests/testthat/test-serializer.R b/tests/testthat/test-serializer.R
index d9682f5a9..4dbfbbac7 100644
--- a/tests/testthat/test-serializer.R
+++ b/tests/testthat/test-serializer.R
@@ -17,68 +17,70 @@ test_that("JSON is the default serializer", {
})
test_that("Overridden serializers apply on filters and endpoints", {
- customSer <- function(){
- function(val, req, res, errorHandler){
- list(status=201L, headers=list(), body="CUSTOM")
- }
- }
- addSerializer("custom", customSer)
- custom2Ser <- function(){
- function(val, req, res, errorHandler){
- list(status=201L, headers=list(), body="CUSTOM2")
+ with_tmp_serializers({
+ customSer <- function(){
+ function(val, req, res, errorHandler){
+ list(status=201L, headers=list(), body="CUSTOM")
+ }
}
- }
- addSerializer("custom2", custom2Ser)
-
- addSerializer("customOneArg", function(single){
- function(val, req, res, errorHandler){
- list(status=200L, headers=list(), body=list(val=val, arg=single))
- }
- })
+ register_serializer("custom", customSer)
- addSerializer("customMultiArg", function(first, second, third){
- function(val, req, res, errorHandler){
- list(status=200L, headers=list(),
- body=list(val=val, args=list(first=first, second=second, third=third)))
+ custom2Ser <- function(){
+ function(val, req, res, errorHandler){
+ list(status=201L, headers=list(), body="CUSTOM2")
+ }
}
+ register_serializer("custom2", custom2Ser)
+
+ register_serializer("customOneArg", function(single){
+ function(val, req, res, errorHandler){
+ list(status=200L, headers=list(), body=list(val=val, arg=single))
+ }
+ })
+
+ register_serializer("customMultiArg", function(first, second, third){
+ function(val, req, res, errorHandler){
+ list(status=200L, headers=list(),
+ body=list(val=val, args=list(first=first, second=second, third=third)))
+ }
+ })
+
+ r <- plumber$new(test_path("files/serializer.R"))
+ res <- PlumberResponse$new("json")
+ expect_equal(r$serve(make_req("GET", "/"), res)$body, "CUSTOM")
+ expect_equal(res$serializer, customSer())
+
+ res <- PlumberResponse$new("json")
+ expect_equal(r$serve(make_req("GET", "/filter-catch"), res)$body, "CUSTOM2")
+ expect_equal(res$serializer, custom2Ser())
+
+ req <- make_req("GET", "/something")
+ res <- PlumberResponse$new(customSer())
+ expect_equal(r$serve(req, res)$body, "CUSTOM")
+ res$serializer <- customSer()
+
+ req <- make_req("GET", "/something")
+ req$QUERY_STRING <- "type=json"
+ expect_equal(r$serve(req, res)$body, jsonlite::toJSON(4))
+ res$serializer <- serializer_json()
+
+ res <- PlumberResponse$new("json")
+ expect_equal(r$serve(make_req("GET", "/another"), res)$body, "CUSTOM3")
+
+ res <- PlumberResponse$new()
+ body <- r$serve(make_req("GET", "/single-arg-ser"), res)$body
+ expect_equal(body$val, "COA")
+ expect_equal(body$arg, "hi there")
+
+ res <- PlumberResponse$new()
+ body <- r$serve(make_req("GET", "/multi-arg-ser"), res)$body
+ expect_equal(body$val, "MAS")
+ expect_equal(body$args$first, "A")
+ expect_equal(body$args$second, 8)
+ expect_equal(body$args$third, 4.3)
})
- r <- plumber$new(test_path("files/serializer.R"))
- res <- PlumberResponse$new("json")
- expect_equal(r$serve(make_req("GET", "/"), res)$body, "CUSTOM")
- expect_equal(res$serializer, customSer())
-
- res <- PlumberResponse$new("json")
- expect_equal(r$serve(make_req("GET", "/filter-catch"), res)$body, "CUSTOM2")
- expect_equal(res$serializer, custom2Ser())
-
- req <- make_req("GET", "/something")
- res <- PlumberResponse$new(customSer())
- expect_equal(r$serve(req, res)$body, "CUSTOM")
- res$serializer <- customSer()
-
- req <- make_req("GET", "/something")
- req$QUERY_STRING <- "type=json"
- expect_equal(r$serve(req, res)$body, jsonlite::toJSON(4))
- res$serializer <- serializer_json()
-
- res <- PlumberResponse$new("json")
- expect_equal(r$serve(make_req("GET", "/another"), res)$body, "CUSTOM3")
-
- res <- PlumberResponse$new()
- body <- r$serve(make_req("GET", "/single-arg-ser"), res)$body
- expect_equal(body$val, "COA")
- expect_equal(body$arg, "hi there")
-
- res <- PlumberResponse$new()
- body <- r$serve(make_req("GET", "/multi-arg-ser"), res)$body
- expect_equal(body$val, "MAS")
- expect_equal(body$args$first, "A")
- expect_equal(body$args$second, 8)
- expect_equal(body$args$third, 4.3)
-
-
# due to covr changing some code, the return answer is very strange
# the tests below should be skipped on covr
testthat::skip_on_covr()
@@ -97,10 +99,14 @@ test_that("Overridden serializers apply on filters and endpoints", {
# })
test_that("Redundant serializers fail", {
- addSerializer("inc", function(val, req, res, errorHandler){
- list(status=201L, headers=list(), body="CUSTOM2")
+
+ with_tmp_serializers({
+ register_serializer("inc", function(val, req, res, errorHandler){
+ list(status=201L, headers=list(), body="CUSTOM2")
+ })
+ expect_error(plumber$new(test_path("files/serializer-redundant.R")), regexp="Multiple @serializers")
})
- expect_error(plumber$new(test_path("files/serializer-redundant.R")), regexp="Multiple @serializers")
+
})
test_that("Empty serializers fail", {
@@ -131,22 +137,24 @@ test_that("serializer_identity errors call error handler", {
})
test_that("Error handler is passed to serializer", {
- res <- PlumberResponse$new()
- addSerializer("failingSer", function() {
- function(val, req, res, errorHandler){
- errorHandler(req, res, simpleError("A serializer error"))
- }
- })
+ with_tmp_serializers({
+ res <- PlumberResponse$new()
- r <- plumber$new(test_path("files/serializer-error.R"))
+ register_serializer("failingSer", function() {
+ function(val, req, res, errorHandler){
+ errorHandler(req, res, simpleError("A serializer error"))
+ }
+ })
- r$setErrorHandler(function(req, res, err) {
- msg <- paste("Handled:", conditionMessage(err))
- stop(msg)
- })
+ r <- plumber$new(test_path("files/serializer-error.R"))
- expect_error(r$serve(make_req("GET", "/fail"), res),
- regexp = "Handled: A serializer error")
+ r$setErrorHandler(function(req, res, err) {
+ msg <- paste("Handled:", conditionMessage(err))
+ stop(msg)
+ })
+ expect_error(r$serve(make_req("GET", "/fail"), res),
+ regexp = "Handled: A serializer error")
+ })
})
diff --git a/tests/testthat/test-sessions.R b/tests/testthat/test-sessions.R
index 916bc9ace..8827db57e 100644
--- a/tests/testthat/test-sessions.R
+++ b/tests/testthat/test-sessions.R
@@ -19,9 +19,9 @@ make_req_cookie <- function(verb, path, cookie) {
req
}
-test_that("sessionCookie throws missing key", {
+test_that("session_cookie throws missing key", {
expect_error(
- sessionCookie(),
+ session_cookie(),
"You must define an encryption key"
)
})
@@ -34,8 +34,8 @@ test_that("cookies are set", {
r$handle("GET", "/", expr)
- key <- randomCookieKey()
- sc <- sessionCookie(
+ key <- random_cookie_key()
+ sc <- session_cookie(
key,
name = "plcook"
)
@@ -59,8 +59,8 @@ test_that("cookies are unset", {
r$handle("GET", "/", exprRemoveSession)
- key <- randomCookieKey()
- sc <- sessionCookie(
+ key <- random_cookie_key()
+ sc <- session_cookie(
key,
name = "plcook"
)
@@ -91,8 +91,8 @@ test_that("cookies are read", {
r$handle("GET", "/", expr)
- key <- randomCookieKey()
- sc <- sessionCookie(
+ key <- random_cookie_key()
+ sc <- session_cookie(
key,
name = "plcook"
)
@@ -122,8 +122,8 @@ test_that("invalid cookies/JSON are handled", {
r$handle("GET", "/", expr)
- key <- randomCookieKey()
- sc <- sessionCookie(
+ key <- random_cookie_key()
+ sc <- session_cookie(
key,
name = "plcook"
)
@@ -131,7 +131,7 @@ test_that("invalid cookies/JSON are handled", {
res <- PlumberResponse$new()
- badKey <- randomCookieKey()
+ badKey <- random_cookie_key()
x <- list(abc = 1234)
encodedX <- encodeCookie(x, asCookieKey(badKey))
expect_silent({
@@ -154,14 +154,14 @@ test_that("cookie attributes are set", {
r$handle("GET", "/", expr)
- key <- randomCookieKey()
- sc <- sessionCookie(
+ key <- random_cookie_key()
+ sc <- session_cookie(
key,
name = "plcook",
expiration = 10,
http = TRUE,
secure = TRUE,
- sameSite = "None"
+ same_site = "None"
)
r$registerHooks(sc)
diff --git a/tests/testthat/test-tidy-plumber.R b/tests/testthat/test-tidy-plumber.R
index 94cc2189f..d7764da70 100644
--- a/tests/testthat/test-tidy-plumber.R
+++ b/tests/testthat/test-tidy-plumber.R
@@ -84,7 +84,7 @@ test_that("pr_hooks registers hooks", {
test_that("pr_cookie adds cookie", {
p <- pr() %>%
pr_cookie(
- randomCookieKey(),
+ random_cookie_key(),
name = "counter"
) %>%
pr_get("/sessionCounter", function(req) {
diff --git a/vignettes/rendering-output.Rmd b/vignettes/rendering-output.Rmd
index 0b6b71901..cd569ad90 100644
--- a/vignettes/rendering-output.Rmd
+++ b/vignettes/rendering-output.Rmd
@@ -239,14 +239,14 @@ In addition to storing plain-text cookies, Plumber also supports handling cookie
To use this feature, you must explicitly add it to your router after constructing it. For example, you could run the following sequence of commands to create a router that supports encrypted session cookies.
```r
-pr <- plumb("myfile.R")
-pr$registerHooks(sessionCookie("mySecretHere", "cookieName"))
-pr$run()
+plumb("myfile.R") %>%
+ pr_cookie("mySecretHere", "cookieName") %>%
+ pr_run()
```
-You'll notice the above example is using the `sessionCookie` hooks that come with Plumber. By adding registering these hooks on your router, you'll ensure that the `req$session` object is made available on incoming requests and is persisted to the cookie named `cookieName` when the response is ready to be sent to the user. In this example, the key used to encrypt the data is `"mySecretHere"`, which is obviously a very weak secret key.
+You'll notice the above example is using the `session_cookie` hooks that come with Plumber. By adding registering these hooks on your router, you'll ensure that the `req$session` object is made available on incoming requests and is persisted to the cookie named `cookieName` when the response is ready to be sent to the user. In this example, the key used to encrypt the data is `"mySecretHere"`, which is obviously a very weak secret key.
-Unlike `res$setHeader()`, the values attached to `req$session` *are* serialized via `jsonlite`; so you're free to use more complex data structures like lists in your session. Also unlike `res$setHeaders()`, `req$session` encrypts the data using the secret key you provide as the first argument to the `sessionCookie()` function.
+Unlike `res$setHeader()`, the values attached to `req$session` *are* serialized via `jsonlite`; so you're free to use more complex data structures like lists in your session. Also unlike `res$setHeaders()`, `req$session` encrypts the data using the secret key you provide as the first argument to the `session_cookie()` function.
As an example, we'll store an encrypted cookie that counts how many times this client has visited a particular endpoint:
@@ -262,6 +262,6 @@ function(req){
}
```
-Again, you would need to register the `sessionCookie()` hooks on your router before this code would work.
+Again, you would need to register the `session_cookie()` hooks on your router before this code would work.
If you inspect the cookie being set in your browser, you'll find that its value is encrypted by the time it gets to the client. But by the time it arrives in Plumber, your cookie is available as a regular R list and can be read or modified.