|
| 1 | +from .device import get_device_type, get_os_info |
| 2 | +from .config import Config |
| 3 | +from time import sleep |
| 4 | +from datetime import datetime, timedelta |
| 5 | +import requests |
| 6 | + |
| 7 | + |
| 8 | +def initiate_device_authorization(config: Config) -> dict: |
| 9 | + client_id = Config.oauth_client_id |
| 10 | + device_type = get_device_type() |
| 11 | + device_os = get_os_info() |
| 12 | + url = f"{Config.api_uri}/api/v1/oauth/device-authorization/" |
| 13 | + |
| 14 | + api_response = requests.post( |
| 15 | + url, |
| 16 | + data={ |
| 17 | + "client_id": client_id, |
| 18 | + "device_type": device_type, |
| 19 | + "device_os": device_os, |
| 20 | + "scope": "profile email", |
| 21 | + }, |
| 22 | + ) |
| 23 | + return api_response.json() |
| 24 | + |
| 25 | + |
| 26 | +def poll_for_token(config: Config, device_code: str, interval: int) -> dict: |
| 27 | + client_id = Config.oauth_client_id |
| 28 | + |
| 29 | + continue_polling = True |
| 30 | + polling_end_time = datetime.now() + timedelta(minutes=config.max_polling_time_mins) |
| 31 | + url = f"{Config.api_uri}/oauth/token/" |
| 32 | + while continue_polling: |
| 33 | + if datetime.now() > polling_end_time: |
| 34 | + continue_polling = False |
| 35 | + break |
| 36 | + sleep(interval) |
| 37 | + api_response = requests.post( |
| 38 | + url, |
| 39 | + data={ |
| 40 | + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", |
| 41 | + "device_code": device_code, |
| 42 | + "client_id": client_id, |
| 43 | + }, |
| 44 | + ) |
| 45 | + resp_json = api_response.json() |
| 46 | + if "error" in resp_json and resp_json["error"] == "authorization_pending": |
| 47 | + continue |
| 48 | + else: |
| 49 | + return api_response.json() |
| 50 | + |
| 51 | + return api_response.json() |
| 52 | + |
| 53 | + |
| 54 | +def refresh_tokens(config: Config, refresh_token) -> dict: |
| 55 | + client_id = Config.oauth_client_id |
| 56 | + url = f"{Config.api_uri}/oauth/token/" |
| 57 | + |
| 58 | + api_response = requests.post( |
| 59 | + url, |
| 60 | + data={ |
| 61 | + "grant_type": "refresh_token", |
| 62 | + "client_id": client_id, |
| 63 | + "refresh_token": refresh_token, |
| 64 | + }, |
| 65 | + ) |
| 66 | + |
| 67 | + return api_response.json() |
0 commit comments