ForcePilot/backend/package/yuxi/channel/extensions/slack/pairing.py

63 lines
2.4 KiB
Python
Raw Normal View History

import secrets
import time
import logging
logger = logging.getLogger(__name__)
_PAIRING_CODES: dict[str, tuple[str, float]] = {}
_CODE_TTL_SECONDS = 300
class SlackPairing:
id_label = "slackSenderId"
async def generate_code(self, peer_id: str) -> str:
code = f"{secrets.randbelow(1_000_000):06d}"
_PAIRING_CODES[peer_id] = (code, time.monotonic())
logger.info("Slack pairing code generated for peer %s", peer_id)
return code
async def verify_code(self, peer_id: str, code: str) -> bool:
stored = _PAIRING_CODES.get(peer_id)
if stored is None:
return False
stored_code, created_at = stored
if time.monotonic() - created_at > _CODE_TTL_SECONDS:
_PAIRING_CODES.pop(peer_id, None)
logger.info("Slack pairing code expired for peer %s", peer_id)
return False
if not secrets.compare_digest(stored_code, code):
return False
_PAIRING_CODES.pop(peer_id, None)
logger.info("Slack pairing code verified for peer %s", peer_id)
return True
def normalize_allow_entry(self, entry: str) -> str:
stripped = entry.strip()
for prefix in ("slack:", "user:"):
if stripped.lower().startswith(prefix):
stripped = stripped[len(prefix) :].strip()
return stripped.upper()
async def notify_approval(self, config: dict, peer_id: str, account_id: str | None = None) -> None:
logger.info("Slack pairing approved for peer %s (account=%s)", peer_id, account_id or "default")
try:
from yuxi.channel.extensions.slack.config import SlackConfigAdapter
adapter = SlackConfigAdapter()
account = await adapter.resolve_account(account_id or "default", config)
bot_token = account.get("bot_token", "")
if not bot_token:
logger.warning("Cannot notify approval: no bot_token for account %s", account_id)
return
from slack_sdk.web.async_client import AsyncWebClient
client = AsyncWebClient(token=bot_token)
await client.chat_postMessage(
channel=peer_id,
text=":white_check_mark: 您的 DM 访问请求已被批准。现在可以直接向我发送消息了!",
)
except Exception:
logger.warning("Failed to send approval notification to peer %s", peer_id, exc_info=True)