Advertisement
Guest User

Untitled

a guest
Feb 26th, 2020
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.10 KB | None | 0 0
  1. import hashlib
  2. import hmac
  3. from collections import OrderedDict
  4. from datetime import datetime, timedelta
  5. from typing import Union
  6.  
  7.  
  8. TELEGRAM_BOT_TOKEN = "токен бота"
  9.  
  10. def is_data_from_telegram(
  11.     data: dict, timedelta_min: Union[int, float] = 1
  12. ) -> bool:
  13.     """
  14.    :param data: данные полученные от телеграма
  15.    :param timedelta_min: кол-во минут в течении которых считать данные валидными
  16.    :return: bool
  17.    """
  18.     data_alphabetical_order = OrderedDict(sorted(data.dict(exclude_unset=True).items()))
  19.     data_check_string = "\n".join([f"{key}={value}" for key, value in data_alphabetical_order.items() if key != "hash"])
  20.  
  21.     secret_key = hashlib.sha256(TELEGRAM_BOT_TOKEN.encode()).digest()
  22.     check_hash = hmac.new(secret_key, data_check_string.encode(), digestmod=hashlib.sha256).hexdigest()
  23.  
  24.     if data.hash != check_hash:
  25.         return False
  26.  
  27.    
  28.     if (int(datetime.now().timestamp()) - data.auth_date) > timedelta(minutes=timedelta_min).total_seconds():
  29.             return False
  30.  
  31.     return True
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement