37 lines
1.0 KiB
Python
37 lines
1.0 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import secrets
|
||
|
|
import time
|
||
|
|
|
||
|
|
|
||
|
|
class LazadaPairingStore:
|
||
|
|
def __init__(self, code_ttl: int = 300):
|
||
|
|
self._codes: dict[str, tuple[str, float]] = {}
|
||
|
|
self._ttl = code_ttl
|
||
|
|
|
||
|
|
async def generate(self, account_id: str) -> str:
|
||
|
|
code = secrets.token_hex(3).upper()
|
||
|
|
self._codes[code] = (account_id, time.time())
|
||
|
|
self._evict_expired()
|
||
|
|
return code
|
||
|
|
|
||
|
|
async def verify(self, account_id: str, code: str) -> bool:
|
||
|
|
self._evict_expired()
|
||
|
|
entry = self._codes.get(code)
|
||
|
|
if entry is None:
|
||
|
|
return False
|
||
|
|
stored_id, _ = entry
|
||
|
|
if stored_id != account_id:
|
||
|
|
return False
|
||
|
|
del self._codes[code]
|
||
|
|
return True
|
||
|
|
|
||
|
|
def revoke(self, code: str) -> None:
|
||
|
|
self._codes.pop(code, None)
|
||
|
|
|
||
|
|
def _evict_expired(self) -> None:
|
||
|
|
now = time.time()
|
||
|
|
expired = [k for k, (_, t) in self._codes.items() if now - t > self._ttl]
|
||
|
|
for k in expired:
|
||
|
|
del self._codes[k]
|