telegram-webapps-authentication


Nametelegram-webapps-authentication JSON
Version 1.0.1 PyPI version JSON
download
home_pagehttps://github.com/danyadanyaa/telegram_webapps_authentication
SummaryThis Python package provides an authentication mechanism for Telegram web apps. It implements the algorithm for validating data received from a Telegram web app, ensuring the authenticity and integrity of the data.
upload_time2024-07-25 10:35:10
maintainerNone
docs_urlNone
authorDanila Dudin
requires_python>=3.6
licenseNone
keywords telegram webapp webapps auth authentication
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Telegram Authentication Module

This Python package provides an authentication mechanism for Telegram web apps. It implements the algorithm for validating data received from a Telegram web app, ensuring the authenticity and integrity of the data. For detailed information on validating data received via a web app, please refer to the [official Telegram documentation](https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app).

## Installation

To use this module, you need to have Python 3.x installed. Install the necessary dependencies using pip:

```bash
pip install telegram_webapps_authentication
```
## Example

Here is an example of how to use the `Authenticator` class with FastAPI:

```python
from typing import Optional

from fastapi import FastAPI, HTTPException, Header, Depends
from pydantic import BaseModel

from telegram_webapps_authentication import Authenticator, TelegramUser

app = FastAPI()

BOT_TOKEN = "YOUR_BOT_TOKEN"  # Replace it with your real telegram bot token
authenticator = Authenticator(BOT_TOKEN)

class Message(BaseModel):
    text: str

@app.get("/validate")
def validate_init_data(authorization: Optional[str] = Header()):
    try:
        if authenticator.validate_init_data(authorization):
            initial_data = authenticator.get_initial_data(authorization)
            return {"message": initial_data.dict()}
        else:
            raise HTTPException(status_code=400, detail="Data is not valid")
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@app.get("/get_user")
def get_user_instance(authorization: Optional[str] = Header()):
    user = authenticator.get_telegram_user(authorization)
    return user

@app.post("/message")
async def send_message(
    message: Message,
    user: TelegramUser = Depends(authenticator.get_telegram_user),
):
    """
    Your backend logic
    """
    ...
```

# Documentation

## Data Models

### `TelegramUser`

Represents a Telegram user.

- **Attributes:**
  - `id` (int): User ID.
  - `first_name` (str): User's first name.
  - `last_name` (str): User's last name.
  - `username` (str): User's username.
  - `language_code` (str): User's language code.

### `InitialData`

Represents the initial data received from Telegram.

- **Attributes:**
  - `query_id` (str): Unique query ID.
  - `user` (`TelegramUser`): User information.
  - `auth_date` (str): Authentication date.
  - `hash` (str): Hash for data validation.

## `Authenticator` Class

The `Authenticator` class provides methods for handling and validating the initial data from Telegram.

### `__init__(self, bot_token: str)`

Initializes the `Authenticator` with a bot token.

- **Args:**
  - `bot_token` (str): Token for the Telegram bot.

### `initial_data_parse(self, init_data: str) -> Dict[str, Any]`

Parses the initial data from a query string format into a dictionary.

- **Args:**
  - `init_data` (str): Initial data in query string format.
- **Returns:**
  - `Dict[str, Any]`: Parsed data as a dictionary.
- **Raises:**
  - `ValueError`: If any required keys are missing in the data.

### `initial_data_prepare(self, init_data_dict: Dict[str, Any]) -> str`

Prepares the cleaned data string by excluding the 'hash' key and sorting the remaining key-value pairs.

- **Args:**
  - `init_data_dict` (Dict[str, Any]): Dictionary of initial data.
- **Returns:**
  - `str`: Prepared data string.
- **Raises:**
  - `ValueError`: If `init_data_dict` is empty or if no data is available after excluding the 'hash' key.
  - `TypeError`: If any value is not a string.

### `extract_user_data(self, init_data: str) -> Dict[str, str]`

Extracts user-specific data from the initial data.

- **Args:**
  - `init_data` (str): Initial data in query string format.
- **Returns:**
  - `Dict[str, str]`: Extracted user data.
- **Raises:**
  - `ValueError`: If 'user' key is missing in initial data or if user data is not valid JSON.

### `validate_init_data(self, init_data: str) -> bool`

Validates the initial data by comparing the provided hash with the computed hash.

- **Args:**
  - `init_data` (str): Initial data in query string format.
- **Returns:**
  - `bool`: True if the data is valid, False otherwise.
- **Raises:**
  - `ValueError`: If 'hash' key is not found in `init_data`.

### `get_telegram_user(self, init_data: str) -> TelegramUser`

Extracts and returns a `TelegramUser` object from the initial data.

- **Args:**
  - `init_data` (str): Initial data in query string format.
- **Returns:**
  - `TelegramUser`: Extracted Telegram user information.
- **Raises:**
  - `ValueError`: If `init_data` is not valid.

### `get_initial_data(self, init_data: str) -> InitialData`

Extracts and returns an `InitialData` object from the initial data.

- **Args:**
  - `init_data` (str): Initial data in query string format.
