---
title: "Tokens"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Tokens}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```


# REDCap API tokens

REDCap API tokens are equivalent to your username and password. They should never be shared with anyone. Ideally, they should never be directly written in an R script, especially if you plan on sharing it in the future. **Never commit a file containing your token on git or GitHub because this will forever be in the history.** If there is ever any doubt in your mind you should quickly regenerate your token on the REDCap website. If you are working on a *real* REDCap project it's good practice to regenerate your token periodically, such as once a week, just to be safe.

Precisely because tokens are sensitive, REDCapSync is designed to only reference the name of your token, such as "REDCAPSYNC_FIRST_PROJECT". If REDCapSync ever wants to use the token to make an API call to REDCap, it will check `Sys.getenv("REDCAPSYNC_FIRST_PROJECT")`. By default are token names start with "REDCAPSYNC_", followed by the `project_name` you chose in `setup_project()`. Below demonstrates how to set and check your tokens...

## 1. Setting Your Token using User Environment Variables (preferred)

You may find want to reuse a token, and you may have several projects, so a convenient way to store the tokens in a separate location. One way to do this is your personal .Renviron file. Again, you should check always confirm the location of this file and make sure it's not a part of any cloud storage or git or GitHub. You can use `usethis::edit_r_environ()` to semi-permanently save your token. Each time you launch an R session this file will run and your token will be visible to you if specifically called with `Sys.getenv("REDCAPSYNC_FIRST_PROJECT")`.

1.  Open the .Renviron file with `usethis::edit_r_environ()`
2.  Add the token like this... `REDCAPSYNC_FIRST_PROJECT = "faKeTokeN"`
3.  Save the file and Close
4.  Restart R Session (Session tab or `.rs.restartR()`).
5.  Confirm with `Sys.getenv("REDCAPSYNC_FIRST_PROJECT")`

```{r, eval=FALSE}
#Install usethis if you don't have it.
#install.packages("usethis") 
usethis::edit_r_environ()
# Now save your token.... (without the comment symbol '#')
# REDCAPSYNC_FIRST_PROJECT = "faKeTokeN"
# Save the file and Close
# Restart R Session (session tab)
# .rs.restartR() # this will also restart R session for you.
Sys.getenv("REDCAPSYNC_FIRST_PROJECT") # now should contain your token
```

The only reference to your token that is ever made or saved in REDCapSync is with its name. For example, any REDCap project object will have the token name at `project$token_name`. In the future, we may set our token in a different way. 

## 2. Setting Your Token using `keyring` package

By default REDCapSync will use keyring = NULL, which is your OS system default and is typically unlocked by default while you are logged in. 

```{r, eval=FALSE}
project <- load_project("TEST_CLASSIC")

project$set_keyring_token() # now enter token in pop-up
# internally the package checks ...
#1. Sys.getenv()
token <- Sys.getenv(project$.internal$token_name)
#2. followed by keyring
token <- keyring::key_get(service = config$keyring.service(),
                          username = project$project_name,
                          keyring = config$keyring())
# you could set with the following; not preferred because token in script
# if you do this set in securely in file that no one can ever see; never github!
keyring::key_set_with_value(service = config$keyring.service(),
                            username = project$project_name,
                            password = "VeryNOTsecureWayToSetYourTOKEN",
                            keyring = config$keyring())
```

You can change default configuration to give you more fine-tuning of keyrings using configuration settings...

```{r, eval=FALSE}
options(redcapsync.config.keyring = "REDCapSync")
# with this kind of method you could define multiple tokens in a private/secret
# .R file which can be sourced to set all tokens in akeyring. Can also be 
# locked and unlocked (see keyring webstite for details)
```

## 3. Setting Your Token for One Session

You can set manually with base R. Unless you specifically set the token `Sys.getenv("REDCAPSYNC_FIRST_PROJECT")` will be blank.

```{r, eval=FALSE}
# Set your token manually
# again having this in a script is not advised but possible
Sys.setenv(REDCAPSYNC_FIRST_PROJECT="a_FaKe_TOkEn") 

# Get your token
Sys.getenv("REDCAPSYNC_FIRST_PROJECT")
#>[1] "a_FaKe_TOkEn"
```

Now the token is set for this R session only. If you restarted R, it would be blank again.

# Testing Your Token (optional)

If you are ever having any issues with your token, you can test your project object with `project$test_token()`.

```{r, eval=FALSE}
project <- load_project("TEST_CLASSIC") # replace project name with yours

project$test_token()
```

# Additional Resources

-   <https://www.dartistics.com/renviron.html>
