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,11 +87,15 @@ 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()
for attempt in range(2):
async with session.get( async with session.get(
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records", f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records",
params={"filter": f'user_id="{user_id}"', "perPage": 1}, params={"filter": f'user_id="{user_id}"', "perPage": 1},
headers=await _hdrs(), headers=await _hdrs(),
) as resp: ) as resp:
if resp.status == 403 and attempt == 0:
_invalidate_token()
continue
resp.raise_for_status() resp.raise_for_status()
data = await resp.json() data = await resp.json()
items = data.get("items", []) items = data.get("items", [])
@@ -96,11 +105,15 @@ async def get_record(user_id: str) -> dict[str, Any] | 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()
for attempt in range(2):
async with session.post( async with session.post(
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records", f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records",
json=record, json=record,
headers=await _hdrs(), headers=await _hdrs(),
) as resp: ) as resp:
if resp.status == 403 and attempt == 0:
_invalidate_token()
continue
if resp.status not in (200, 201): if resp.status not in (200, 201):
text = await resp.text() text = await resp.text()
raise RuntimeError(f"PocketBase create failed ({resp.status}): {text}") raise RuntimeError(f"PocketBase create failed ({resp.status}): {text}")
@@ -110,11 +123,15 @@ async def create_record(record: dict[str, Any]) -> dict[str, Any]:
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()
for attempt in range(2):
async with session.patch( async with session.patch(
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records/{record_id}", f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records/{record_id}",
json=data, json=data,
headers=await _hdrs(), headers=await _hdrs(),
) as resp: ) as resp:
if resp.status == 403 and attempt == 0:
_invalidate_token()
continue
resp.raise_for_status() resp.raise_for_status()
return await resp.json() return await resp.json()
@@ -122,11 +139,15 @@ async def update_record(record_id: str, data: dict[str, Any]) -> dict[str, Any]:
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()
for attempt in range(2):
async with session.get( async with session.get(
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records", f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records",
params={"perPage": 1, "page": 1}, params={"perPage": 1, "page": 1},
headers=await _hdrs(), headers=await _hdrs(),
) as resp: ) as resp:
if resp.status == 403 and attempt == 0:
_invalidate_token()
continue
resp.raise_for_status() resp.raise_for_status()
data = await resp.json() data = await resp.json()
return int(data.get("totalItems", 0)) return int(data.get("totalItems", 0))
@@ -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:
hdrs = await _hdrs()
for attempt in range(2):
async with session.get( async with session.get(
f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records", f"{PB_URL}/api/collections/{ECONOMY_COLLECTION}/records",
params={"perPage": page_size, "page": page}, params={"perPage": page_size, "page": page},
headers=hdrs, headers=hdrs,
) as resp: ) as resp:
if resp.status == 403 and attempt == 0:
_invalidate_token()
hdrs = await _hdrs()
continue
resp.raise_for_status() resp.raise_for_status()
data = await resp.json() data = await resp.json()
batch = data.get("items", []) batch = data.get("items", [])
results.extend(batch) results.extend(batch)
if len(batch) < page_size: if len(batch) < page_size:
break
page += 1
return results return results
page += 1
break