如何在R Shiny会话中留存并获取当前登录用户信息?
解决Shiny + shinymanager登录后获取会话用户信息的问题
首先修正基础语法错误
你当前创建credentials数据框的语法有误,向量组合需用c()而非直接括号,修正后:
credentials <- data.frame( user = c("sample_user", "sample_user_1"), password = c("password1", "password2"), admin = c(TRUE, FALSE), stringsAsFactors = FALSE # 避免因子类型导致的认证异常 )
正确获取登录用户信息的方法
shinymanager不会将用户信息存入session$user或session$userData,而是通过secure_server()返回的**reactive对象res_auth**提供当前会话的用户数据。修正你的server代码如下:
res_auth <- secure_server( check_credentials = check_credentials(credentials) ) # 输出完整的当前用户信息 output$auth_output <- renderPrint({ req(res_auth()) # 确保用户完成登录后再读取数据 res_auth() # 返回包含user、password、admin的列表 }) # 提取单个字段示例 output$current_username <- renderText({ req(res_auth()) paste("当前登录账号:", res_auth()$user) }) output$current_admin_status <- renderText({ req(res_auth()) paste("管理员权限:", ifelse(res_auth()$admin, "开启", "关闭")) })
其他场景使用用户信息
如果需要在server的其他reactive/observer逻辑中使用用户信息,同样依赖res_auth()触发:
observeEvent(res_auth(), { user_info <- res_auth() # 可添加用户登录后的自定义逻辑,比如记录登录日志、加载用户专属数据等 message(paste0("用户 ", user_info$user, " 于 ", Sys.time(), " 登录系统")) })
内容的提问来源于stack exchange,提问作者liam6666
相关产品推荐
相关产品推荐

