Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

API key authentication for REST API's #3013

Merged
merged 5 commits into from
Jan 11, 2023
Merged
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
32 changes: 32 additions & 0 deletions apps/api/R/auth.R
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,22 @@ validate_crypt_pass <- function(username, crypt_pass) {
return(NA)
}

#* Check if the API key exists
#* @param api_key API Key
#* @return user details if apikey exists, else Invalid API Key
#* @author Nihar Sanda
validate_api_key <- function(api_key) {
res <- tbl(global_db_pool, "users") %>%
filter(apikey == api_key) %>%
collect()

if (nrow(res) == 1) {
return(res)
}

return(NA)
}
Comment on lines +48 to +58
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how you're planning on having the users store the API key, but often packages have users put it in a .Renviron file. Then, the validate_api_key can look for the key there by default. An example: https://github.com/ropensci/webchem/blob/18e551609c8f1aa371f83aad1b281540e9df1066/R/chemspider.R#L22


#* Filter to authenticate a user calling the PEcAn API
#* @param req The request
#* @param res The response to be set
Expand Down Expand Up @@ -81,6 +97,22 @@ authenticate_user <- function(req, res) {

}

if(!is.null(req$HTTP_X_API_KEY)) {
key <- req$HTTP_X_API_KEY
# HTTP_X_API_KEY is of the form "api_key"
user <- validate_api_key(key)
userid <- user$id
username <- user$login
print(userid)
print(username)

if(! is.na(userid)){
req$user$userid <- userid
req$user$username <- username
return(plumber::forward())
}
}

res$status <- 401 # Unauthorized
return(list(error="Authentication required"))
}