Skip to content

Commit

Permalink
user async lock
Browse files Browse the repository at this point in the history
  • Loading branch information
Zoom-Developer committed Nov 6, 2024
1 parent 9e0d95e commit b485524
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 12 deletions.
12 changes: 7 additions & 5 deletions backend/src/application/auth/depends.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from typing import AsyncGenerator
from fastapi import Depends, Security
from fastapi.security import APIKeyHeader
import hashlib
import hmac
import json
import asyncio
import urllib.parse

from config import TG_CHANNEL_ID, TG_TOKEN
from config import TG_TOKEN
from domain.user import UserRepository
from application.user import UserService
from infrastructure.db import User, CTX_SESSION
Expand All @@ -14,8 +16,9 @@

tg_auth = APIKeyHeader(name = "Tg-Authorization", description = "Telgram Init Data")

locks: dict[int, asyncio.Lock] = {}

async def get_userdata(auth: str = Security(tg_auth)) -> dict:
async def get_userdata(auth: str = Security(tg_auth)) -> AsyncGenerator[dict, None]:
tg = dict(urllib.parse.parse_qsl(urllib.parse.unquote(auth)))
if not tg.get("hash"):
raise AuthDataException
Expand All @@ -30,13 +33,12 @@ async def get_userdata(auth: str = Security(tg_auth)) -> dict:
raise AuthDataException

user = json.loads(tg['user'])
return user

async with locks.setdefault(user['id'], asyncio.Lock()):
yield user

async def get_userid(userdata: dict = Depends(get_userdata)) -> int:
return userdata['id']


async def get_user(userdata: dict = Depends(get_userdata)) -> User:
user = await UserRepository().get(userdata['id'])
if not user:
Expand Down
9 changes: 2 additions & 7 deletions backend/src/domain/user/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ class BaseUser(BaseModel):

@field_validator("name", "surname")
@staticmethod
def name_validator(val):
def name_validator(val: str):
val = val.strip()
if " " in val:
raise HTTPException(422, "name and surname should be one word")
return val
Expand Down Expand Up @@ -59,12 +60,6 @@ class BanUser(UserRequest):
class VerifyUser(UserRequest):
value: bool

# class GetUser(TelegramRequest):
# user_id: int

# class TelegramRequestResponse(TelegramRequest):
# success: bool

class GetUserResponse(BaseModel):
text: str
attachments: list[str]
Expand Down

0 comments on commit b485524

Please sign in to comment.