How can I hide/show the Flexdashboard page based on the user?

190 views Asked by At

I created a Flexdashboard with two tabs. I'm using shinymanager package for authentication. In the shinymanager credentials, I created two users: "admin" and "manager." Now I want the admin user to have access to both tabs and the manager to only TAB A. 

Here is my code:

---
title: "Flexdashboard"
output: flexdashboard::flex_dashboard
runtime: shiny
---

```{css}
.panel-auth {
  position: fixed;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFF;
  opacity: 1;
  z-index: 99997;
  overflow-x: hidden;
  overflow-y: scroll;
}
```



```{r setup, include=FALSE}
library(flexdashboard)
library(shiny)
library(shinymanager)

credentials <- data.frame(
  user = c("admin", "manager"),
  password = c("1234", "1234"),
  stringsAsFactors = FALSE
)
```

```{r}
auth_ui(id = "auth")
auth <- callModule(
    module = auth_server,
    id = "auth",
    check_credentials = check_credentials(credentials))

user_role <- "manager"
r_show_hide <- reactive({
  if(user_role %in% auth$user) {
      "hidden"
  } else {
      "show" 
  }
})

```


TAB A
=============================

### Chart


TAB B {.`r isolate(r_show_hide())`}
===============================

### Chart
1

There are 1 answers

0
thothal On

I think that your approach cannot work by design, as the rendering happens before any user inputs are generated.

Having said that, I would simply use some JavaScript to hide the corresponding navbar items:

---
title: "Flexdashboard"
output: flexdashboard::flex_dashboard
runtime: shiny
---

```{css}
.panel-auth {
  position: fixed;
  top:0;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFF;
  opacity: 1;
  z-index: 99997;
  overflow-x: hidden;
  overflow-y: scroll;
}
```

```{r setup, include = FALSE}
library(flexdashboard)
library(shiny)
library(shinymanager)

credentials <- data.frame(
   user = c("admin", "manager"),
   password = c("1234", "1234"),
   stringsAsFactors = FALSE
)
```

```{js}
Shiny.addCustomMessageHandler('hide-tabs', function(tabs) {
   /* for whatever reason Shiny does not box single values 
      despite the output of `shiny:::toJSON(c("TAB A"))`.
      Thus, make sure that tabs is always an array
   */
   if (!Array.isArray(tabs)) {
      tabs = [tabs]; 
   }
   const $sel = $('.nav-item > a').filter(function() {
      return(tabs.includes($(this).text()));
   });
   $sel.addClass('hidden');
})
```


```{r}
auth_ui(id = "auth")
auth <- callModule(
   module = auth_server,
   id = "auth",
   check_credentials = check_credentials(credentials))

observeEvent(auth$user, {
   if (auth$user == "manager") {
      session$sendCustomMessage("hide-tabs", c("TAB B"))
   }
})
```


TAB A
=============================
   
### Chart on TAB A

```{r}
```

   
   
TAB B
===============================
   
### Chart on TAB B
```{r}
```