|
| 1 | +"""File-based JSON token storage. |
| 2 | +
|
| 3 | +Stores all tokens in a single JSON file. Suitable for development |
| 4 | +and single-server deployments. Not recommended for high-concurrency |
| 5 | +production use. |
| 6 | +""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import json |
| 11 | +import os |
| 12 | +from typing import Any, Dict, Optional |
| 13 | + |
| 14 | +from allow2_service.models.oauth_tokens import OAuthTokens |
| 15 | +from allow2_service.token_storage import TokenStorageInterface |
| 16 | + |
| 17 | + |
| 18 | +class FileTokenStorage(TokenStorageInterface): |
| 19 | + """File-based JSON token storage. |
| 20 | +
|
| 21 | + Stores all tokens in a single JSON file with ``chmod 0600`` |
| 22 | + for security. |
| 23 | +
|
| 24 | + Args: |
| 25 | + file_path: Path to the JSON storage file. |
| 26 | + """ |
| 27 | + |
| 28 | + def __init__(self, file_path: str) -> None: |
| 29 | + self._file_path = file_path |
| 30 | + self._data: Optional[Dict[str, Any]] = None |
| 31 | + |
| 32 | + def store(self, user_id: str, tokens: OAuthTokens) -> None: |
| 33 | + """Store tokens for a user.""" |
| 34 | + data = self._load_all() |
| 35 | + data[user_id] = tokens.to_dict() |
| 36 | + self._save_all(data) |
| 37 | + |
| 38 | + def retrieve(self, user_id: str) -> Optional[OAuthTokens]: |
| 39 | + """Retrieve tokens for a user, or None if none stored.""" |
| 40 | + data = self._load_all() |
| 41 | + |
| 42 | + if user_id not in data: |
| 43 | + return None |
| 44 | + |
| 45 | + return OAuthTokens.from_dict(data[user_id]) |
| 46 | + |
| 47 | + def delete(self, user_id: str) -> None: |
| 48 | + """Delete tokens for a user.""" |
| 49 | + data = self._load_all() |
| 50 | + data.pop(user_id, None) |
| 51 | + self._save_all(data) |
| 52 | + |
| 53 | + def exists(self, user_id: str) -> bool: |
| 54 | + """Check whether tokens exist for a user.""" |
| 55 | + data = self._load_all() |
| 56 | + return user_id in data |
| 57 | + |
| 58 | + def _load_all(self) -> Dict[str, Any]: |
| 59 | + """Load all tokens from disk.""" |
| 60 | + if self._data is not None: |
| 61 | + return self._data |
| 62 | + |
| 63 | + if not os.path.exists(self._file_path): |
| 64 | + self._data = {} |
| 65 | + return self._data |
| 66 | + |
| 67 | + try: |
| 68 | + with open(self._file_path, "r", encoding="utf-8") as f: |
| 69 | + self._data = json.load(f) |
| 70 | + except (json.JSONDecodeError, OSError): |
| 71 | + self._data = {} |
| 72 | + |
| 73 | + return self._data |
| 74 | + |
| 75 | + def _save_all(self, data: Dict[str, Any]) -> None: |
| 76 | + """Persist all tokens to disk.""" |
| 77 | + self._data = data |
| 78 | + |
| 79 | + dir_path = os.path.dirname(self._file_path) |
| 80 | + if dir_path and not os.path.isdir(dir_path): |
| 81 | + os.makedirs(dir_path, mode=0o700, exist_ok=True) |
| 82 | + |
| 83 | + with open(self._file_path, "w", encoding="utf-8") as f: |
| 84 | + json.dump(data, f, indent=2) |
| 85 | + |
| 86 | + try: |
| 87 | + os.chmod(self._file_path, 0o600) |
| 88 | + except OSError: |
| 89 | + pass # chmod may not be available on all platforms |
0 commit comments