33 lines
952 B
Python
33 lines
952 B
Python
import secrets
|
|
import time
|
|
|
|
from yuxi.channel.extensions.alipay.constants import (
|
|
ALIPAY_PAIRING_CODE_LENGTH,
|
|
ALIPAY_PAIRING_CODE_TTL_SECONDS,
|
|
)
|
|
|
|
|
|
class AlipayPairing:
|
|
def __init__(self):
|
|
self._codes: dict[str, tuple[str, float]] = {}
|
|
|
|
def generate_code(self, peer_id: str) -> str:
|
|
import random
|
|
|
|
code = "".join(str(random.randint(0, 9)) for _ in range(ALIPAY_PAIRING_CODE_LENGTH))
|
|
self._codes[peer_id] = (code, time.time())
|
|
return code
|
|
|
|
def verify_code(self, peer_id: str, code: str) -> bool:
|
|
entry = self._codes.get(peer_id)
|
|
if not entry:
|
|
return False
|
|
stored_code, created_at = entry
|
|
if time.time() - created_at > ALIPAY_PAIRING_CODE_TTL_SECONDS:
|
|
del self._codes[peer_id]
|
|
return False
|
|
if not secrets.compare_digest(stored_code, code):
|
|
return False
|
|
del self._codes[peer_id]
|
|
return True
|