telegram-webapp-auth


Nametelegram-webapp-auth JSON
Version 1.0.1 PyPI version JSON
download
home_pagehttps://pypi.org/project/telegram-webapp-auth/
SummaryPython package that implements Telegram Web authentication algorithm.
upload_time2023-03-11 10:57:46
maintainer
docs_urlNone
authorDmitry Vasiliev
requires_python>=3.8,<4.0
licenseMIT
keywords telegram telegram bot
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # telegram-webapp-auth
This Python package implements [Telegram Web authentication algorithm](https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app).

## Documentation
[Small package - small documentation](docs/auth.md) :)

## Examples
### Using with FastAPI
Let's create some useful stuff according [OAuth2 tutorial](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/?h=auth).

File `utils.py`:
```python
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`:
```python
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...
    """
    ...
```

            

Raw data

            {
    "_id": null,
    "home_page": "https://pypi.org/project/telegram-webapp-auth/",
    "name": "telegram-webapp-auth",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "Telegram,Telegram Bot",
    "author": "Dmitry Vasiliev",
    "author_email": "contact.vasiliev.dmitry@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/e1/0b/153ae1e03fb577f9219ffcd6bec5227e402ad0d243fc0fcb1cca7666fa86/telegram_webapp_auth-1.0.1.tar.gz",
    "platform": null,
    "description": "# telegram-webapp-auth\nThis Python package implements [Telegram Web authentication algorithm](https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app).\n\n## Documentation\n[Small package - small documentation](docs/auth.md) :)\n\n## Examples\n### Using with FastAPI\nLet's create some useful stuff according [OAuth2 tutorial](https://fastapi.tiangolo.com/advanced/security/oauth2-scopes/?h=auth).\n\nFile `utils.py`:\n```python\nfrom telegram_webapp_auth import parse_user_data, parse_init_data, validate\nfrom fastapi import HTTPException, Depends\nfrom fastapi.security.http import HTTPBase, HTTPAuthorizationCredentials\nfrom pydantic import BaseModel\n\nfrom .config import TelegramBotSettings  # Telegram Bot configuration\n\ntelegram_authentication_schema = HTTPBase()\n\n\nclass TelegramUser(BaseModel):\n    id: int\n    first_name: str\n    last_name: str\n    username: str\n    language_code: str\n\n\ndef verify_token(auth_cred: HTTPAuthorizationCredentials) -> TelegramUser:\n    settings = TelegramBotSettings()\n    init_data = auth_cred.credentials\n    try:\n        if validate(init_data, settings.secret_key):  # generated using generate_secret_key function\n            raise ValueError(\"Invalid hash\")\n    except ValueError:\n        raise HTTPException(status_code=403, detail=\"Could not validate credentials\")\n\n    init_data = parse_init_data(init_data)\n    user_data = parse_user_data(init_data[\"user\"])\n    return TelegramUser.parse_obj(user_data)\n\n\ndef get_current_user(\n    auth_cred: HTTPAuthorizationCredentials = Depends(telegram_authentication_schema)\n) -> TelegramUser:\n    return verify_token(auth_cred)\n```\n\nFinally, we can use it as usual.\n\nFile `app.py`:\n```python\nfrom pydantic import BaseModel\nfrom fastapi import FastAPI, Depends\n\nfrom utils import get_current_user, TelegramUser\n\napp = FastAPI()\n\nclass Message(BaseModel):\n    text: str\n\n\n@app.post(\"/message\")\nasync def send_message(\n    message: Message,\n    user: TelegramUser = Depends(get_current_user),\n):\n    \"\"\"\n    Some backend logic...\n    \"\"\"\n    ...\n```\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Python package that implements Telegram Web authentication algorithm.",
    "version": "1.0.1",
    "split_keywords": [
        "telegram",
        "telegram bot"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "cab07380c7d074ca661bf875457d870589608b4ff3c6a7cb86a5639972388b21",
                "md5": "0e6f2e56fb19556802c72b5260066ae2",
                "sha256": "0c91f21cf955484cc8db9d1f5d75ff5bdebffcb41dbcdfb3fd83430859329b53"
            },
            "downloads": -1,
            "filename": "telegram_webapp_auth-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "0e6f2e56fb19556802c72b5260066ae2",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 3181,
            "upload_time": "2023-03-11T10:57:44",
            "upload_time_iso_8601": "2023-03-11T10:57:44.689158Z",
            "url": "https://files.pythonhosted.org/packages/ca/b0/7380c7d074ca661bf875457d870589608b4ff3c6a7cb86a5639972388b21/telegram_webapp_auth-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "e10b153ae1e03fb577f9219ffcd6bec5227e402ad0d243fc0fcb1cca7666fa86",
                "md5": "524af273c3c200f9ad044aaa0cd74c3e",
                "sha256": "0f29724c9f7631cf946d59b49a9769258747ead89f69ab1d0efdb5cc8dd71ed9"
            },
            "downloads": -1,
            "filename": "telegram_webapp_auth-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "524af273c3c200f9ad044aaa0cd74c3e",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 3058,
            "upload_time": "2023-03-11T10:57:46",
            "upload_time_iso_8601": "2023-03-11T10:57:46.333022Z",
            "url": "https://files.pythonhosted.org/packages/e1/0b/153ae1e03fb577f9219ffcd6bec5227e402ad0d243fc0fcb1cca7666fa86/telegram_webapp_auth-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-03-11 10:57:46",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "lcname": "telegram-webapp-auth"
}
        
Elapsed time: 0.04138s