### Create Project Directory Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/install.md Creates a new directory for the project and navigates into it. ```shell mkdir learn-twa-auth && cd learn-twa-auth ``` -------------------------------- ### Install telegram-webapp-auth Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/install.md Installs or upgrades the telegram-webapp-auth library using pip. ```shell pip install --upgrade telegram-webapp-auth ``` -------------------------------- ### Set Up Virtual Environment Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/install.md Creates a Python virtual environment and activates it for project isolation. ```shell python -m venv .venv && source .venv/bin/activate ``` -------------------------------- ### Verify Python and Pip Installation Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/install.md Checks if Python and pip are installed and accessible in your system's PATH. ```shell python --version pip --version ``` -------------------------------- ### Install telegram-webapp-auth Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/README.md Instructions for installing the telegram-webapp-auth package using pip, poetry, or uv. ```Bash pip install telegram-webapp-auth # or poetry add telegram-webapp-auth # or uv add telegram-webapp-auth ``` -------------------------------- ### FastAPI Telegram Authentication Setup Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/examples/fastapi.md Sets up the necessary components for Telegram authentication within a FastAPI application. It defines a dependency to retrieve the Telegram authenticator and a dependency to get the current authenticated user based on provided credentials. ```Python import http from fastapi import Depends from fastapi import HTTPException from fastapi.security.http import HTTPAuthorizationCredentials from fastapi.security.http import HTTPBase from telegram_webapp_auth.auth import TelegramAuthenticator from telegram_webapp_auth.auth import WebAppUser from telegram_webapp_auth.auth import generate_secret_key from telegram_webapp_auth.errors import InvalidInitDataError from .config import TelegramBotSettings # Telegram Bot configuration telegram_authentication_schema = HTTPBase() def get_telegram_authenticator() -> TelegramAuthenticator: settings = TelegramBotSettings() secret_key = generate_secret_key(settings.token) return TelegramAuthenticator(secret_key) def get_current_user( auth_cred: HTTPAuthorizationCredentials = Depends(telegram_authentication_schema), telegram_authenticator: TelegramAuthenticator = Depends(get_telegram_authenticator), ) -> WebAppUser: try: init_data = telegram_authenticator.validate(auth_cred.credentials) except InvalidInitDataError: raise HTTPException( status_code=http.HTTPStatus.FORBIDDEN, detail="Forbidden access.", ) except Exception: raise HTTPException( status_code=http.HTTPStatus.INTERNAL_SERVER_ERROR, detail="Internal error.", ) if init_data.user is None: raise HTTPException( status_code=http.HTTPStatus.FORBIDDEN, detail="Forbidden access.", ) return init_data.user ``` -------------------------------- ### Django Settings for Telegram Auth Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/examples/django.md Configure your Django project's settings to include the Telegram Bot Token and generate a secret key for Telegram Web App authentication. This setup is crucial for the custom middleware to function correctly. ```python from telegram_webapp_auth.auth import generate_secret_key # other settings TELEGRAM_BOT_TOKEN = env.str('TELEGRAM_BOT_TOKEN') TELEGRAM_SECRET_KEY = generate_secret_key(TELEGRAM_BOT_TOKEN) ``` -------------------------------- ### Telegram Web App Authentication Initialization Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/index.md This snippet shows the basic initialization of the `telegram-webapp-auth` library. You need to provide your Telegram Bot Token to the constructor. This token is essential for the library to perform the cryptographic verification of the incoming data. ```javascript const TelegramWebAppAuth = require('telegram-webapp-auth'); // Replace 'YOUR_BOT_TOKEN' with your actual bot token obtained from BotFather const botToken = 'YOUR_BOT_TOKEN'; // Initialize the authenticator with the bot token const authenticator = new TelegramWebAppAuth(botToken); console.log('Telegram Web App authenticator initialized.'); ``` ```typescript import TelegramWebAppAuth from 'telegram-webapp-auth'; // Replace 'YOUR_BOT_TOKEN' with your actual bot token obtained from BotFather const botToken: string = 'YOUR_BOT_TOKEN'; // Initialize the authenticator with the bot token const authenticator = new TelegramWebAppAuth(botToken); console.log('Telegram Web App authenticator initialized.'); ``` -------------------------------- ### TelegramAuthenticator Class Source: https://github.com/swimmwatch/telegram-webapp-auth/wiki/Home Handles the authentication process for Telegram WebApp. It requires a secret key during initialization and provides a method to verify incoming tokens. ```python class TelegramAuthenticator: def __init__(self, secret: bytes): pass def verify_token(self, token: str) -> TelegramUser: """Verifies the data using the method from documentation. Returns Telegram user if data is valid. Links: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app Args: hash_: hash from init data token: init data from webapp Returns: TelegramUser: Telegram user if token is valid Raises: InvalidInitDataError: if the token is invalid """ pass ``` -------------------------------- ### Adding TWAAuthorizationMiddleware to Django Settings Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/examples/django.md Instructs how to register the custom `TWAAuthorizationMiddleware` within your Django project's `MIDDLEWARE` setting in `settings.py` to enable Telegram Web App authentication for all incoming requests. ```python MIDDLEWARE = [ # other middleware classes 'path.to.TWAAuthorizationMiddleware', ] ``` -------------------------------- ### Node.js Telegram Web App Authentication Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/index.md This snippet demonstrates how to use the telegram-webapp-auth library in a Node.js environment to verify the authenticity of a Telegram Web App request. It involves initializing the library with your bot's token and then using the `verify` method with the request's `initData` and `initDataRaw`. ```javascript const TelegramWebAppAuth = require('telegram-webapp-auth'); // Replace with your bot's token const botToken = 'YOUR_BOT_TOKEN'; const authenticator = new TelegramWebAppAuth(botToken); async function handleWebAppRequest(req, res) { const initData = req.body.initData; // Assuming initData is in the request body const initDataRaw = req.headers['x-telegram-init-data']; // Assuming initDataRaw is in headers if (!initData || !initDataRaw) { return res.status(400).send('Missing initData or initDataRaw'); } try { const isValid = await authenticator.verify(initData, initDataRaw); if (isValid) { // Data is valid, proceed with your application logic // You can access parsed initData via authenticator.data console.log('User data:', authenticator.data); res.status(200).send('Authentication successful!'); } else { res.status(401).send('Authentication failed!'); } } catch (error) { console.error('Authentication error:', error); res.status(500).send('Internal server error'); } } // Example usage within an Express.js route: // app.post('/webhook', express.json(), handleWebAppRequest); ``` ```typescript import TelegramWebAppAuth from 'telegram-webapp-auth'; import { Request, Response } from 'express'; // Replace with your bot's token const botToken: string = 'YOUR_BOT_TOKEN'; const authenticator = new TelegramWebAppAuth(botToken); async function handleWebAppRequest(req: Request, res: Response): Promise { const initData: string | undefined = req.body.initData; const initDataRaw: string | undefined = req.headers['x-telegram-init-data'] as string | undefined; if (!initData || !initDataRaw) { res.status(400).send('Missing initData or initDataRaw'); return; } try { const isValid: boolean = await authenticator.verify(initData, initDataRaw); if (isValid) { // Data is valid, proceed with your application logic // You can access parsed initData via authenticator.data console.log('User data:', authenticator.data); res.status(200).send('Authentication successful!'); } else { res.status(401).send('Authentication failed!'); } } catch (error) { console.error('Authentication error:', error); res.status(500).send('Internal server error'); } } // Example usage within an Express.js route: // app.post('/webhook', express.json(), handleWebAppRequest); ``` -------------------------------- ### Telegram Web App Authentication Module Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/references/auth.md The `auth` module within the `telegram-webapp-auth` library handles the core logic for verifying Telegram Web App requests. It typically involves checking signatures and validating data against known parameters. ```Python from telegram_webapp_auth import auth # Example usage (assuming you have the necessary data) # bot_token = "YOUR_BOT_TOKEN" # web_app_data = { # "init_data": "...", # "signature": "..." # } # # try: # is_valid = auth.validate_web_app_data(bot_token, web_app_data) # if is_valid: # print("Web App data is valid!") # else: # print("Web App data is invalid.") # except Exception as e: # print(f"An error occurred: {e}") ``` -------------------------------- ### FastAPI Endpoint with Telegram User Authentication Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/examples/fastapi.md Demonstrates how to secure a FastAPI POST endpoint using the `get_current_user` dependency. This ensures that only authenticated users, verified via Telegram Web App, can access the endpoint's functionality. ```Python from fastapi import Depends from fastapi import FastAPI from pydantic import BaseModel from telegram_webapp_auth.auth import WebAppUser from .auth import get_current_user app = FastAPI() class Message(BaseModel): text: str @app.post("/message") async def send_message( message: Message, user: WebAppUser = Depends(get_current_user), ): """ Some logic... """ ... ``` -------------------------------- ### TelegramWebAppAuthError Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/references/errors.md Base exception class for all errors within the telegram-webapp-auth library. Provides a common interface for handling authentication-related exceptions. ```python class TelegramWebAppAuthError(Exception): """Base exception for all errors in the telegram-webapp-auth library.""" pass ``` -------------------------------- ### Generate Secret Key Source: https://github.com/swimmwatch/telegram-webapp-auth/wiki/Home Generates a secret key from a Telegram token. This is a prerequisite for verifying authentication data. ```python def generate_secret_key(token: str) -> bytes: # Generates a secret key from a Telegram token. # Links: https://core.telegram.org/bots/webapps#validating-data-received-via-the-mini-app pass ``` -------------------------------- ### TelegramUser Class Source: https://github.com/swimmwatch/telegram-webapp-auth/wiki/Home Represents a Telegram user with various attributes like ID, name, and language code. Used to store and return user information after successful authentication. ```python class TelegramUser: """Represents a Telegram user. Links: https://core.telegram.org/bots/webapps#webappuser """ def __init__(self, id: int, first_name: str, is_bot: bool | None = None, last_name: str | None = None, username: str | None = None, language_code: str | None = None, is_premium: bool | None = None, added_to_attachment_menu: bool | None = None, allows_write_to_pm: bool | None = None, photo_url: str | None = None) -> None: pass ``` -------------------------------- ### Telegram Web App Authorization Middleware for Django Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/guide/examples/django.md Implement a custom Django middleware to handle Telegram Web App authentication. This middleware validates the 'Authorization' header using a TelegramAuthenticator, retrieves user information, and associates the authenticated user with the request object. ```python from django.conf import settings from django.contrib.auth.models import User from django.http import HttpRequest from django.http import HttpResponse from telegram_webapp_auth.auth import TelegramAuthenticator from telegram_webapp_auth.errors import InvalidInitDataError class TWAAuthorizationMiddleware: def __init__(self, get_response) -> None: self.get_response = get_response self._telegram_authenticator = TelegramAuthenticator(settings.TELEGRAM_SECRET_KEY) def __call__(self, request: HttpRequest) -> HttpResponse: # Code to be executed for each request before # the view (and later middleware) are called. auth_cred = request.headers.get('Authorization') try: init_data = self._telegram_authenticator.validate(auth_cred) except InvalidInitDataError: # TODO: handle error pass if not init_data.user: # TODO: handle error pass current_user = User.objects.filter(tg_id=init_data.user.id).first() if not current_user: # TODO: handle error pass request.user = current_user # Associate current user with the request object response = self.get_response(request) # Code to be executed for each request/response after # the view is called. return response ``` -------------------------------- ### InvalidBotTokenError Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/references/errors.md Raised when the provided bot token is incorrect or does not match the token associated with the Web App's origin. This is essential for verifying the bot's identity. ```python class InvalidBotTokenError(TelegramWebAppAuthError): """Raised when the bot token is invalid.""" pass ``` -------------------------------- ### InvalidSignatureError Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/references/errors.md Raised when the digital signature of the authentication data does not match the expected signature. This is a critical security check failure. ```python class InvalidSignatureError(InvalidAuthDataError): """Raised when the signature of the auth data is invalid.""" pass ``` -------------------------------- ### ExpiredAuthDataError Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/references/errors.md Raised when the authentication data has expired. Telegram Web App data has a limited validity period, and this error indicates that the data is no longer fresh. ```python class ExpiredAuthDataError(InvalidAuthDataError): """Raised when the authentication data has expired.""" pass ``` -------------------------------- ### InvalidAuthDataError Source: https://github.com/swimmwatch/telegram-webapp-auth/blob/master/docs/references/errors.md Raised when the authentication data received from Telegram is invalid or malformed. This typically indicates a problem with the data signature or its structure. ```python class InvalidAuthDataError(TelegramWebAppAuthError): """Raised when the authentication data is invalid.""" pass ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.