Right way to manage same user opening multiple sessions

Hi again @randyzwitch !

Thanks for your explanation and for nudging me in what I think is the right direction, appreciate it.

Sharing below a solution that combines (1) session tokens and (2) st.experimental_singleton in order to expire any old sessions for a given user - whenever that user opens a new session.

Follow-up question: This seems to work locally even across browsers, but would this work when deployed? Am i missing anything that should be obvious? Also if you or anyone else have ideas to improve this logic, it would be great to read them :slight_smile: Thanks again!

Code:

import streamlit as st
import datetime as dt

# Example list of users
USER_LIST = ['Barbara','Christopher']


# Updates the active session for a given user
@st.experimental_singleton
def get_active_session(username):
    return st.session_state.session_id


# App when logged out
if 'session_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.session_id = username + '_' + str(dt.datetime.now())
        get_active_session.clear()
        aux_active_session = get_active_session(st.session_state.user_id)
        st.experimental_rerun()


# App when logged in and session active
elif st.session_state.session_id == get_active_session(st.session_state.user_id):
    st.success('You are currently logged in')
    st.write('Session ID: ',st.session_state.session_id)
    st.button('Useless button')

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


# App when session expired
else:
    st.info('Your session has expired')
    for key in st.session_state.keys():
        del st.session_state[key]
    st.button('Return to homepage')
3 Likes