heic_sync/get_onedrive_token.py

83 lines
2.3 KiB
Python

import msal
import json
import os
import sys
import webbrowser
import time
# OneDrive API configuration
CLIENT_ID = "4765445b-32c6-49b0-83e6-1d93765276ca" # Official OneDrive client ID
AUTHORITY = "https://login.microsoftonline.com/consumers"
SCOPE = [
"Files.ReadWrite",
"User.Read",
"Photos.ReadWrite"
]
def get_access_token():
"""
Get an access token for OneDrive using device code flow
Returns:
dict: Token data if successful, None otherwise
"""
# Create MSAL app
app = msal.PublicClientApplication(
CLIENT_ID,
authority=AUTHORITY
)
try:
# Get device code
flow = app.initiate_device_flow(scopes=SCOPE)
if "user_code" not in flow:
print("Failed to create device flow")
print(json.dumps(flow, indent=2))
return None
print(flow["message"])
# Open browser for authentication
auth_url = flow["verification_uri"]
print(f"Opening browser at {auth_url}...")
webbrowser.open(auth_url)
# Wait for user to complete the flow
result = app.acquire_token_by_device_flow(flow)
if "access_token" in result:
print("Successfully obtained access token!")
# Save both access token and refresh token
return {
"access_token": result["access_token"],
"refresh_token": result.get("refresh_token"),
"expires_in": result.get("expires_in"),
"token_type": result.get("token_type")
}
else:
print("Failed to obtain access token:")
print(json.dumps(result, indent=2))
return None
except Exception as e:
print(f"Error during authentication: {str(e)}")
return None
def save_token(token_data):
"""Save the token data to a file"""
if token_data:
with open('onedrive_token.json', 'w') as f:
json.dump(token_data, f, indent=2)
print("Token data saved to onedrive_token.json")
def main():
"""Main function"""
print("Getting OneDrive access token...")
token_data = get_access_token()
if token_data:
save_token(token_data)
return 0
return 1
if __name__ == "__main__":
sys.exit(main())