Add session cooldown to batcher

This commit is contained in:
Michail Kostocka 2024-12-14 11:38:23 +03:00
parent ff9c8c76b4
commit df4e6a685b
4 changed files with 18 additions and 3 deletions

1
.gitignore vendored
View File

@ -5,4 +5,5 @@ __pycache__/
*.py[cod]
celerybeat-schedule
backend/static
backend/media
bot/logs.log

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

View File

@ -4,11 +4,12 @@ import base64
import hashlib
import json
from fastapi import Header, HTTPException
from typing import Tuple
from .config import TG_TOKEN
async def get_token_header(authorization: str = Header()) -> (int, str):
async def get_token_header(authorization: str = Header()) -> Tuple[int, str]:
if not authorization:
raise HTTPException(status_code=403, detail='Unauthorized')
@ -48,5 +49,4 @@ async def get_token_header(authorization: str = Header()) -> (int, str):
raise HTTPException(status_code=403, detail='Unauthorized')
user_info = json.loads(data_dict['user'])
return user_info['id'], authorization
return user_info['id'], token

View File

@ -5,6 +5,8 @@ import aiohttp
import redis.asyncio as redis
import aio_pika
import asyncpg
import base64
from fastapi.exceptions import HTTPException
from app.src.domain.setting import get_setting
from .repos.redis import (
@ -103,8 +105,14 @@ async def _has_any_clicks(r: redis.Redis, user_id: int) -> bool:
async def _get_refresh_energy(r: redis.Redis, user_id: int, req_token: str) -> int:
new_auth_date = _auth_date_from_token(req_token)
current_token = await get_user_session(r, user_id)
if current_token != req_token:
if current_token is not None:
last_auth_date = _auth_date_from_token(current_token)
session_cooldown = get_setting('SESSION_COOLDOWN')
if new_auth_date - last_auth_date < session_cooldown:
raise HTTPException(status_code=403, detail='Unauthorized')
session_energy = int(get_setting('SESSION_ENERGY'))
await set_user_session(r, user_id, req_token)
await set_energy(r, user_id, session_energy)
@ -112,6 +120,12 @@ async def _get_refresh_energy(r: redis.Redis, user_id: int, req_token: str) -> i
else:
return await r_get_energy(r, user_id)
def _auth_date_from_token(token):
split_res = base64.b64decode(token).decode('utf-8').split(':')
data_check_string = ':'.join(split_res[:-1]).strip().replace('/', '\\/')
data_dict = dict([x.split('=') for x in data_check_string.split('\n')])
return int(data_dict['auth_date'])
async def check_energy(r: redis.Redis, user_id: int, amount: int, _token: str) -> Tuple[int, int]:
_energy = await _get_refresh_energy(r, user_id, _token)