Created
March 20, 2025 15:16
-
-
Save pawnhearts/7c10c21c64ad045980ac1b60ad80d963 to your computer and use it in GitHub Desktop.
tg miniapp auth
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
from urllib.parse import parse_qs | |
from django.conf import settings | |
from django.contrib.auth import login, get_user_model | |
from aiogram.utils.web_app import check_webapp_signature | |
from rest_framework.authentication import TokenAuthentication, BaseAuthentication, exceptions | |
class MiniAppAuthenication(BaseAuthentication): | |
def authenticate(self, request): | |
if not check_webapp_signature(settings.BOT_TOKEN, request.data.get('_auth', '')): | |
raise exceptions.AuthenticationFailed('Invalid signature') | |
model = get_user_model() | |
user_data = json.loads(parse_qs(request.data.get('_auth', ''))['user'][0]) | |
try: | |
user = model.objects.get(telegram_id=user_data['id']) | |
except model.DoesNotExist: | |
raise exceptions.AuthenticationFailed('Invalid user') | |
if not user.is_active: | |
raise exceptions.AuthenticationFailed('Blocked user') | |
if telegram_username := user_data.get('username'): | |
user.telegram_username = telegram_username | |
for k in ('first_name', 'last_name'): | |
if user_data.get(k) and not getattr(user, k): | |
setattr(user, k, user_data[k]) | |
user.save(update_fields=['first_name', 'last_name', 'telegram_username']) | |
login(request._request, user) | |
return user, None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment