Spaces:
Sleeping
Sleeping
File size: 6,106 Bytes
aa7b713 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | """
utils.py β Shared helpers: hash gen, initData verification, bcrypt, sessions.
All config imported from config.py β no os.getenv() here.
"""
import hashlib
import hmac
import json
import secrets
import urllib.parse
from datetime import datetime, timedelta
import bcrypt
import asyncio
import base64
import os
import httpx
import config
class ImgBBUploader:
"""Async uploader for ImgBB using direct API calls."""
def __init__(self, api_key: str):
self.api_key = api_key
self.upload_url = "https://api.imgbb.com/1/upload"
async def upload_from_file(self, file_path: str, name: str = "") -> dict:
"""
Upload an image from a file path.
Args:
file_path: Path to the image file
name: Optional custom name for the image
Returns:
Dictionary containing upload response with URL
"""
with open(file_path, "rb") as f:
image_data = f.read()
return await self._upload(image_data, name)
async def upload_from_bytes(self, image_bytes: bytes, name: str = "") -> dict:
"""
Upload an image from bytes.
Args:
image_bytes: Image data as bytes
name: Optional custom name for the image
Returns:
Dictionary containing upload response with URL
"""
return await self._upload(image_bytes, name)
async def _upload(self, image_data: bytes, name: str = "") -> dict:
"""
Internal method to perform the upload.
"""
encoded_image = base64.b64encode(image_data).decode('utf-8')
async with httpx.AsyncClient() as client:
payload = {
"key": self.api_key,
"image": encoded_image,
}
if name:
payload["name"] = name
response = await client.post(self.upload_url, data=payload)
response.raise_for_status()
result = response.json()
if not result.get("success"):
raise Exception(f"Upload failed: {result.get('error', {}).get('message', 'Unknown error')}")
return result
def get_image_url(self, upload_response: dict) -> str:
"""Extract the image URL from the upload response."""
return upload_response["data"]["url"]
def get_delete_url(self, upload_response: dict) -> str:
"""Extract the delete URL from the upload response."""
return upload_response["data"]["delete_url"]
def get_display_url(self, upload_response: dict) -> str:
"""Extract the display URL from the upload response."""
return upload_response["data"]["display_url"]
# ββ Hash Generation ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def generate_hash() -> str:
"""16-char URL-safe token (~96 bits entropy)."""
return secrets.token_urlsafe(12)[:16]
def generate_session_token() -> str:
"""64-char hex admin session token."""
return secrets.token_hex(32)
# ββ Telegram initData Verification ββββββββββββββββββββββββββββββββββββββββββββ
def verify_init_data(init_data_raw: str) -> bool:
"""
Verify Telegram WebApp initData via HMAC-SHA256.
Spec: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app
"""
if not init_data_raw or not config.BOT_TOKEN:
return False
try:
parsed = dict(urllib.parse.parse_qsl(init_data_raw, keep_blank_values=True))
received_hash = parsed.pop("hash", None)
if not received_hash:
return False
data_check_string = "\n".join(f"{k}={v}" for k, v in sorted(parsed.items()))
secret_key = hmac.new(b"WebAppData", config.BOT_TOKEN.encode(), hashlib.sha256).digest()
computed = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
return hmac.compare_digest(computed, received_hash)
except Exception:
return False
def extract_user_from_init_data(init_data_raw: str) -> dict | None:
if not verify_init_data(init_data_raw):
return None
try:
parsed = dict(urllib.parse.parse_qsl(init_data_raw, keep_blank_values=True))
user_json = parsed.get("user")
if not user_json:
return None
return json.loads(user_json)
except Exception:
return None
def extract_user_id(init_data_raw: str) -> int | None:
user = extract_user_from_init_data(init_data_raw)
if user:
return int(user.get("id", 0)) or None
return None
def is_owner_initdata(init_data_raw: str) -> bool:
"""Return True if verified initData belongs to any configured owner."""
uid = extract_user_id(init_data_raw)
return uid is not None and config.is_owner(uid)
# ββ Password Hashing βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def hash_password(plain: str) -> str:
return bcrypt.hashpw(plain.encode(), bcrypt.gensalt(rounds=12)).decode()
def check_password(plain: str, hashed: str) -> bool:
if not hashed:
return False
return bcrypt.checkpw(plain.encode(), hashed.encode())
# ββ Session Expiry βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def session_is_valid(created_at) -> bool:
"""Accept datetime object or ISO string."""
try:
if isinstance(created_at, str):
created_at = datetime.fromisoformat(created_at)
return datetime.utcnow() - created_at < timedelta(days=config.SESSION_TTL_DAYS)
except Exception:
return False
|