shinyauthr icon indicating copy to clipboard operation
shinyauthr copied to clipboard

Modular implementation of various function menus

Open chuxinyuan opened this issue 10 months ago • 3 comments

As there are more and more function points in the project, it is difficult to maintain them in an app.R file, so I want to modularize each function menu. Can I have an example for reference?

chuxinyuan avatar Mar 15 '25 04:03 chuxinyuan

Sorry I do not understand what you are asking.

PaulC91 avatar Mar 18 '25 10:03 PaulC91

There is a moduleServer() in my project, so I hope there is a mini example, I want to know how the shinyauthr package can be run in a project with modules.

chuxinyuan avatar Mar 18 '25 10:03 chuxinyuan

Use a uiOutput placeholder for your module's UI then use an observer to render it and run the module server function after a successful login has taken place.

library(shiny)

# dataframe that holds usernames, passwords and other user data
user_base <- tibble::tibble(
  user = c("user1", "user2"),
  password = c("pass1", "pass2"),
  permissions = c("admin", "standard"),
  name = c("User One", "User Two")
)

ui <- fluidPage(
  # add logout button UI
  div(class = "pull-right", shinyauthr::logoutUI(id = "logout")),
  # add login panel UI function
  shinyauthr::loginUI(id = "login"),
  # placeholder for your module UI
  uiOutput("module_ui")
)

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

  # call login module supplying data frame, 
  # user and password cols and reactive trigger
  credentials <- shinyauthr::loginServer(
    id = "login",
    data = user_base,
    user_col = user,
    pwd_col = password,
    log_out = reactive(logout_init())
  )

  # call the logout module with reactive trigger to hide/show
  logout_init <- shinyauthr::logoutServer(
    id = "logout",
    active = reactive(credentials()$user_auth)
  )

 # use an observer to render your module's UI and run its server
 # function after a successful a login
  observeEvent(credentials()$user_auth, {
    logged_in <- credentials()$user_auth
    output$module_ui <- renderUI({
      if (logged_in) yourModuleUI("module_id") else NULL
    })
    if (logged_in) yourModuleServer("module_id")
  })
}

PaulC91 avatar Mar 18 '25 14:03 PaulC91