1 | initial version |
To use shinymanager with passwords encrypted and saved in a PostgreSQL database, you need to follow these steps:
Here is an example code to illustrate how to do this:
```{r} library(shiny) library(shinymanager) library(RPostgreSQL) library(bcrypt)
salt <- "$2a$12$WYjCTiJBnIDomRyf78QySO"
pass1 <- bcrypt("password1", salt = salt) pass2 <- bcrypt("password2", salt = salt) pass3 <- bcrypt("password3", salt = salt)
con <- dbConnect(PostgreSQL(), host = "localhost", user = "username", password = "password", dbname = "database")
dbSendQuery(con, "CREATE TABLE users (username char(32), password char(60))")
dbSendQuery(con, paste0("INSERT INTO users VALUES ('user1', '", pass1, "');")) dbSendQuery(con, paste0("INSERT INTO users VALUES ('user2', '", pass2, "');")) dbSendQuery(con, paste0("INSERT INTO users VALUES ('user3', '", pass3, "');"))
auth <- function(username, password) { # Get the encrypted password from the PostgreSQL database query <- paste0("SELECT password FROM users WHERE username='", username, "'") result <- dbGetQuery(con, query) encrypted_password <- result[[1]]
# Compare the input password with the encrypted password if (!is.null(encryptedpassword) && bcrypt::bcryptverify(password, encrypted_password)) { return(TRUE) } else { return(FALSE) } }
ui <- fluidPage( headerPanel("Protected page"), mainPanel( verbatimTextOutput("auth_result") ) )
server <- function(input, output, session) {
# Call the shinymanager authentication function resauth <- secureapp(ui, server, authentication = shinymanager::authenticator(auth))
# Print the authentication result output$authresult <- renderText({ if (resauth == TRUE) { "Authentication successful." } else { "Authentication failed." } }) }
shinyApp(ui, server) ```
In this code, the passwords are encrypted using the bcrypt package with a fixed salt. The encrypted passwords are then inserted into a PostgreSQL table called "users". The auth function queries the "users" table to retrieve the encrypted password for the given username, and then compares the input password with the encrypted password using the bcrypt::bcryptverify function. The shinymanager::authenticator function is used to authenticate users based on the auth function. Finally, the secureapp function is used to specify that authentication is required to access the UI.