47 lines
1.2 KiB
Python
47 lines
1.2 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import logging
|
||
|
|
import random
|
||
|
|
import string
|
||
|
|
import time
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
_pairing_codes: dict[str, tuple[str, float]] = {}
|
||
|
|
_pairing_verified: set[str] = set()
|
||
|
|
CODE_TTL = 600
|
||
|
|
|
||
|
|
|
||
|
|
def generate_code(peer_id: str) -> str:
|
||
|
|
code = "".join(random.choices(string.digits, k=6))
|
||
|
|
_pairing_codes[peer_id] = (code, time.time())
|
||
|
|
logger.info("为 %s 生成配对码: %s", peer_id, code)
|
||
|
|
return code
|
||
|
|
|
||
|
|
|
||
|
|
def verify_code(peer_id: str, code: str) -> bool:
|
||
|
|
entry = _pairing_codes.get(peer_id)
|
||
|
|
if entry is None:
|
||
|
|
return False
|
||
|
|
stored_code, created_at = entry
|
||
|
|
if time.time() - created_at > CODE_TTL:
|
||
|
|
del _pairing_codes[peer_id]
|
||
|
|
return False
|
||
|
|
if stored_code == code:
|
||
|
|
del _pairing_codes[peer_id]
|
||
|
|
_pairing_verified.add(peer_id)
|
||
|
|
return True
|
||
|
|
return False
|
||
|
|
|
||
|
|
|
||
|
|
def check_pairing(sender_uid: str, account) -> bool:
|
||
|
|
if hasattr(account, "dm_allow_from"):
|
||
|
|
allow_from = account.dm_allow_from or []
|
||
|
|
if str(sender_uid) in allow_from:
|
||
|
|
return True
|
||
|
|
return sender_uid in _pairing_verified
|
||
|
|
|
||
|
|
|
||
|
|
def normalize_allow_entry(entry: str) -> str:
|
||
|
|
return entry.strip()
|