Refat81 commited on
Commit
6a1d8d6
Β·
verified Β·
1 Parent(s): 8ecd1b3

Update pages/oauth_callback.py

Browse files
Files changed (1) hide show
  1. pages/oauth_callback.py +89 -49
pages/oauth_callback.py CHANGED
@@ -1,4 +1,4 @@
1
- # pages/oauth_callback.py - WORKING VERSION
2
  import streamlit as st
3
  import requests
4
  import os
@@ -6,64 +6,104 @@ from datetime import datetime
6
 
7
  st.set_page_config(page_title="Authenticating...", page_icon="⏳")
8
 
9
- # Get Google credentials from environment
10
  GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
11
  GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
12
 
13
- st.title("πŸ” Authenticating...")
14
- st.write("Please wait while we log you in with Google.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
- # Get the authorization code from URL
17
  try:
18
- query_params = st.experimental_get_query_params()
 
 
 
 
 
19
 
20
- if "code" in query_params:
21
- code = query_params["code"][0]
 
 
 
 
 
 
 
22
 
23
- with st.spinner("Exchanging code for token..."):
24
- # Exchange code for access token
25
- token_url = "https://oauth2.googleapis.com/token"
26
- data = {
27
- "client_id": GOOGLE_CLIENT_ID,
28
- "client_secret": GOOGLE_CLIENT_SECRET,
29
- "code": code,
30
- "redirect_uri": "https://refat81-social-media-data-extractor-chatbot.hf.space/oauth_callback",
31
- "grant_type": "authorization_code"
32
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
 
34
- response = requests.post(token_url, data=data)
35
- tokens = response.json()
36
 
37
- if "access_token" in tokens:
38
- # Get user info from Google
39
- userinfo_url = "https://www.googleapis.com/oauth2/v3/userinfo"
40
- headers = {"Authorization": f"Bearer {tokens['access_token']}"}
41
- user_response = requests.get(userinfo_url, headers=headers)
42
- user_info = user_response.json()
43
-
44
- # Store user info in session
45
- st.session_state.user_info = user_info
46
- st.session_state.authenticated = True
47
- st.session_state.login_time = datetime.now()
48
-
49
- st.success("βœ… Login successful!")
50
- st.write(f"Welcome, {user_info.get('name', 'User')}!")
51
-
52
- # Redirect to main app
53
- st.markdown("""
54
- <script>
55
- setTimeout(function() {
56
- window.location.href = "/";
57
- }, 2000);
58
- </script>
59
- """, unsafe_allow_html=True)
60
-
61
- else:
62
- st.error("❌ Authentication failed")
63
- st.write("Error details:", tokens)
64
  else:
65
- st.error("No authorization code received")
66
 
67
  except Exception as e:
68
- st.error(f"Error during authentication: {str(e)}")
69
  st.write("Please try logging in again.")
 
1
+ # pages/oauth_callback.py - UPDATED FOR Streamlit 1.28+
2
  import streamlit as st
3
  import requests
4
  import os
 
6
 
7
  st.set_page_config(page_title="Authenticating...", page_icon="⏳")
8
 
9
+ # Get credentials from environment
10
  GOOGLE_CLIENT_ID = os.getenv("GOOGLE_CLIENT_ID")
11
  GOOGLE_CLIENT_SECRET = os.getenv("GOOGLE_CLIENT_SECRET")
12
 
13
+ # Show loading screen
14
+ st.markdown("""
15
+ <style>
16
+ .spinner {
17
+ border: 4px solid #f3f3f3;
18
+ border-top: 4px solid #4285F4;
19
+ border-radius: 50%;
20
+ width: 40px;
21
+ height: 40px;
22
+ animation: spin 2s linear infinite;
23
+ margin: 20px auto;
24
+ }
25
+ @keyframes spin {
26
+ 0% { transform: rotate(0deg); }
27
+ 100% { transform: rotate(360deg); }
28
+ }
29
+ </style>
30
+ <div style="text-align: center; padding: 50px;">
31
+ <h1>πŸ” Authenticating...</h1>
32
+ <p>Please wait while we log you in with Google.</p>
33
+ <div class="spinner"></div>
34
+ </div>
35
+ """, unsafe_allow_html=True)
36
 
37
+ # Process the OAuth callback
38
  try:
39
+ # Get the authorization code from URL - USING NEW METHOD
40
+ # Try new method first, fallback to old
41
+ try:
42
+ query_params = st.query_params
43
+ except AttributeError:
44
+ query_params = st.experimental_get_query_params()
45
 
46
+ if "code" in query_params and GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET:
47
+ # Extract code (different format in old vs new)
48
+ if isinstance(query_params, dict) and "get" in dir(query_params):
49
+ # New method returns dict
50
+ code = query_params.get("code", "")
51
+ else:
52
+ # Old method returns dict with lists
53
+ code_list = query_params.get("code", [])
54
+ code = code_list[0] if code_list else ""
55
 
56
+ if not code:
57
+ st.error("❌ No authorization code received")
58
+ st.stop()
59
+
60
+ # Exchange code for token
61
+ token_url = "https://oauth2.googleapis.com/token"
62
+ data = {
63
+ "client_id": GOOGLE_CLIENT_ID,
64
+ "client_secret": GOOGLE_CLIENT_SECRET,
65
+ "code": code,
66
+ "redirect_uri": "https://refat81-social-media-data-extractor-chatbot.hf.space/oauth_callback",
67
+ "grant_type": "authorization_code"
68
+ }
69
+
70
+ response = requests.post(token_url, data=data)
71
+ tokens = response.json()
72
+
73
+ if "access_token" in tokens:
74
+ # Get user info
75
+ userinfo_url = "https://www.googleapis.com/oauth2/v3/userinfo"
76
+ headers = {"Authorization": f"Bearer {tokens['access_token']}"}
77
+ user_response = requests.get(userinfo_url, headers=headers)
78
+ user_info = user_response.json()
79
+
80
+ # Store in session
81
+ st.session_state.user_info = user_info
82
+ st.session_state.authenticated = True
83
+ st.session_state.login_time = datetime.now()
84
 
85
+ # Show success message
86
+ st.success(f"βœ… Login successful! Welcome, {user_info.get('name', 'User')}!")
87
 
88
+ # Auto-redirect to main page
89
+ st.markdown("""
90
+ <script>
91
+ setTimeout(function() {
92
+ window.location.href = "/";
93
+ }, 2000);
94
+ </script>
95
+ """, unsafe_allow_html=True)
96
+
97
+ else:
98
+ st.error("❌ Authentication failed. Please try again.")
99
+ st.write("Error details:", tokens)
100
+
101
+ elif not GOOGLE_CLIENT_ID or not GOOGLE_CLIENT_SECRET:
102
+ st.error("❌ Server configuration error. Contact administrator.")
103
+
 
 
 
 
 
 
 
 
 
 
 
104
  else:
105
+ st.error("❌ No authorization code received. Please try logging in again.")
106
 
107
  except Exception as e:
108
+ st.error(f"❌ Error: {str(e)}")
109
  st.write("Please try logging in again.")