outlook-oauth-hack/refresh_token.py

42 lines
1.1 KiB
Python
Raw Permalink Normal View History

2024-04-05 18:13:16 -04:00
#! /usr/bin/env python3
from msal import ConfidentialClientApplication, SerializableTokenCache
import config
import sys
2024-04-05 20:16:31 -04:00
import os
import time
2024-04-05 22:11:51 -04:00
print_access_token = True
2024-04-05 18:47:33 -04:00
if len(sys.argv) > 1:
profile = sys.argv[1]
else:
sys.exit("Please provide a profile name as the first argument.")
2024-04-05 18:47:33 -04:00
profile_config = config.get_config(profile)
# We use the cache to extract the refresh token
cache = SerializableTokenCache()
2024-04-05 18:47:33 -04:00
app = ConfidentialClientApplication(profile_config.ClientId, client_credential=profile_config.ClientSecret, token_cache=cache, authority=profile_config.Authority)
2024-04-05 20:16:31 -04:00
2024-04-05 22:11:51 -04:00
token_cache = config.get_cache(profile_config)
if not token_cache:
2024-04-05 21:34:10 -04:00
sys.exit("Please get the initial token by running `o365-get-token` first.")
2024-04-05 21:34:10 -04:00
st = os.stat(profile_config.CacheFile)
if (time.time()-st.st_mtime) < token_cache["expires_in"]:
print(token_cache["access_token"])
sys.exit(0)
2024-04-05 21:34:10 -04:00
token = app.acquire_token_by_refresh_token(token_cache["refresh_token"],profile_config.Scopes)
if 'error' in token:
print(token)
sys.exit("Failed to get access token")
2024-04-05 22:11:51 -04:00
config.write_cache(profile_config, token)
if print_access_token:
print(token['access_token'])