Auto user session timeout using st.fragment

Hi Everyone,

I am new to streamlit and currently trying to learn some of the common functionalities. One of the things that I am currently stuck on is how to perform auto session timeout or logout inactive users.

I went through various posts in streamlit discussion board but was not able to make the code work.
Basically, I want users who are inactive for some particular time interval to be auto logged off. Then I came across “st.fragment” and thought of using it as a timer to check for user activity.

My code is working fine as per my requirement (at least as per my initial testing) but I am not sure if this is the right approach and whether using “st.fragment” is the correct way to implement the timeout functionality. Please let me know your views on this. Any input with regards to below code or session timeout in general is welcome.

Thanks.

Below is my code-

import streamlit as st import time

Example list of users

USER_LIST = [‘Barbara’,‘Christopher’]

@st.fragment(run_every=“30s”)
def auto_function():
if time.time() - st.session_state.last_user_activity > 30:
for key in st.session_state.keys():
del st.session_state[key]
st.logout()

App when logged out

if ‘user_id’ not in st.session_state:
st.warning(‘You are currently logged out’)

#Login form
with st.form('Login form'):
    username = st.text_input('Username (try "Barbara" or "Christopher")')
    sign_in = st.form_submit_button('Sign In')
if sign_in and username in USER_LIST:
    st.session_state.user_id = username
    st.session_state.last_user_activity = time.time()
    print(st.session_state.user_id)
    st.rerun()

elif st.session_state.user_id in USER_LIST:
st.success(‘You are currently logged in’)
st.session_state.last_user_activity = time.time()
auto_function()

#Do something here
activity=st.button('I am Active')
if activity:
    st.session_state.last_user_activity = time.time()



# Logout button
if st.button('Logout'):
    for key in st.session_state.keys():
        del st.session_state[key]
    st.logout()