28 lines
		
	
	
		
			759 B
		
	
	
	
		
			Python
		
	
	
	
	
	
			
		
		
	
	
			28 lines
		
	
	
		
			759 B
		
	
	
	
		
			Python
		
	
	
	
	
	
import hmac
 | 
						|
import hashlib
 | 
						|
 | 
						|
from backend import config
 | 
						|
 | 
						|
 | 
						|
def _generate_hash(telegram_data: dict):
 | 
						|
    data = telegram_data.copy()
 | 
						|
    del data['hash']
 | 
						|
    keys = sorted(data.keys())
 | 
						|
    string_arr = []
 | 
						|
    for key in keys:
 | 
						|
        if data[key] is not None:
 | 
						|
            string_arr.append(key + '=' + str(data[key]))
 | 
						|
    string_cat = '\n'.join(string_arr)
 | 
						|
 | 
						|
    secret_key = hashlib.sha256(settings.TELEGRAM_BOT_TOKEN.encode('utf-8')).digest()
 | 
						|
    hash_bytes = bytes(string_cat, 'utf-8')
 | 
						|
    hmac_hash = hmac.new(secret_key, hash_bytes, hashlib.sha256).hexdigest()
 | 
						|
    return hmac_hash
 | 
						|
 | 
						|
 | 
						|
def telegram_authorize(telegram_data: dict):
 | 
						|
    generated_hash = _generate_hash(telegram_data)
 | 
						|
    user_hash = telegram_data['hash']
 | 
						|
    return generated_hash == user_hash
 | 
						|
 |