- **Returns:**
  - `InitialData`: Extracted initial data information.
- **Raises:**
  - `ValueError`: If `init_data` is not valid.

### `encode_init_data(self, data: str) -> str`

Encodes initial data to base64 format.

- **Args:**
  - `data` (str): Data to be encoded.
- **Returns:**
  - `str`: Base64 encoded data.

### `decode_init_data(self, encoded_data: str) -> str`

Decodes initial data from base64 format.

- **Args:**
  - `encoded_data` (str): Base64 encoded data.
- **Returns:**
  - `str`: Decoded data.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/danyadanyaa/telegram_webapps_authentication",
    "name": "telegram-webapps-authentication",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.6",
    "maintainer_email": null,
    "keywords": "telegram webapp webapps auth authentication",
    "author": "Danila Dudin",
    "author_email": "sten1243@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/b4/79/538239b82cf627d3f746003d22e502e0ea5fadfa4573f35de5ba4c34fb27/telegram_webapps_authentication-1.0.1.tar.gz",
    "platform": null,
    "description": "# Telegram Authentication Module\r\n\r\nThis Python package provides an authentication mechanism for Telegram web apps. It implements the algorithm for validating data received from a Telegram web app, ensuring the authenticity and integrity of the data. For detailed information on validating data received via a web app, please refer to the [official Telegram documentation](https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app).\r\n\r\n## Installation\r\n\r\nTo use this module, you need to have Python 3.x installed. Install the necessary dependencies using pip:\r\n\r\n```bash\r\npip install telegram_webapps_authentication\r\n```\r\n## Example\r\n\r\nHere is an example of how to use the `Authenticator` class with FastAPI:\r\n\r\n```python\r\nfrom typing import Optional\r\n\r\nfrom fastapi import FastAPI, HTTPException, Header, Depends\r\nfrom pydantic import BaseModel\r\n\r\nfrom telegram_webapps_authentication import Authenticator, TelegramUser\r\n\r\napp = FastAPI()\r\n\r\nBOT_TOKEN = \"YOUR_BOT_TOKEN\"  # Replace it with your real telegram bot token\r\nauthenticator = Authenticator(BOT_TOKEN)\r\n\r\nclass Message(BaseModel):\r\n    text: str\r\n\r\n@app.get(\"/validate\")\r\ndef validate_init_data(authorization: Optional[str] = Header()):\r\n    try:\r\n        if authenticator.validate_init_data(authorization):\r\n            initial_data = authenticator.get_initial_data(authorization)\r\n            return {\"message\": initial_data.dict()}\r\n        else:\r\n            raise HTTPException(status_code=400, detail=\"Data is not valid\")\r\n    except Exception as e:\r\n        raise HTTPException(status_code=400, detail=str(e))\r\n\r\n@app.get(\"/get_user\")\r\ndef get_user_instance(authorization: Optional[str] = Header()):\r\n    user = authenticator.get_telegram_user(authorization)\r\n    return user\r\n\r\n@app.post(\"/message\")\r\nasync def send_message(\r\n    message: Message,\r\n    user: TelegramUser = Depends(authenticator.get_telegram_user),\r\n):\r\n    \"\"\"\r\n    Your backend logic\r\n    \"\"\"\r\n    ...\r\n```\r\n\r\n# Documentation\r\n\r\n## Data Models\r\n\r\n### `TelegramUser`\r\n\r\nRepresents a Telegram user.\r\n\r\n- **Attributes:**\r\n  - `id` (int): User ID.\r\n  - `first_name` (str): User's first name.\r\n  - `last_name` (str): User's last name.\r\n  - `username` (str): User's username.\r\n  - `language_code` (str): User's language code.\r\n\r\n### `InitialData`\r\n\r\nRepresents the initial data received from Telegram.\r\n\r\n- **Attributes:**\r\n  - `query_id` (str): Unique query ID.\r\n  - `user` (`TelegramUser`): User information.\r\n  - `auth_date` (str): Authentication date.\r\n  - `hash` (str): Hash for data validation.\r\n\r\n## `Authenticator` Class\r\n\r\nThe `Authenticator` class provides methods for handling and validating the initial data from Telegram.\r\n\r\n### `__init__(self, bot_token: str)`\r\n\r\nInitializes the `Authenticator` with a bot token.\r\n\r\n- **Args:**\r\n  - `bot_token` (str): Token for the Telegram bot.\r\n\r\n### `initial_data_parse(self, init_data: str) -> Dict[str, Any]`\r\n\r\nParses the initial data from a query string format into a dictionary.\r\n\r\n- **Args:**\r\n  - `init_data` (str): Initial data in query string format.\r\n- **Returns:**\r\n  - `Dict[str, Any]`: Parsed data as a dictionary.\r\n- **Raises:**\r\n  - `ValueError`: If any required keys are missing in the data.\r\n\r\n### `initial_data_prepare(self, init_data_dict: Dict[str, Any]) -> str`\r\n\r\nPrepares the cleaned data string by excluding the 'hash' key and sorting the remaining key-value pairs.\r\n\r\n- **Args:**\r\n  - `init_data_dict` (Dict[str, Any]): Dictionary of initial data.\r\n- **Returns:**\r\n  - `str`: Prepared data string.\r\n- **Raises:**\r\n  - `ValueError`: If `init_data_dict` is empty or if no data is available after excluding the 'hash' key.\r\n  - `TypeError`: If any value is not a string.\r\n\r\n### `extract_user_data(self, init_data: str) -> Dict[str, str]`\r\n\r\nExtracts user-specific data from the initial data.\r\n\r\n- **Args:**\r\n  - `init_data` (str): Initial data in query string format.\r\n- **Returns:**\r\n  - `Dict[str, str]`: Extracted user data.\r\n- **Raises:**\r\n  - `ValueError`: If 'user' key is missing in initial data or if user data is not valid JSON.\r\n\r\n### `validate_init_data(self, init_data: str) -> bool`\r\n\r\nValidates the initial data by comparing the provided hash with the computed hash.\r\n\r\n- **Args:**\r\n  - `init_data` (str): Initial data in query string format.\r\n- **Returns:**\r\n  - `bool`: True if the data is valid, False otherwise.\r\n- **Raises:**\r\n  - `ValueError`: If 'hash' key is not found in `init_data`.\r\n\r\n### `get_telegram_user(self, init_data: str) -> TelegramUser`\r\n\r\nExtracts and returns a `TelegramUser` object from the initial data.\r\n\r\n- **Args:**\r\n  - `init_data` (str): Initial data in query string format.\r\n- **Returns:**\r\n  - `TelegramUser`: Extracted Telegram user information.\r\n- **Raises:**\r\n  - `ValueError`: If `init_data` is not valid.\r\n\r\n### `get_initial_data(self, init_data: str) -> InitialData`\r\n\r\nExtracts and returns an `InitialData` object from the initial data.\r\n\r\n- **Args:**\r\n  - `init_data` (str): Initial data in query string format.\r\n- **Returns:**\r\n  - `InitialData`: Extracted initial data information.\r\n- **Raises:**\r\n  - `ValueError`: If `init_data` is not valid.\r\n\r\n### `encode_init_data(self, data: str) -> str`\r\n\r\nEncodes initial data to base64 format.\r\n\r\n- **Args:**\r\n  - `data` (str): Data to be encoded.\r\n- **Returns:**\r\n  - `str`: Base64 encoded data.\r\n\r\n### `decode_init_data(self, encoded_data: str) -> str`\r\n\r\nDecodes initial data from base64 format.\r\n\r\n- **Args:**\r\n  - `encoded_data` (str): Base64 encoded data.\r\n- **Returns:**\r\n  - `str`: Decoded data.\r\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "This Python package provides an authentication mechanism for Telegram web apps. It implements the algorithm for validating data received from a Telegram web app, ensuring the authenticity and integrity of the data.",
    "version": "1.0.1",
    "project_urls": {
        "GitHub": "https://github.com/danyadanyaa",
        "Homepage": "https://github.com/danyadanyaa/telegram_webapps_authentication",
        "Telegram": "https://t.me/yadaehodaice"
    },
    "split_keywords": [
        "telegram",
        "webapp",
        "webapps",
        "auth",
        "authentication"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2e2dd2c1bff3dcf28f7bfde7212d36fd3f25d82a75080a454fcac1c5855f94c7",
                "md5": "fc18a3e305054b649a468c7b2d76c4a4",
                "sha256": "d03b52cd04082462de67d0cca32ed1b2a83b5c9d4067ae6cd80ce6d15f0cfdae"
            },
            "downloads": -1,
            "filename": "telegram_webapps_authentication-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "fc18a3e305054b649a468c7b2d76c4a4",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.6",
            "size": 5432,
            "upload_time": "2024-07-25T10:35:08",
            "upload_time_iso_8601": "2024-07-25T10:35:08.666288Z",
            "url": "https://files.pythonhosted.org/packages/2e/2d/d2c1bff3dcf28f7bfde7212d36fd3f25d82a75080a454fcac1c5855f94c7/telegram_webapps_authentication-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "b479538239b82cf627d3f746003d22e502e0ea5fadfa4573f35de5ba4c34fb27",
                "md5": "a8895823e37bead602dea8cfa6f14473",
                "sha256": "a8d58c846e88fd186a1ff67288bd145953fdaeaf5b735f2e68b3fa070b69e6dc"
            },
            "downloads": -1,
            "filename": "telegram_webapps_authentication-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "a8895823e37bead602dea8cfa6f14473",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.6",
            "size": 4511,
            "upload_time": "2024-07-25T10:35:10",
            "upload_time_iso_8601": "2024-07-25T10:35:10.749461Z",
            "url": "https://files.pythonhosted.org/packages/b4/79/538239b82cf627d3f746003d22e502e0ea5fadfa4573f35de5ba4c34fb27/telegram_webapps_authentication-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-07-25 10:35:10",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "danyadanyaa",
    "github_project": "telegram_webapps_authentication",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [],
    "lcname": "telegram-webapps-authentication"
}
        
Elapsed time: 0.35992s