10  Secrets

The best way to avoid leaking secrets is to store them in local files. These can then be excluded from Git tracking with a .gitignore file. More likely and safer still, they will be stored within an IDE‘s folder structure (e.g. .Renviron) so that they are available across projects and are not exposed to specific project directories and version control.

10.1 Passwords & RStudio

It’s poor practice to include login details in code. One option is using the .Renviron file for securing credentials. usethis::edit_r_environ() will open your user .Renviron.

If you’re sharing the script, you can anticipate that the environment variable might not be set and use the RStudio API to prompt for credentials. For example:

# Connect to OSCAR database via ODBC DSN
oscar_con <- DBI::dbConnect(
  odbc::odbc(),
  dsn = "OSCAR",
  UID = if (Sys.getenv("oscar_userid") == "") {
    rstudioapi::askForPassword("OSCAR User ID")
  } else {
    Sys.getenv("oscar_userid")
  },
  PWD = if (Sys.getenv("oscar_pwd") == "") {
    rstudioapi::askForPassword("OSCAR Password")
  } else {
    Sys.getenv("oscar_pwd")
  },
  timeout = 10
)

Note that including all the connection logic within a single statement works well with the RStudio Connections tab.

10.2 ToDo