datastorm-open / shinymanager

Simple and secure authentification mechanism for single shiny applications.
https://datastorm-open.github.io/shinymanager/
379 stars 79 forks source link

auto-populate username field #169

Closed apulvino closed 5 months ago

apulvino commented 12 months ago

I have a button ready for Guest Login at the top of my shinymanager page. I would like for users to be able to click it and have it auto-populate the username field with "guest". Is there a straightforward way for me to solve this issue?

Thanks so much ahead!

pvictor commented 11 months ago

Hi, I imagine you can do something like that :

# define credentials
credentials <- data.frame(
  user = "user",
  password = "123",
  role = "user"
)

library(shiny)
library(shinymanager)

# UI ----------------------------------------------------------------------

ui <- fluidPage(
  tags$h2("My secure application"),
  verbatimTextOutput("auth_output")
)

# Wrap your UI with secure_app
ui <- secure_app(
  ui = ui,
  tags_bottom = tagList(
    tags$div(
      style = "text-align: center; margin-bottom: 15px;",
      "OR"
    ),
    actionButton(
      inputId = "visitor", 
      label = "Connect as guest",
      width = "100%"
    )
  )
)

# Server ------------------------------------------------------------------

server <- function(input, output, session) {

  # call the server part
  # check_credentials returns a function to authenticate users
  res_auth <- secure_server(
    check_credentials = check_credentials(credentials)
  )

  # bypass auth module if guest button is clicked
  observeEvent(input$visitor, {
    token <- shinymanager:::.tok$generate("visitor")
    shinymanager:::.tok$add(token, list(user = "visitor", role = "guest"))
    shinymanager:::addAuthToQuery(session, token, "en")
    session$reload()
  })

  output$auth_output <- renderPrint({
    reactiveValuesToList(res_auth)
  })

  # your classic server logic

}

# App ---------------------------------------------------------------------

shinyApp(ui, server)

But note that this is experimental and haven't been fully tested.