Python package that implements Telegram Web authentication algorithm.
Project description
telegram-webapp-auth
This Python package implements Telegram Web authentication algorithm.
Documentation
Small package - small documentation :)
Examples
Using with FastAPI
Let's create some useful stuff according OAuth2 tutorial.
File utils.py
:
from telegram_webapp_auth import parse_user_data, parse_init_data, validate
from fastapi import HTTPException, Depends
from fastapi.security.http import HTTPBase, HTTPAuthorizationCredentials
from pydantic import BaseModel
from .config import TelegramBotSettings # Telegram Bot configuration
telegram_authentication_schema = HTTPBase()
class TelegramUser(BaseModel):
id: int
first_name: str
last_name: str
username: str
language_code: str
def verify_token(auth_cred: HTTPAuthorizationCredentials) -> TelegramUser:
settings = TelegramBotSettings()
init_data = auth_cred.credentials
try:
if validate(init_data, settings.secret_key): # generated using generate_secret_key function
raise ValueError("Invalid hash")
except ValueError:
raise HTTPException(status_code=403, detail="Could not validate credentials")
init_data = parse_init_data(init_data)
user_data = parse_user_data(init_data["user"])
return TelegramUser.parse_obj(user_data)
def get_current_user(
auth_cred: HTTPAuthorizationCredentials = Depends(telegram_authentication_schema)
) -> TelegramUser:
return verify_token(auth_cred)
Finally, we can use it as usual.
File app.py
:
from pydantic import BaseModel
from fastapi import FastAPI, Depends
from utils import get_current_user, TelegramUser
app = FastAPI()
class Message(BaseModel):
text: str
@app.post("/message")
async def send_message(
message: Message,
user: TelegramUser = Depends(get_current_user),
):
"""
Some backend logic...
"""
...
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Close
Hashes for telegram_webapp_auth-1.0.1.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0f29724c9f7631cf946d59b49a9769258747ead89f69ab1d0efdb5cc8dd71ed9 |
|
MD5 | 524af273c3c200f9ad044aaa0cd74c3e |
|
BLAKE2b-256 | e10b153ae1e03fb577f9219ffcd6bec5227e402ad0d243fc0fcb1cca7666fa86 |
Close
Hashes for telegram_webapp_auth-1.0.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 0c91f21cf955484cc8db9d1f5d75ff5bdebffcb41dbcdfb3fd83430859329b53 |
|
MD5 | 0e6f2e56fb19556802c72b5260066ae2 |
|
BLAKE2b-256 | cab07380c7d074ca661bf875457d870589608b4ff3c6a7cb86a5639972388b21 |