-
Notifications
You must be signed in to change notification settings - Fork 39
Expand file tree
/
Copy path_auth.py
More file actions
41 lines (30 loc) · 1.22 KB
/
_auth.py
File metadata and controls
41 lines (30 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
"""Shared Diffbot credential resolution for both the library and the CLI.
The same lookup chain is used everywhere so a single credential works for the
``db`` CLI and any Python script that constructs a client:
1. An explicit token passed to the client / function.
2. The ``DIFFBOT_API_TOKEN`` environment variable.
3. A ``DIFFBOT_API_TOKEN=...`` line in ``~/.diffbot/credentials``.
"""
import os
import pathlib
from typing import Optional
TOKEN_ENV_VAR = "DIFFBOT_API_TOKEN"
CREDENTIALS_PATH = pathlib.Path.home() / ".diffbot" / "credentials"
def _read_credentials_file() -> str:
if not CREDENTIALS_PATH.exists():
return ""
for line in CREDENTIALS_PATH.read_text().splitlines():
line = line.strip()
if line.startswith(f"{TOKEN_ENV_VAR}="):
return line[len(TOKEN_ENV_VAR) + 1:].strip()
return ""
def resolve_token(token: Optional[str] = None) -> str:
"""Resolve a Diffbot API token from the explicit argument, env var, or file.
Returns an empty string if no token can be found.
"""
if token and token.strip():
return token.strip()
env_token = os.environ.get(TOKEN_ENV_VAR, "").strip()
if env_token:
return env_token
return _read_credentials_file()