Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import msal
|
3 |
+
import requests
|
4 |
+
from fastapi import FastAPI, HTTPException, Request
|
5 |
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
6 |
+
from dotenv import load_dotenv
|
7 |
+
|
8 |
+
load_dotenv()
|
9 |
+
|
10 |
+
# Configuration
|
11 |
+
CLIENT_ID = os.getenv('CLIENT_ID_2')
|
12 |
+
CLIENT_SECRET = os.getenv('CLIENT_SECRET_2')
|
13 |
+
TENANT_ID = os.getenv('TENANT_ID')
|
14 |
+
AUTHORITY = f"https://login.microsoftonline.com/common"
|
15 |
+
REDIRECT_URI = 'http://localhost:8000/getAToken'
|
16 |
+
SCOPES = ['Mail.Read']
|
17 |
+
|
18 |
+
app = FastAPI()
|
19 |
+
|
20 |
+
|
21 |
+
@app.get("/")
|
22 |
+
def read_root(request: Request):
|
23 |
+
# Generate the authorization URL
|
24 |
+
app_instance = msal.ConfidentialClientApplication(
|
25 |
+
CLIENT_ID,
|
26 |
+
CLIENT_SECRET,
|
27 |
+
authority=AUTHORITY
|
28 |
+
)
|
29 |
+
auth_url = app_instance.get_authorization_request_url(SCOPES, redirect_uri=REDIRECT_URI)
|
30 |
+
return {"auth_url":auth_url}
|
31 |
+
|
32 |
+
@app.get("/getAToken")
|
33 |
+
def get_a_token(request: Request, code: str):
|
34 |
+
app_instance = msal.ConfidentialClientApplication(
|
35 |
+
CLIENT_ID,
|
36 |
+
CLIENT_SECRET,
|
37 |
+
authority=AUTHORITY
|
38 |
+
)
|
39 |
+
|
40 |
+
# Exchange the authorization code for an access token
|
41 |
+
result = app_instance.acquire_token_by_authorization_code(code, SCOPES, redirect_uri=REDIRECT_URI)
|
42 |
+
print(result)
|
43 |
+
if "access_token" in result:
|
44 |
+
access_token = result['access_token']
|
45 |
+
print(access_token)
|
46 |
+
if not access_token:
|
47 |
+
return {"Access Token Not found !!"}
|
48 |
+
|
49 |
+
return {"access_token":access_token}
|