Search code examples
javascriptrshinyflexdashboard

R Shiny Flexdashboard - reactive value to see is a user is logged in, the redirect if null?


I have a interesting problem,

I have a flexdashboard that uses firebase auth to log into the app. Part of the login process assigns a reactive value rv$userName which by default is set to NULL.

Once the user successfully logs in, I then assign the reactive value to a value. But now I am trying to create a simple redirect in case the user access part of the app while not logged in.

I am putting this code on the Rmd file above the page that is being rendered and required to be logged in:


library(flexdashboard)
library(shiny)
library(shinyWidgets)
library(shinydashboard)
library(shinyjs)

renderUI({
  observe({
    if(is.null(rv$userName)){
      tags$script(JS("window.location.href = '/SmartAlpha_Screener.Rmd';"))
      }
  })
})

The result is an error: Error: cannot coerce type 'environment' to vector of type 'character'

the location /SmartAlpha_Screener.Rmd is the location of the top of the app and is not the issue as I use it in other js on the app.

Ugh, I am stuck.. anyone know what I am doing wrong?

Cheers, Sody

Edit: I guess the question I am asking is there a easy way to run JS when a new flexdashboard page is loaded with a if statement? I wanted to avoid running the if statement in JS and leave it on the shiny side, for security purposes.


Solution

  • Okay got it working,

    First, I added some JS to handle the redirect.

    Shiny.addCustomMessageHandler('myRedirect', function(u) {
      if (!u) {
        window.location.href = '/SmartAlpha_Screener.Rmd';
        }
    });
    
    

    After that I had to wrap the code in renderUI to keep the code on that page only and not run across the entire site. From there I used shiny's useful session$sendCustomMessage to pass a boolean to JS function. Now if someone access the app using a url and is not logged in, it simple redirects them to the log in page.

    renderUI({
      if(is.null(rv$userName)) {
      observe({
        session$sendCustomMessage("myRedirect", FALSE)
        invalidateLater(1000*60)
        })
      }
    })
    

    and BAM, if you go to a page while not logged in you are directed to the log in page.

    Cheers,

    if you have a better option or way of handling this please share!!