awacke1 commited on
Commit
0676bbf
·
verified ·
1 Parent(s): a81cb6d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +20 -33
app.py CHANGED
@@ -4,6 +4,7 @@ import requests
4
  import msal
5
  import secrets
6
  import time
 
7
 
8
  # Configuration
9
  APPLICATION_ID = os.getenv('APPLICATION_ID_KEY')
@@ -12,12 +13,6 @@ AUTHORITY = 'https://login.microsoftonline.com/common'
12
  REDIRECT_URI = 'https://huggingface.co/spaces/awacke1/MSGraphAPI'
13
  SCOPES = ['User.Read', 'Calendars.ReadWrite', 'Mail.ReadWrite']
14
 
15
- # Initialize session state
16
- if 'auth_state' not in st.session_state:
17
- st.session_state.auth_state = None
18
- if 'auth_state_time' not in st.session_state:
19
- st.session_state.auth_state_time = None
20
-
21
  # MSAL setup
22
  def get_msal_app():
23
  return msal.ConfidentialClientApplication(
@@ -30,13 +25,15 @@ def get_msal_app():
30
  def generate_auth_url():
31
  msal_app = get_msal_app()
32
  state = secrets.token_urlsafe(32)
33
- st.session_state.auth_state = state
34
- st.session_state.auth_state_time = time.time()
35
- return msal_app.get_authorization_request_url(
36
  scopes=SCOPES,
37
  redirect_uri=REDIRECT_URI,
38
  state=state
39
  )
 
 
 
 
40
 
41
  def get_token_from_code(code):
42
  msal_app = get_msal_app()
@@ -50,16 +47,6 @@ def get_token_from_code(code):
50
  else:
51
  raise Exception(f"Error acquiring token: {result.get('error_description')}")
52
 
53
- def get_token_from_cache():
54
- if 'token_cache' in st.session_state:
55
- msal_app = get_msal_app()
56
- accounts = msal_app.get_accounts()
57
- if accounts:
58
- result = msal_app.acquire_token_silent(SCOPES, account=accounts[0])
59
- if result:
60
- return result
61
- return None
62
-
63
  # API call function
64
  def make_api_call(endpoint, token):
65
  headers = {'Authorization': f'Bearer {token}'}
@@ -76,37 +63,37 @@ def main():
76
 
77
  # Debug information
78
  st.sidebar.write("Debug Info:")
79
- st.sidebar.write(f"Auth State: {st.session_state.auth_state}")
80
- st.sidebar.write(f"Auth State Time: {st.session_state.auth_state_time}")
81
- st.sidebar.write(f"Query Params: {st.query_params}")
82
 
83
- # Check for authentication
84
- token = get_token_from_cache()
85
-
86
- if 'code' in st.query_params:
87
- received_state = st.query_params.get('state')
88
- if received_state != st.session_state.auth_state:
89
- st.error(f"Invalid state parameter. Expected {st.session_state.auth_state}, got {received_state}")
90
  st.error("Please try logging in again.")
91
- st.session_state.clear()
92
  st.rerun()
93
 
94
  try:
95
  token = get_token_from_code(st.query_params['code'])
96
- st.session_state['token_cache'] = token
 
97
  st.success("Successfully authenticated!")
98
  st.rerun()
99
  except Exception as e:
100
  st.error(f"Authentication failed: {str(e)}")
101
- st.session_state.clear()
 
102
 
103
- if not token:
104
  auth_url = generate_auth_url()
105
  st.write("Please log in to continue:")
106
  st.markdown(f"[Login with Microsoft]({auth_url})")
107
  return
108
 
109
  # User is authenticated, show the main app
 
110
  st.sidebar.success("Authenticated successfully!")
111
 
112
  # Display user info
 
4
  import msal
5
  import secrets
6
  import time
7
+ from urllib.parse import urlencode
8
 
9
  # Configuration
10
  APPLICATION_ID = os.getenv('APPLICATION_ID_KEY')
 
13
  REDIRECT_URI = 'https://huggingface.co/spaces/awacke1/MSGraphAPI'
14
  SCOPES = ['User.Read', 'Calendars.ReadWrite', 'Mail.ReadWrite']
15
 
 
 
 
 
 
 
16
  # MSAL setup
17
  def get_msal_app():
18
  return msal.ConfidentialClientApplication(
 
25
  def generate_auth_url():
26
  msal_app = get_msal_app()
27
  state = secrets.token_urlsafe(32)
28
+ auth_url = msal_app.get_authorization_request_url(
 
 
29
  scopes=SCOPES,
30
  redirect_uri=REDIRECT_URI,
31
  state=state
32
  )
33
+ # Store the state in query params
34
+ new_query_params = st.query_params.to_dict()
35
+ new_query_params['auth_state'] = state
36
+ return f"{auth_url}&{urlencode(new_query_params)}"
37
 
38
  def get_token_from_code(code):
39
  msal_app = get_msal_app()
 
47
  else:
48
  raise Exception(f"Error acquiring token: {result.get('error_description')}")
49
 
 
 
 
 
 
 
 
 
 
 
50
  # API call function
51
  def make_api_call(endpoint, token):
52
  headers = {'Authorization': f'Bearer {token}'}
 
63
 
64
  # Debug information
65
  st.sidebar.write("Debug Info:")
66
+ st.sidebar.write(f"Query Params: {st.query_params.to_dict()}")
 
 
67
 
68
+ if 'code' in st.query_params and 'state' in st.query_params:
69
+ received_state = st.query_params['state']
70
+ expected_state = st.query_params.get('auth_state')
71
+
72
+ if received_state != expected_state:
73
+ st.error(f"Invalid state parameter. Expected {expected_state}, got {received_state}")
 
74
  st.error("Please try logging in again.")
75
+ st.query_params.clear()
76
  st.rerun()
77
 
78
  try:
79
  token = get_token_from_code(st.query_params['code'])
80
+ st.session_state['token'] = token
81
+ st.query_params.clear()
82
  st.success("Successfully authenticated!")
83
  st.rerun()
84
  except Exception as e:
85
  st.error(f"Authentication failed: {str(e)}")
86
+ st.query_params.clear()
87
+ st.rerun()
88
 
89
+ if 'token' not in st.session_state:
90
  auth_url = generate_auth_url()
91
  st.write("Please log in to continue:")
92
  st.markdown(f"[Login with Microsoft]({auth_url})")
93
  return
94
 
95
  # User is authenticated, show the main app
96
+ token = st.session_state['token']
97
  st.sidebar.success("Authenticated successfully!")
98
 
99
  # Display user info