File size: 2,508 Bytes
db7b744 21999ba 7822987 db7b744 21999ba db7b744 21999ba db7b744 21999ba db7b744 21999ba db7b744 ced155a db7b744 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import os
from typing import Callable, Any
import streamlit as st
from descope.descope_client import DescopeClient
from descope.exceptions import AuthException
from helpers.activities import restoreUserActivity
import utils as U
from dotenv import load_dotenv
load_dotenv()
DESCOPE_PROJECT_ID = os.environ.get("DESCOPE_PROJECT_ID")
descopeClient = DescopeClient(project_id=DESCOPE_PROJECT_ID)
def runWithAuth(func: Callable[[], Any]):
if "token" not in st.session_state:
if "code" in st.query_params:
code = st.query_params["code"]
st.query_params.clear()
try:
with st.spinner("Authenticating ..."):
jwtResponse = descopeClient.sso.exchange_token(code)
st.session_state["token"] = jwtResponse["sessionToken"].get("jwt")
st.session_state["refreshToken"] = jwtResponse["refreshSessionToken"].get(
"jwt"
)
st.session_state["user"] = jwtResponse["user"]
with st.spinner("Restoring your chats ..."):
restoreUserActivity()
st.rerun()
except AuthException:
st.error("Login failed!")
st.warning("Login to Unlock the Magic ✨", icon=":material/login:")
with st.container(border=False):
if st.button(
"Sign in with Google",
type="primary",
use_container_width=True
):
oauthResponse = descopeClient.oauth.start(
provider="google", return_url=st.context.headers["Origin"]
)
url = oauthResponse["url"]
# Redirect to Google
st.markdown(
f'<meta http-equiv="refresh" content="0; url={url}">',
unsafe_allow_html=True,
)
else:
try:
with st.spinner("Verifying your identity ..."):
jwtResponse = descopeClient.validate_and_refresh_session(
st.session_state.token, st.session_state.refreshToken
)
st.session_state["token"] = jwtResponse["sessionToken"].get("jwt")
userEmail = st.session_state["user"].get("email")
U.pprint(f"{userEmail} successfully authenticated!")
func()
except AuthException:
# Log out user
del st.session_state.token
st.rerun()
|