File size: 6,241 Bytes
14fcd71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import os
import streamlit as st
import requests
import msal

# πŸ€“ Load environment variables (Ensure these are set!)
APPLICATION_ID_KEY = os.getenv('APPLICATION_ID_KEY')
CLIENT_SECRET_KEY = os.getenv('CLIENT_SECRET_KEY')
AUTHORITY_URL = 'https://login.microsoftonline.com/common'  # Use 'common' for multi-tenant apps
REDIRECT_URI = 'http://localhost:8501'  # πŸ‘ˆ Make sure this matches your app's redirect URI

# 🎯 Define the scopes your app will need
SCOPES = ['User.Read', 'Calendars.ReadWrite']

# πŸ› οΈ Initialize the MSAL client
def get_msal_app():
    return msal.ConfidentialClientApplication(
        client_id=APPLICATION_ID_KEY,
        client_credential=CLIENT_SECRET_KEY,
        authority=AUTHORITY_URL
    )

# πŸ” Acquire access token using authorization code
def get_access_token(code):
    client_instance = get_msal_app()
    result = client_instance.acquire_token_by_authorization_code(
        code=code,
        scopes=SCOPES,
        redirect_uri=REDIRECT_URI
    )
    if 'access_token' in result:
        return result['access_token']
    else:
        st.error('Error acquiring token: ' + str(result.get('error_description')))
        st.stop()

# πŸƒβ€β™‚οΈ Main application function
def main():
    st.title("πŸ¦„ Simple Streamlit App with MS Graph API")
    
    # πŸš€ Sidebar navigation
    st.sidebar.title("Navigation")
    menu = st.sidebar.radio("Go to", [
        "1️⃣ Dashboard with Widgets",
        "🏠 Landing Page",
        "πŸ“… Upcoming Events",
        "πŸ“† Schedule",
        "πŸ“ Agenda",
        "πŸ” Event Details",
        "βž• Add Event",
        "πŸ”Ž Filter By"
    ])
    
    # πŸ”‘ Authentication
    if 'access_token' not in st.session_state:
        # πŸ•΅οΈβ€β™‚οΈ Check for authorization code in query parameters
        query_params = st.experimental_get_query_params()
        if 'code' in query_params:
            code = query_params['code'][0]
            st.write('πŸ”‘ Acquiring access token...')
            access_token = get_access_token(code)
            st.session_state['access_token'] = access_token
            st.experimental_rerun()  # Reload the app to clear the code from URL
        else:
            # πŸ“’ Prompt user to log in
            client_instance = get_msal_app()
            authorization_url = client_instance.get_authorization_request_url(
                scopes=SCOPES,
                redirect_uri=REDIRECT_URI
            )
            st.write('πŸ‘‹ Please [click here]({}) to log in and authorize the app.'.format(authorization_url))
            st.stop()
    else:
        # πŸ₯³ User is authenticated, proceed with the app
        access_token = st.session_state['access_token']
        headers = {'Authorization': 'Bearer ' + access_token}
        
        # πŸ€— Greet the user
        response = requests.get('https://graph.microsoft.com/v1.0/me', headers=headers)
        if response.status_code == 200:
            user_info = response.json()
            st.sidebar.write(f"πŸ‘‹ Hello, {user_info['displayName']}!")
        else:
            st.error('Failed to fetch user info.')
            st.write(response.text)
        
        # πŸŽ›οΈ Handle menu options
        if menu == "1️⃣ Dashboard with Widgets":
            st.header("1️⃣ Dashboard with Widgets")
            st.write("Widgets will be displayed here. πŸŽ›οΈ")
            # Add your widgets here
        
        elif menu == "🏠 Landing Page":
            st.header("🏠 Landing Page")
            st.write("Welcome to the app! πŸ₯³")
            # Add landing page content here
        
        elif menu == "πŸ“… Upcoming Events":
            st.header("πŸ“… Upcoming Events")
            events = get_upcoming_events(access_token)
            for event in events:
                st.write(f"πŸ“† {event['subject']} on {event['start']['dateTime']}")
            # Display upcoming events
        
        elif menu == "πŸ“† Schedule":
            st.header("πŸ“† Schedule")
            schedule = get_schedule(access_token)
            st.write(schedule)
            # Display schedule
        
        elif menu == "πŸ“ Agenda":
            st.header("πŸ“ Agenda")
            st.write("Your agenda for today. πŸ“‹")
            # Display agenda
        
        elif menu == "πŸ” Event Details":
            st.header("πŸ” Event Details")
            event_id = st.text_input("Enter Event ID")
            if event_id:
                event_details = get_event_details(access_token, event_id)
                st.write(event_details)
            # Display event details based on ID
        
        elif menu == "βž• Add Event":
            st.header("βž• Add Event")
            event_subject = st.text_input("Event Subject")
            event_start = st.date_input("Event Start Date")
            event_start_time = st.time_input("Event Start Time")
            event_end = st.date_input("Event End Date")
            event_end_time = st.time_input("Event End Time")
            if st.button("Add Event"):
                event_details = {
                    "subject": event_subject,
                    "start": {
                        "dateTime": f"{event_start}T{event_start_time}",
                        "timeZone": "UTC"
                    },
                    "end": {
                        "dateTime": f"{event_end}T{event_end_time}",
                        "timeZone": "UTC"
                    }
                }
                add_event(access_token, event_details)
                st.success("Event added successfully! πŸŽ‰")
            # Form to add new event
        
        elif menu == "πŸ”Ž Filter By":
            st.header("πŸ”Ž Filter Events")
            filter_criteria = st.text_input("Enter filter criteria")
            if filter_criteria:
                filtered_events = filter_events(access_token, filter_criteria)
                for event in filtered_events:
                    st.write(f"πŸ“… {event['subject']} on {event['start']['dateTime']}")
            # Filter events based on criteria
        
        else:
            st.write("Please select a menu option.")

# πŸ“… Function to get upcoming events
def get_upcoming_events(access_token):
    headers = {'Authoriza