1
0
forked from sass/tipibot

Fix 403 auth error

This commit is contained in:
Rene Arumetsa
2026-05-04 17:14:21 +03:00
parent d65173fbe9
commit 6d344a47f4

View File

@@ -75,6 +75,11 @@ async def _hdrs() -> dict[str, str]:
return {"Authorization": await _ensure_auth()} return {"Authorization": await _ensure_auth()}
def _invalidate_token() -> None:
global _token_expiry
_token_expiry = 0.0
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# CRUD helpers # CRUD helpers
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
@@ -82,54 +87,70 @@ async def _hdrs() -> dict[str, str]:
async def get_record(user_id: str) -> dict[str, Any] | None: async def get_record(user_id: str) -> dict[str, Any] | None:
"""Fetch one economy record by Discord user_id. Returns None if not found.""" """Fetch one economy record by Discord user_id. Returns None if not found."""
session = _get_session() session = _get_session()
async with session.get( for attempt in range(2):
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records", async with session.get(
params={"filter": f'user_id="{user_id}"', "perPage": 1}, f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records",
headers=await _hdrs(), params={"filter": f'user_id="{user_id}"', "perPage": 1},
) as resp: headers=await _hdrs(),
resp.raise_for_status() ) as resp:
data = await resp.json() if resp.status == 403 and attempt == 0:
items = data.get("items", []) _invalidate_token()
return items[0] if items else None continue
resp.raise_for_status()
data = await resp.json()
items = data.get("items", [])
return items[0] if items else None
async def create_record(record: dict[str, Any]) -> dict[str, Any]: async def create_record(record: dict[str, Any]) -> dict[str, Any]:
"""Create a new economy record. Returns the created record (includes PB id).""" """Create a new economy record. Returns the created record (includes PB id)."""
session = _get_session() session = _get_session()
async with session.post( for attempt in range(2):
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records", async with session.post(
json=record, f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records",
headers=await _hdrs(), json=record,
) as resp: headers=await _hdrs(),
if resp.status not in (200, 201): ) as resp:
text = await resp.text() if resp.status == 403 and attempt == 0:
raise RuntimeError(f"PocketBase create failed ({resp.status}): {text}") _invalidate_token()
return await resp.json() continue
if resp.status not in (200, 201):
text = await resp.text()
raise RuntimeError(f"PocketBase create failed ({resp.status}): {text}")
return await resp.json()
async def update_record(record_id: str, data: dict[str, Any]) -> dict[str, Any]: async def update_record(record_id: str, data: dict[str, Any]) -> dict[str, Any]:
"""PATCH an existing record by its PocketBase record id.""" """PATCH an existing record by its PocketBase record id."""
session = _get_session() session = _get_session()
async with session.patch( for attempt in range(2):
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records/{record_id}", async with session.patch(
json=data, f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records/{record_id}",
headers=await _hdrs(), json=data,
) as resp: headers=await _hdrs(),
resp.raise_for_status() ) as resp:
return await resp.json() if resp.status == 403 and attempt == 0:
_invalidate_token()
continue
resp.raise_for_status()
return await resp.json()
async def count_records() -> int: async def count_records() -> int:
"""Return the total number of records in the collection (single cheap request).""" """Return the total number of records in the collection (single cheap request)."""
session = _get_session() session = _get_session()
async with session.get( for attempt in range(2):
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records", async with session.get(
params={"perPage": 1, "page": 1}, f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records",
headers=await _hdrs(), params={"perPage": 1, "page": 1},
) as resp: headers=await _hdrs(),
resp.raise_for_status() ) as resp:
data = await resp.json() if resp.status == 403 and attempt == 0:
return int(data.get("totalItems", 0)) _invalidate_token()
continue
resp.raise_for_status()
data = await resp.json()
return int(data.get("totalItems", 0))
async def list_all_records(page_size: int = 500) -> list[dict[str, Any]]: async def list_all_records(page_size: int = 500) -> list[dict[str, Any]]:
@@ -137,18 +158,23 @@ async def list_all_records(page_size: int = 500) -> list[dict[str, Any]]:
results: list[dict[str, Any]] = [] results: list[dict[str, Any]] = []
page = 1 page = 1
session = _get_session() session = _get_session()
hdrs = await _hdrs()
while True: while True:
async with session.get( hdrs = await _hdrs()
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records", for attempt in range(2):
params={"perPage": page_size, "page": page}, async with session.get(
headers=hdrs, f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records",
) as resp: params={"perPage": page_size, "page": page},
resp.raise_for_status() headers=hdrs,
data = await resp.json() ) as resp:
batch = data.get("items", []) if resp.status == 403 and attempt == 0:
results.extend(batch) _invalidate_token()
if len(batch) < page_size: hdrs = await _hdrs()
continue
resp.raise_for_status()
data = await resp.json()
batch = data.get("items", [])
results.extend(batch)
if len(batch) < page_size:
return results
page += 1
break break
page += 1
return results