30 lines
930 B
Python
30 lines
930 B
Python
"""Encrypted, user-bound storage for third-party credentials."""
|
|
import base64
|
|
import hashlib
|
|
import json
|
|
|
|
from cryptography.fernet import Fernet, InvalidToken
|
|
|
|
from app.config import get_settings
|
|
|
|
|
|
def _cipher() -> Fernet:
|
|
key = hashlib.sha256(("f95-session:" + get_settings().secret_key).encode()).digest()
|
|
return Fernet(base64.urlsafe_b64encode(key))
|
|
|
|
|
|
def seal(user_id: int, cookie: str, user_agent: str) -> str:
|
|
data = json.dumps({"user_id": user_id, "cookie": cookie, "user_agent": user_agent})
|
|
return _cipher().encrypt(data.encode()).decode()
|
|
|
|
|
|
def open_session(user_id: int, token: str | None) -> tuple[str, str]:
|
|
if token:
|
|
try:
|
|
data = json.loads(_cipher().decrypt(token.encode()))
|
|
if data["user_id"] == user_id:
|
|
return data["cookie"], data["user_agent"]
|
|
except (InvalidToken, ValueError, KeyError, TypeError):
|
|
pass
|
|
return "", ""
|