Using streamlit to do 3 legged OAuth

Hi friends,
I am trying to build a Twitter dashboard and I want to do OAuth 3-legged authentication for my app to allow the user to get more access.

This is my code for authentication.

login.py


from tweet_analyzer import config

def authrize():
    CONSUMER_KEY = config.CONSUMER_KEY
    CONSUMER_SECRET = config.CONSUMER_SECRET

    BEARER_TOKEN = config.BEARER_TOKEN

    auth = tweepy.OAuth1UserHandler(CONSUMER_KEY, CONSUMER_SECRET,callback="oob")

    print(auth.get_authorization_url())

    verifier = input("Input PIN: ")
    ACCESS_TOKEN, ACCESS_TOKEN_SECRET = auth.get_access_token(verifier)
    auth.set_access_token(ACCESS_TOKEN,ACCESS_TOKEN_SECRET)
    config.ACCESS_TOKEN = ACCESS_TOKEN
    config.ACCESS_TOKEN_SECRET = ACCESS_TOKEN_SECRET
    return True


And this is my authorization part of app.py(streamlit file). Once the user is authorized, ta_main() should run. But since streamlit runs full code every time some update happens, verifier is null value even before I get the input and authorization fails :frowning:

if 'login' not in st.session_state:
     st.session_state['login']= False
#OAuth part

if st.session_state['login' ] == True:
    ta_main() # main app 
else:
    if st.button("Sign in"):
        logged_in = login.authrize()
        if logged_in:
            print("hi")
            st.session_state['login'] = True

I could not find a way to stop setting ACCESS TOKENS before verifier input is receieved. Anybody have any idea what can be done :frowning:

Hi @Soumya_Somasundaran, welcome to the Streamlit community!

It looks like you’re halfway there. If you want to make sure a piece of code only runs once, you can use st.experimental_singleton and/or st.experimental_memo. This will keep the values from being overwritten, which will allow you to save the token and authenticate.

Best,
Randy

1 Like