48 lines
1.4 KiB
Python
48 lines
1.4 KiB
Python
|
|
from __future__ import annotations
|
||
|
|
|
||
|
|
import logging
|
||
|
|
import secrets
|
||
|
|
import time
|
||
|
|
|
||
|
|
logger = logging.getLogger(__name__)
|
||
|
|
|
||
|
|
|
||
|
|
class QQBotPairing:
|
||
|
|
def __init__(self):
|
||
|
|
self._codes: dict[str, tuple[str, float]] = {}
|
||
|
|
self._code_ttl = 300
|
||
|
|
self._id_label = "QQ OpenID"
|
||
|
|
|
||
|
|
@property
|
||
|
|
def id_label(self) -> str:
|
||
|
|
return self._id_label
|
||
|
|
|
||
|
|
async def generate_code(self, peer_id: str) -> str:
|
||
|
|
code = secrets.token_hex(3).upper()
|
||
|
|
self._codes[peer_id] = (code, time.time())
|
||
|
|
logger.info("Pairing code generated for peer=%s: %s", peer_id, code)
|
||
|
|
return code
|
||
|
|
|
||
|
|
async def verify_code(self, peer_id: str, code: str) -> bool:
|
||
|
|
entry = self._codes.get(peer_id)
|
||
|
|
if entry is None:
|
||
|
|
return False
|
||
|
|
|
||
|
|
stored_code, created_at = entry
|
||
|
|
if time.time() - created_at > self._code_ttl:
|
||
|
|
del self._codes[peer_id]
|
||
|
|
return False
|
||
|
|
|
||
|
|
if stored_code.upper() == code.upper():
|
||
|
|
del self._codes[peer_id]
|
||
|
|
return True
|
||
|
|
|
||
|
|
return False
|
||
|
|
|
||
|
|
async def notify_approval(self, config: dict, peer_id: str, account_id: str | None = None) -> None:
|
||
|
|
logger.info("Pairing approval notification for peer=%s", peer_id)
|
||
|
|
|
||
|
|
def normalize_allow_entry(self, entry: str) -> str:
|
||
|
|
if entry.startswith("qqbot:"):
|
||
|
|
return entry.split(":", 1)[1] if len(entry.split(":", 1)) >= 2 else entry
|
||
|
|
return entry
|