28 lines
795 B
Python
28 lines
795 B
Python
|
|
"""Bearer-token helpers shared by accounts.py/boxes.py.
|
||
|
|
|
||
|
|
Tokens are minted as ``"<row-id>.<secret>"`` so authenticating one is an
|
||
|
|
O(1) primary-key lookup followed by a single hash comparison, rather than
|
||
|
|
scanning every row and hashing each one looking for a match.
|
||
|
|
"""
|
||
|
|
|
||
|
|
import secrets
|
||
|
|
|
||
|
|
|
||
|
|
def generate_secret() -> str:
|
||
|
|
return secrets.token_urlsafe(32)
|
||
|
|
|
||
|
|
|
||
|
|
def issue(row_id: str) -> tuple[str, str]:
|
||
|
|
"""Return ``(bearer_token_to_hand_out, secret_to_hash_and_store)``."""
|
||
|
|
secret = generate_secret()
|
||
|
|
return f"{row_id}.{secret}", secret
|
||
|
|
|
||
|
|
|
||
|
|
def split(token: str) -> tuple[str, str] | None:
|
||
|
|
if not isinstance(token, str) or "." not in token:
|
||
|
|
return None
|
||
|
|
row_id, _, secret = token.partition(".")
|
||
|
|
if not row_id or not secret:
|
||
|
|
return None
|
||
|
|
return row_id, secret
|