|
1 | 1 | import base64
|
2 | 2 | import functools
|
3 | 3 | import hashlib
|
| 4 | +import json |
4 | 5 | import logging
|
| 6 | +import os |
5 | 7 | import secrets
|
6 | 8 | import threading
|
7 | 9 | import urllib.parse
|
|
10 | 12 | from dataclasses import dataclass
|
11 | 13 | from datetime import datetime, timedelta
|
12 | 14 | from http.server import BaseHTTPRequestHandler, HTTPServer
|
13 |
| -from typing import Any, Dict, List |
| 15 | +from typing import Any, Dict, List, Optional |
14 | 16 |
|
15 | 17 | import requests
|
16 | 18 | import requests.auth
|
@@ -402,3 +404,41 @@ def refresh(self) -> Token:
|
402 | 404 | params,
|
403 | 405 | use_params=self.use_params,
|
404 | 406 | use_header=self.use_header)
|
| 407 | + |
| 408 | + |
| 409 | +class TokenCache(): |
| 410 | + BASE_PATH = "~/.config/databricks-sdk-py/oauth" |
| 411 | + |
| 412 | + def __init__(self, client: OAuthClient) -> None: |
| 413 | + self.client = client |
| 414 | + |
| 415 | + @property |
| 416 | + def filename(self) -> str: |
| 417 | + # Include host, client_id, and scopes in the cache filename to make it unique. |
| 418 | + hash = hashlib.sha256() |
| 419 | + for chunk in [self.client.host, self.client.client_id, ",".join(self.client._scopes), ]: |
| 420 | + hash.update(chunk.encode('utf-8')) |
| 421 | + return os.path.expanduser(os.path.join(self.__class__.BASE_PATH, hash.hexdigest() + ".json")) |
| 422 | + |
| 423 | + def load(self) -> Optional[RefreshableCredentials]: |
| 424 | + """ |
| 425 | + Load credentials from cache file. Return None if the cache file does not exist or is invalid. |
| 426 | + """ |
| 427 | + if not os.path.exists(self.filename): |
| 428 | + return None |
| 429 | + |
| 430 | + try: |
| 431 | + with open(self.filename, 'r') as f: |
| 432 | + raw = json.load(f) |
| 433 | + return RefreshableCredentials.from_dict(self.client, raw) |
| 434 | + except Exception: |
| 435 | + return None |
| 436 | + |
| 437 | + def save(self, credentials: RefreshableCredentials) -> None: |
| 438 | + """ |
| 439 | + Save credentials to cache file. |
| 440 | + """ |
| 441 | + os.makedirs(os.path.dirname(self.filename), exist_ok=True) |
| 442 | + with open(self.filename, 'w') as f: |
| 443 | + json.dump(credentials.as_dict(), f) |
| 444 | + os.chmod(self.filename, 0o600) |
0 commit comments