# pages/oauth_callback.py - COMPLETE FIXED VERSION
import streamlit as st
import requests
import os
from datetime import datetime
st.set_page_config(page_title="Authenticating...", page_icon="⏳", layout="centered")
# Get credentials from environment
GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
# Show loading screen
st.markdown("""
""", unsafe_allow_html=True)
# Initial loading message
st.markdown("""
🔐 Authenticating...
Please wait while we log you in with Google.
""", unsafe_allow_html=True)
# Process the OAuth callback
try:
# Get the authorization code from URL
# Try new method first, fallback to old
try:
query_params = st.query_params
is_new_api = True
except AttributeError:
query_params = st.experimental_get_query_params()
is_new_api = False
if "code" in query_params and GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
# Extract code (different format in old vs new)
if is_new_api:
code = query_params.get("code", "")
else:
code_list = query_params.get("code", [])
code = code_list[0] if code_list else ""
if not code:
st.error("❌ No authorization code received")
st.stop()
# Exchange code for token
with st.spinner("Verifying credentials..."):
token_url = "https://oauth2.googleapis.com/token"
data = {
"client_id": GOOGLE_CLIENT_ID,
"client_secret": GOOGLE_CLIENT_SECRET,
"code": code,
"redirect_uri": "https://refat81-social-media-data-extractor-chatbot.hf.space/oauth_callback",
"grant_type": "authorization_code"
}
response = requests.post(token_url, data=data)
tokens = response.json()
if "access_token" in tokens:
# Get user info
with st.spinner("Loading your profile..."):
userinfo_url = "https://www.googleapis.com/oauth2/v3/userinfo"
headers = {"Authorization": f"Bearer {tokens['access_token']}"}
user_response = requests.get(userinfo_url, headers=headers)
user_info = user_response.json()
# Store in session
st.session_state.user_info = user_info
st.session_state.authenticated = True
st.session_state.login_time = datetime.now()
# Clear the loading message and show success
st.empty() # Clear loading message
st.markdown(f"""
✅ Login Successful!
Welcome, {user_info.get('name', 'User')}!
Redirecting to dashboard...
""", unsafe_allow_html=True)
# Auto-redirect to main page
st.markdown("""
If you are not redirected automatically, click here.
""", unsafe_allow_html=True)
else:
st.error("❌ Authentication failed. Please try again.")
if "error" in tokens:
st.write(f"Error: {tokens['error']}")
elif not GOOGLE_CLIENT_ID or not GOOGLE_CLIENT_SECRET:
st.error("""
❌ Server configuration error.
Please contact administrator or check HuggingFace Space secrets.
""")
else:
st.error("❌ No authorization code received. Please try logging in again.")
except Exception as e:
st.error(f"❌ Error: {str(e)}")
st.write("Please try logging in again from the main page.")
# Footer
st.markdown("---")
st.caption("Social Media Data Extractor • Secure OAuth Authentication")