forked from mtusi2026/mtusi2026lab4
feat(lab4): implement S3 attachments with fault tolerance
This commit is contained in:
@@ -0,0 +1,137 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unicodedata
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from .database import get_connection
|
||||
from .storage import s3, BUCKET
|
||||
|
||||
MAX_BYTES = 10 * 1024**2
|
||||
upload_slots = asyncio.Semaphore(1)
|
||||
|
||||
|
||||
def serialize(row):
|
||||
result = {key: str(row[key]) for key in ('id', 'chat_id', 'owner_id')}
|
||||
result.update({key: row[key] for key in ('filename', 'content_type', 'size_bytes', 'sha256', 'status')})
|
||||
result.update({key: row[key].isoformat().replace('+00:00', 'Z') for key in ('created_at', 'updated_at')})
|
||||
return dict(result, variants=[], error_code=None)
|
||||
|
||||
|
||||
def persist(path, chat, owner, filename, mime, size, checksum):
|
||||
attachment_id = uuid4()
|
||||
key = 'originals/' + str(attachment_id)
|
||||
# The same lock is taken by cleanup before its final DB check/deletion.
|
||||
# A process crash releases the transaction; an uncommitted object is later cleaned.
|
||||
with get_connection() as conn:
|
||||
with conn.transaction():
|
||||
conn.execute('SELECT pg_advisory_xact_lock(hashtextextended(%s, 0))', (key,))
|
||||
with open(path, 'rb') as source:
|
||||
s3.put_object(Bucket=BUCKET, Key=key, Body=source, ContentLength=size, ContentType=mime)
|
||||
row = conn.execute('''INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, object_key, size_bytes, content_type, sha256)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *''',
|
||||
(attachment_id, UUID(chat), UUID(owner), filename, key, size, mime, checksum)).fetchone()
|
||||
# Exiting transaction above commits before returning 201.
|
||||
return serialize(row)
|
||||
|
||||
|
||||
def accessible(attachment_id, user_id):
|
||||
try:
|
||||
aid = UUID(attachment_id)
|
||||
except ValueError:
|
||||
raise HTTPException(400, 'Неверный UUID') from None
|
||||
with get_connection() as conn:
|
||||
row = conn.execute('''SELECT a.* FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id=a.chat_id
|
||||
WHERE a.id=%s AND cm.user_id=%s''', (aid, UUID(user_id))).fetchone()
|
||||
if row is None:
|
||||
raise HTTPException(404, 'Вложение не найдено')
|
||||
return row
|
||||
|
||||
|
||||
def register(app, current_user, get_chat):
|
||||
@app.post('/api/v1/chats/{chat_id}/attachments', status_code=201)
|
||||
async def upload(chat_id: str, request: Request):
|
||||
user = await run_in_threadpool(current_user, request)
|
||||
chat = await run_in_threadpool(get_chat, chat_id, request)
|
||||
filename = request.query_params.get('filename', '')
|
||||
if (not 1 <= len(filename) <= 255 or not filename.strip()
|
||||
or any(c in '/\\' or unicodedata.category(c).startswith('C') for c in filename)):
|
||||
raise HTTPException(400, 'Недопустимое имя файла')
|
||||
mime = request.headers.get('content-type', '').split(';')[0].strip().lower()
|
||||
if mime not in ('image/png', 'image/jpeg'):
|
||||
raise HTTPException(415, 'Ожидается PNG или JPEG')
|
||||
length = request.headers.get('content-length')
|
||||
if length is not None:
|
||||
if not length.isascii() or not length.isdecimal() or len(length) > 12:
|
||||
raise HTTPException(400, 'Неверный размер')
|
||||
if int(length) > MAX_BYTES:
|
||||
raise HTTPException(413, 'Файл больше 10 MiB')
|
||||
try:
|
||||
await asyncio.wait_for(upload_slots.acquire(), timeout=30)
|
||||
except asyncio.TimeoutError:
|
||||
raise HTTPException(503, 'Загрузчик занят') from None
|
||||
try:
|
||||
with tempfile.NamedTemporaryFile(prefix='lab4-') as target:
|
||||
size = 0
|
||||
digest = hashlib.sha256()
|
||||
try:
|
||||
async with asyncio.timeout(30):
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > MAX_BYTES:
|
||||
raise HTTPException(413, 'Файл больше 10 MiB')
|
||||
target.write(chunk)
|
||||
digest.update(chunk)
|
||||
except ClientDisconnect:
|
||||
raise HTTPException(400, 'Загрузка прервана') from None
|
||||
except TimeoutError:
|
||||
raise HTTPException(400, 'Истекло время загрузки') from None
|
||||
target.flush()
|
||||
def validate():
|
||||
try:
|
||||
return subprocess.run([sys.executable, '-m', 'src.image_check', target.name, mime],
|
||||
timeout=10, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL).returncode
|
||||
except subprocess.TimeoutExpired:
|
||||
return 15
|
||||
code = await run_in_threadpool(validate)
|
||||
if code != 0:
|
||||
raise HTTPException(413 if code == 13 else 415, 'Недопустимое изображение')
|
||||
return await run_in_threadpool(persist, target.name, chat['id'], user['id'], filename, mime, size, digest.hexdigest())
|
||||
finally:
|
||||
upload_slots.release()
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}')
|
||||
def metadata(attachment_id: str, request: Request):
|
||||
return serialize(accessible(attachment_id, current_user(request)['id']))
|
||||
|
||||
@app.get('/api/v1/attachments/{attachment_id}/content')
|
||||
def content(attachment_id: str, request: Request):
|
||||
row = accessible(attachment_id, current_user(request)['id'])
|
||||
if request.query_params.get('variant', 'original') != 'original':
|
||||
raise HTTPException(404, 'Вариант не найден')
|
||||
obj = s3.get_object(Bucket=BUCKET, Key=row['object_key'])
|
||||
def chunks():
|
||||
try:
|
||||
for chunk in obj['Body'].iter_chunks(64 * 1024):
|
||||
yield chunk
|
||||
finally:
|
||||
obj['Body'].close()
|
||||
return StreamingResponse(chunks(), media_type=row['content_type'], headers={
|
||||
'Content-Length': str(row['size_bytes']), 'X-Content-Type-Options': 'nosniff',
|
||||
'Content-Disposition': 'attachment', 'Cache-Control': 'private, no-store'})
|
||||
|
||||
@app.exception_handler(BotoCoreError)
|
||||
@app.exception_handler(ClientError)
|
||||
async def storage_error(request, exc):
|
||||
from .main import error_response
|
||||
return error_response(request, 503, 'unavailable', 'Хранилище временно недоступно')
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerifyMismatchError
|
||||
|
||||
|
||||
password_hasher = PasswordHasher(
|
||||
time_cost=3,
|
||||
memory_cost=65536,
|
||||
parallelism=4,
|
||||
)
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return password_hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash: str, password: str) -> bool:
|
||||
try:
|
||||
return password_hasher.verify(password_hash, password)
|
||||
except (VerifyMismatchError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def parse_basic(authorization: str | None) -> tuple[str, str] | None:
|
||||
if not authorization:
|
||||
return None
|
||||
|
||||
scheme, separator, credentials = authorization.partition(" ")
|
||||
|
||||
if not separator or scheme.lower() != "basic":
|
||||
return None
|
||||
|
||||
try:
|
||||
raw = base64.b64decode(credentials, validate=True)
|
||||
decoded = raw.decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
return None
|
||||
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", username):
|
||||
return None
|
||||
|
||||
if not 12 <= len(password) <= 128:
|
||||
return None
|
||||
|
||||
return username, password
|
||||
|
||||
|
||||
def parse_bearer(authorization: str | None) -> str | None:
|
||||
if not authorization:
|
||||
return None
|
||||
|
||||
scheme, separator, token = authorization.partition(" ")
|
||||
|
||||
if not separator or scheme.lower() != "bearer":
|
||||
return None
|
||||
|
||||
if not re.fullmatch(r"[A-Za-z0-9._~+/-]+={0,2}", token) or len(token) > 512:
|
||||
return None
|
||||
|
||||
return token
|
||||
|
||||
|
||||
def create_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
|
||||
|
||||
def session_expiration() -> datetime:
|
||||
ttl = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
if ttl < 1:
|
||||
raise ValueError("SESSION_TTL_SECONDS must be positive")
|
||||
|
||||
return datetime.now(timezone.utc) + timedelta(seconds=ttl)
|
||||
|
||||
|
||||
def format_datetime(value: datetime) -> str:
|
||||
return value.astimezone(timezone.utc).isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z")
|
||||
@@ -0,0 +1,245 @@
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from .database import get_connection
|
||||
|
||||
|
||||
def serialize_chat(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(member_id) for member_id in row["member_ids"]],
|
||||
"created_at": row["created_at"].isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def serialize_message(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"attachment_ids": [str(a) for a in row["attachment_ids"]],
|
||||
"created_at": row["created_at"].isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def create_chat(creator_id, title, member_ids):
|
||||
chat_id = uuid4()
|
||||
members = [UUID(member_id) for member_id in member_ids]
|
||||
|
||||
with get_connection() as conn:
|
||||
with conn.transaction():
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id
|
||||
FROM users
|
||||
WHERE id = ANY(%s::uuid[])
|
||||
""",
|
||||
(members,),
|
||||
)
|
||||
existing = {row["id"] for row in cur.fetchall()}
|
||||
|
||||
if len(existing) != len(members):
|
||||
return None
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO chats (id, title, created_by)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id, title, created_at
|
||||
""",
|
||||
(chat_id, title, UUID(creator_id)),
|
||||
)
|
||||
chat = cur.fetchone()
|
||||
|
||||
cur.executemany(
|
||||
"""
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
VALUES (%s, %s)
|
||||
""",
|
||||
[(chat_id, member_id) for member_id in members],
|
||||
)
|
||||
|
||||
return {
|
||||
"id": str(chat["id"]),
|
||||
"title": chat["title"],
|
||||
"member_ids": member_ids,
|
||||
"created_at": chat["created_at"].isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def get_chat(chat_id, user_id):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
ARRAY(
|
||||
SELECT cm2.user_id
|
||||
FROM chat_members cm2
|
||||
WHERE cm2.chat_id = c.id
|
||||
ORDER BY cm2.user_id
|
||||
) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = c.id
|
||||
WHERE c.id = %s
|
||||
AND cm.user_id = %s
|
||||
""",
|
||||
(UUID(chat_id), UUID(user_id)),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return serialize_chat(row) if row else None
|
||||
|
||||
|
||||
def list_chats(user_id, limit, last_chat_id=None):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
last_key = None
|
||||
|
||||
if last_chat_id is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT c.created_at, c.id
|
||||
FROM chats c
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = c.id
|
||||
WHERE c.id = %s
|
||||
AND cm.user_id = %s
|
||||
""",
|
||||
(UUID(last_chat_id), UUID(user_id)),
|
||||
)
|
||||
last_key = cur.fetchone()
|
||||
|
||||
if last_key is None:
|
||||
return None
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
ARRAY(
|
||||
SELECT cm2.user_id
|
||||
FROM chat_members cm2
|
||||
WHERE cm2.chat_id = c.id
|
||||
ORDER BY cm2.user_id
|
||||
) AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = %s
|
||||
AND (
|
||||
%s::timestamptz IS NULL
|
||||
OR (c.created_at, c.id) >
|
||||
(%s::timestamptz, %s::uuid)
|
||||
)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT %s
|
||||
""",
|
||||
(
|
||||
UUID(user_id),
|
||||
last_key["created_at"] if last_key else None,
|
||||
last_key["created_at"] if last_key else None,
|
||||
last_key["id"] if last_key else None,
|
||||
limit + 1,
|
||||
),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [serialize_chat(row) for row in rows]
|
||||
|
||||
|
||||
def create_message(chat_id, sender_id, text, key, attachment_ids):
|
||||
# INSERT ON CONFLICT waits for a concurrent transaction on the same key.
|
||||
# READ COMMITTED's next statement sees its committed result. Both the
|
||||
# message and deduplication record commit together, or both roll back.
|
||||
with get_connection() as conn:
|
||||
with conn.transaction():
|
||||
attachments = [UUID(a) for a in attachment_ids]
|
||||
rows = conn.execute('SELECT id FROM attachments WHERE chat_id=%s AND id=ANY(%s::uuid[])', (UUID(chat_id), attachments)).fetchall()
|
||||
if len(rows) != len(attachments):
|
||||
return None
|
||||
scope = (UUID(chat_id), UUID(sender_id), key)
|
||||
row = conn.execute(
|
||||
"""INSERT INTO message_requests(chat_id, sender_id, key, text)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
ON CONFLICT (chat_id, sender_id, key) DO NOTHING
|
||||
RETURNING key""", (*scope, text)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
previous = conn.execute(
|
||||
"""SELECT m.* FROM message_requests r
|
||||
JOIN messages m ON m.id = r.message_id
|
||||
WHERE r.chat_id=%s AND r.sender_id=%s AND r.key=%s""",
|
||||
scope,
|
||||
).fetchone()
|
||||
if previous["text"] != text or previous["attachment_ids"] != attachments:
|
||||
return "conflict"
|
||||
return serialize_message(previous)
|
||||
message = conn.execute(
|
||||
"""INSERT INTO messages(id, chat_id, sender_id, text, attachment_ids)
|
||||
VALUES (%s, %s, %s, %s, %s) RETURNING *""",
|
||||
(uuid4(), UUID(chat_id), UUID(sender_id), text, attachments),
|
||||
).fetchone()
|
||||
conn.execute(
|
||||
"""UPDATE message_requests SET message_id=%s
|
||||
WHERE chat_id=%s AND sender_id=%s AND key=%s""",
|
||||
(message["id"], *scope),
|
||||
)
|
||||
return serialize_message(message)
|
||||
|
||||
|
||||
def list_messages(chat_id, limit, last_message_id=None):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
last_key = None
|
||||
|
||||
if last_message_id is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT created_at, id
|
||||
FROM messages
|
||||
WHERE chat_id = %s
|
||||
AND id = %s
|
||||
""",
|
||||
(UUID(chat_id), UUID(last_message_id)),
|
||||
)
|
||||
last_key = cur.fetchone()
|
||||
|
||||
if last_key is None:
|
||||
return None
|
||||
|
||||
# Разные формы SQL сохраняют индексный range scan и для generic plan.
|
||||
# В SQL подставляется только константа; значения остаются параметрами.
|
||||
cursor_condition = ""
|
||||
params = [UUID(chat_id)]
|
||||
if last_key is not None:
|
||||
cursor_condition = "AND (created_at, id) > (%s, %s)"
|
||||
params.extend([last_key["created_at"], last_key["id"]])
|
||||
params.append(limit + 1)
|
||||
cur.execute(
|
||||
f"""
|
||||
SELECT id, chat_id, sender_id, text, attachment_ids, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = %s
|
||||
{cursor_condition}
|
||||
ORDER BY created_at, id
|
||||
LIMIT %s
|
||||
""",
|
||||
params,
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
|
||||
return [serialize_message(row) for row in rows]
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Grade 4 orphan cleanup. Run periodically/manual; fails closed if DB is down.
|
||||
Only originals older than one hour, no committed metadata, and no active uploader.
|
||||
"""
|
||||
import json
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from .database import open_database, close_database, get_connection
|
||||
from .storage import s3, BUCKET
|
||||
|
||||
|
||||
def cleanup():
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(hours=1)
|
||||
result = dict(scanned=0, fresh=0, referenced=0, busy=0, deleted=0)
|
||||
for page in s3.get_paginator('list_objects_v2').paginate(Bucket=BUCKET, Prefix='originals/'):
|
||||
for obj in page.get('Contents', []):
|
||||
result['scanned'] += 1
|
||||
if obj['LastModified'] >= cutoff:
|
||||
result['fresh'] += 1
|
||||
continue
|
||||
key = obj['Key']
|
||||
with get_connection() as conn:
|
||||
with conn.transaction():
|
||||
locked = conn.execute('SELECT pg_try_advisory_xact_lock(hashtextextended(%s, 0)) AS locked', (key,)).fetchone()['locked']
|
||||
if not locked:
|
||||
result['busy'] += 1
|
||||
elif conn.execute('SELECT 1 FROM attachments WHERE object_key=%s', (key,)).fetchone():
|
||||
result['referenced'] += 1
|
||||
else:
|
||||
s3.delete_object(Bucket=BUCKET, Key=key)
|
||||
result['deleted'] += 1
|
||||
return result
|
||||
|
||||
if __name__ == '__main__':
|
||||
open_database()
|
||||
try:
|
||||
print(json.dumps(cleanup()))
|
||||
finally:
|
||||
close_database()
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Periodic grade 4 orphan cleanup, plus scripts/cleanup.sh for manual runs."""
|
||||
import json
|
||||
import time
|
||||
from .database import open_database
|
||||
from .cleanup import cleanup
|
||||
|
||||
open_database()
|
||||
while True:
|
||||
try:
|
||||
print(json.dumps(cleanup()), flush=True)
|
||||
except Exception:
|
||||
# Never log endpoint/credentials or underlying SDK exception contents.
|
||||
print('Cleanup unavailable; will retry in 300 seconds', flush=True)
|
||||
time.sleep(300)
|
||||
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg_pool import ConnectionPool
|
||||
|
||||
|
||||
def get_database_url() -> str:
|
||||
secret_file = os.getenv("DATABASE_URL_FILE")
|
||||
|
||||
if secret_file:
|
||||
return Path(secret_file).read_text().strip()
|
||||
|
||||
database_url = os.getenv("DATABASE_URL")
|
||||
|
||||
if database_url:
|
||||
return database_url
|
||||
|
||||
raise RuntimeError("Database connection is not configured")
|
||||
|
||||
|
||||
pool = ConnectionPool(
|
||||
conninfo=get_database_url(),
|
||||
min_size=1,
|
||||
max_size=10,
|
||||
timeout=5,
|
||||
open=False,
|
||||
kwargs={
|
||||
"row_factory": dict_row,
|
||||
"connect_timeout": 5,
|
||||
"options": "-c statement_timeout=5000",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def open_database():
|
||||
pool.open(wait=True, timeout=15)
|
||||
|
||||
|
||||
def close_database():
|
||||
pool.close()
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_connection():
|
||||
with pool.connection() as connection:
|
||||
yield connection
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Isolated image decoder: bounded address space, CPU and parent wall timeout."""
|
||||
import resource
|
||||
import sys
|
||||
import warnings
|
||||
|
||||
resource.setrlimit(resource.RLIMIT_AS, (512 * 1024**2, 512 * 1024**2))
|
||||
resource.setrlimit(resource.RLIMIT_CPU, (8, 8))
|
||||
from PIL import Image
|
||||
Image.MAX_IMAGE_PIXELS = 40_000_000
|
||||
warnings.simplefilter('error', Image.DecompressionBombWarning)
|
||||
try:
|
||||
with Image.open(sys.argv[1]) as image:
|
||||
if image.width * image.height > 40_000_000:
|
||||
sys.exit(13)
|
||||
actual = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}.get(image.format)
|
||||
if actual != sys.argv[2] or getattr(image, 'n_frames', 1) != 1:
|
||||
sys.exit(15)
|
||||
image.verify()
|
||||
with Image.open(sys.argv[1]) as image:
|
||||
image.load()
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
sys.exit(13)
|
||||
except Exception:
|
||||
sys.exit(15)
|
||||
+517
@@ -0,0 +1,517 @@
|
||||
"""Мессенджер: PostgreSQL хранит данные и сессии, Redis кеширует профили."""
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
from pathlib import Path
|
||||
import logging
|
||||
import re
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
|
||||
|
||||
from psycopg import OperationalError, Error as DatabaseError
|
||||
from psycopg_pool import PoolTimeout
|
||||
|
||||
from .auth import (
|
||||
create_token,
|
||||
format_datetime,
|
||||
hash_password,
|
||||
hash_token,
|
||||
parse_basic,
|
||||
parse_bearer,
|
||||
session_expiration,
|
||||
verify_password,
|
||||
)
|
||||
from .database import open_database, close_database, get_connection
|
||||
from .user_repository import (
|
||||
create_user as insert_user,
|
||||
create_session,
|
||||
find_session_user_cached,
|
||||
find_user_by_username,
|
||||
revoke_session,
|
||||
serialize_user,
|
||||
)
|
||||
|
||||
from .chat_repository import (
|
||||
create_chat as insert_chat,
|
||||
get_chat as find_chat,
|
||||
list_chats as find_chats,
|
||||
create_message as insert_message,
|
||||
list_messages as find_messages,
|
||||
)
|
||||
|
||||
app = FastAPI(title="MTUSI Messenger", version="1.4.0")
|
||||
# Serve the mandatory contract in Swagger, including auth and request schemas.
|
||||
OPENAPI_SCHEMA = json.loads(
|
||||
(Path(__file__).resolve().parents[1] / "contracts/openapi.json").read_text()
|
||||
)
|
||||
app.openapi = lambda: OPENAPI_SCHEMA
|
||||
|
||||
INSTANCE_ID = str(uuid4())
|
||||
|
||||
logger = logging.getLogger("uvicorn.error")
|
||||
|
||||
ERROR_CODES = {
|
||||
400: "invalid_request",
|
||||
401: "unauthorized",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
413: "payload_too_large",
|
||||
415: "unsupported_media_type",
|
||||
429: "rate_limited",
|
||||
500: "internal_error",
|
||||
503: "unavailable",
|
||||
}
|
||||
|
||||
|
||||
def error_response(request, status_code, code, message):
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content={
|
||||
"error": {
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": request.state.request_id,
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_id_middleware(request: Request, call_next):
|
||||
request.state.request_id = str(uuid4())
|
||||
try:
|
||||
response = await call_next(request)
|
||||
except Exception:
|
||||
# Логируем путь, метод и request_id, но НЕ тело сообщения.
|
||||
await run_in_threadpool(
|
||||
logger.error,
|
||||
"Unhandled error: %s %s request_id=%s",
|
||||
request.method,
|
||||
request.url.path,
|
||||
request.state.request_id,
|
||||
)
|
||||
response = error_response(
|
||||
request, 500, "internal_error", "Внутренняя ошибка сервера"
|
||||
)
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
response.headers["X-Instance-Id"] = INSTANCE_ID
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(StarletteHTTPException)
|
||||
async def http_error_handler(request: Request, exc: StarletteHTTPException):
|
||||
response = error_response(
|
||||
request,
|
||||
exc.status_code,
|
||||
ERROR_CODES.get(exc.status_code, "invalid_request"),
|
||||
str(exc.detail),
|
||||
)
|
||||
if exc.headers:
|
||||
response.headers.update(exc.headers)
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(DatabaseError)
|
||||
@app.exception_handler(PoolTimeout)
|
||||
async def database_error_handler(request: Request, exc):
|
||||
return error_response(request, 503, "unavailable", "База данных временно недоступна")
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(request: Request, exc: RequestValidationError):
|
||||
return error_response(request, 400, "invalid_request", "Некорректные данные запроса")
|
||||
|
||||
|
||||
async def read_json(request: Request):
|
||||
"""415 — только для неправильного Content-Type; 400 — для неверного JSON."""
|
||||
content_type = (
|
||||
request.headers.get("content-type", "").split(";")[0].strip().lower()
|
||||
)
|
||||
if content_type != "application/json":
|
||||
raise HTTPException(415, "Неподдерживаемый Content-Type")
|
||||
|
||||
try:
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
if len(raw) + len(chunk) > 65536:
|
||||
raise HTTPException(413, "JSON слишком большой")
|
||||
raw.extend(chunk)
|
||||
data = json.loads(raw)
|
||||
except (ValueError, UnicodeError):
|
||||
raise HTTPException(400, "Неверный JSON") from None
|
||||
|
||||
# [], строка, число, true, false, null — это корректный JSON,
|
||||
# но НЕ объект, обязательный по контракту.
|
||||
if not isinstance(data, dict):
|
||||
raise HTTPException(400, "Ожидается JSON-объект")
|
||||
return data
|
||||
|
||||
|
||||
def get_current_user(request: Request):
|
||||
token = parse_bearer(request.headers.get("Authorization"))
|
||||
if token is None:
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Требуется действующий Bearer-токен",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
try:
|
||||
user = find_session_user_cached(hash_token(token))
|
||||
except (OperationalError, PoolTimeout):
|
||||
raise HTTPException(
|
||||
503,
|
||||
"База данных временно недоступна",
|
||||
) from None
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Недействительная или истёкшая сессия",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_limit(request: Request):
|
||||
"""Проверяем длину ДО int(): 5000 цифр должны дать 400, а не 500."""
|
||||
limit_raw = request.query_params.get("limit", "50")
|
||||
if not limit_raw.isascii() or not limit_raw.isdecimal():
|
||||
raise HTTPException(400, "Неверный limit")
|
||||
|
||||
significant = limit_raw.lstrip("0")
|
||||
if not significant or len(significant) > 3:
|
||||
raise HTTPException(400, "Неверный limit")
|
||||
|
||||
limit = int(significant) # Теперь строка содержит максимум 3 цифры.
|
||||
if not 1 <= limit <= 100:
|
||||
raise HTTPException(400, "limit должен быть от 1 до 100")
|
||||
return limit
|
||||
|
||||
|
||||
def encode_cursor(first_id, last_id):
|
||||
raw = f"{first_id}|{last_id}".encode("ascii")
|
||||
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(cursor):
|
||||
try:
|
||||
if not cursor or len(cursor) > 256:
|
||||
raise ValueError("empty or too long")
|
||||
padded = cursor + "=" * (-len(cursor) % 4)
|
||||
raw = base64.b64decode(
|
||||
padded, altchars=b"-_", validate=True
|
||||
).decode("ascii")
|
||||
first_id, last_id = raw.split("|")
|
||||
return str(UUID(first_id)), str(UUID(last_id))
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
raise HTTPException(400, "Неверный cursor") from None
|
||||
|
||||
|
||||
# ---- Health ----
|
||||
|
||||
@app.get("/health/live")
|
||||
def health_live():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/health/ready")
|
||||
def health_ready():
|
||||
try:
|
||||
with get_connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
from .storage import s3, BUCKET
|
||||
s3.list_objects_v2(Bucket=BUCKET, Prefix="originals/", MaxKeys=1)
|
||||
except (OperationalError, PoolTimeout):
|
||||
raise HTTPException(503, "База данных недоступна") from None
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
# ---- Users ----
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
async def create_user(request: Request):
|
||||
data = await read_json(request)
|
||||
|
||||
if set(data) != {"username", "display_name", "password"}:
|
||||
raise HTTPException(400, "Неверные поля пользователя")
|
||||
|
||||
username = data["username"]
|
||||
display_name = data["display_name"]
|
||||
password = data["password"]
|
||||
|
||||
if not isinstance(username, str) or not re.fullmatch(
|
||||
r"[a-z0-9_]{3,32}", username
|
||||
):
|
||||
raise HTTPException(400, "Недопустимый username")
|
||||
|
||||
if (
|
||||
not isinstance(display_name, str)
|
||||
or not 1 <= len(display_name) <= 100
|
||||
or not display_name.strip()
|
||||
):
|
||||
raise HTTPException(400, "Недопустимое имя пользователя")
|
||||
|
||||
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||
raise HTTPException(400, "Пароль должен содержать 12–128 символов")
|
||||
|
||||
password_hash = await run_in_threadpool(hash_password, password)
|
||||
user = await run_in_threadpool(insert_user, username, display_name, password_hash)
|
||||
if user is None:
|
||||
raise HTTPException(409, "Username уже занят")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def get_me(request: Request):
|
||||
return get_current_user(request)
|
||||
|
||||
|
||||
@app.post("/api/v1/auth/sessions", status_code=201)
|
||||
def login(request: Request):
|
||||
credentials = parse_basic(request.headers.get("Authorization"))
|
||||
|
||||
if credentials is None:
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Неверные учётные данные",
|
||||
headers={
|
||||
"WWW-Authenticate":
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
},
|
||||
)
|
||||
|
||||
username, password = credentials
|
||||
user_row = find_user_by_username(username)
|
||||
|
||||
if user_row is None or not verify_password(
|
||||
user_row["password_hash"], password
|
||||
):
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Неверные учётные данные",
|
||||
headers={
|
||||
"WWW-Authenticate":
|
||||
'Basic realm="messenger", charset="UTF-8"'
|
||||
},
|
||||
)
|
||||
|
||||
token = create_token()
|
||||
expires_at = session_expiration()
|
||||
|
||||
create_session(user_row["id"], hash_token(token), expires_at)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": format_datetime(expires_at),
|
||||
"user": serialize_user(user_row),
|
||||
}
|
||||
|
||||
|
||||
@app.delete("/api/v1/auth/sessions/current", status_code=204)
|
||||
def logout(request: Request):
|
||||
get_current_user(request)
|
||||
token = parse_bearer(request.headers.get("Authorization"))
|
||||
|
||||
from .session_cache import invalidate_session
|
||||
|
||||
if not revoke_session(hash_token(token)):
|
||||
raise HTTPException(
|
||||
401,
|
||||
"Недействительная сессия",
|
||||
headers={"WWW-Authenticate": 'Bearer realm="messenger"'},
|
||||
)
|
||||
|
||||
invalidate_session(hash_token(token))
|
||||
|
||||
from fastapi import Response
|
||||
return Response(status_code=204)
|
||||
|
||||
|
||||
|
||||
# ---- Chats ----
|
||||
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
async def create_chat(request: Request):
|
||||
user = await run_in_threadpool(get_current_user, request)
|
||||
data = await read_json(request)
|
||||
|
||||
if set(data) != {"title", "member_ids"}:
|
||||
raise HTTPException(400, "Неверные поля чата")
|
||||
|
||||
title = data["title"]
|
||||
member_ids = data["member_ids"]
|
||||
|
||||
if not isinstance(title, str) or not 1 <= len(title) <= 100 or not title.strip():
|
||||
raise HTTPException(400, "Недопустимое название чата")
|
||||
|
||||
if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100:
|
||||
raise HTTPException(400, "Неверный список участников")
|
||||
|
||||
normalized_ids = []
|
||||
|
||||
for member_id in member_ids:
|
||||
if not isinstance(member_id, str):
|
||||
raise HTTPException(400, "Неверный ID участника")
|
||||
|
||||
try:
|
||||
normalized_ids.append(str(UUID(member_id)))
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Неверный UUID участника") from None
|
||||
|
||||
if len(normalized_ids) != len(set(normalized_ids)):
|
||||
raise HTTPException(400, "Участники повторяются")
|
||||
|
||||
if user["id"] not in normalized_ids:
|
||||
raise HTTPException(400, "Создатель должен быть участником")
|
||||
|
||||
chat = await run_in_threadpool(insert_chat, user["id"], title, normalized_ids)
|
||||
|
||||
if chat is None:
|
||||
raise HTTPException(400, "Неизвестный участник")
|
||||
|
||||
return chat
|
||||
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(request: Request):
|
||||
user = get_current_user(request)
|
||||
limit = get_limit(request)
|
||||
cursor = request.query_params.get("cursor")
|
||||
|
||||
last_chat_id = None
|
||||
|
||||
if cursor is not None:
|
||||
cursor_user_id, last_chat_id = decode_cursor(cursor)
|
||||
|
||||
if cursor_user_id != user["id"]:
|
||||
raise HTTPException(400, "Неверный cursor")
|
||||
|
||||
rows = find_chats(user["id"], limit, last_chat_id)
|
||||
|
||||
if rows is None:
|
||||
raise HTTPException(400, "Неверный cursor")
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = (
|
||||
encode_cursor(user["id"], page[-1]["id"])
|
||||
if has_more and page
|
||||
else None
|
||||
)
|
||||
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def get_chat(chat_id: str, request: Request):
|
||||
user = get_current_user(request)
|
||||
|
||||
try:
|
||||
chat_id = str(UUID(chat_id))
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Неверный UUID чата") from None
|
||||
|
||||
chat = find_chat(chat_id, user["id"])
|
||||
|
||||
if chat is None:
|
||||
raise HTTPException(404, "Чат не найден")
|
||||
|
||||
return chat
|
||||
|
||||
|
||||
# ---- Messages ----
|
||||
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
async def send_message(chat_id: str, request: Request):
|
||||
user = await run_in_threadpool(get_current_user, request)
|
||||
chat = await run_in_threadpool(get_chat, chat_id, request)
|
||||
data = await read_json(request)
|
||||
|
||||
if "text" not in data or set(data) - {"text", "attachment_ids"}:
|
||||
raise HTTPException(400, "Неверные поля сообщения")
|
||||
|
||||
text = data["text"]
|
||||
|
||||
attachment_ids = data.get("attachment_ids", [])
|
||||
if not isinstance(attachment_ids, list) or len(attachment_ids) > 10:
|
||||
raise HTTPException(400, "Неверный список вложений")
|
||||
try:
|
||||
if any(not isinstance(a, str) for a in attachment_ids):
|
||||
raise ValueError()
|
||||
attachment_ids = [str(UUID(a)) for a in attachment_ids]
|
||||
if len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
raise HTTPException(400, "Неверные ID вложений") from None
|
||||
if not isinstance(text, str) or len(text) > 4000 or (not text.strip() and not attachment_ids):
|
||||
raise HTTPException(400, "Недопустимый текст сообщения")
|
||||
|
||||
key = request.headers.get("Idempotency-Key", "")
|
||||
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key):
|
||||
raise HTTPException(400, "Неверный Idempotency-Key")
|
||||
message = await run_in_threadpool(insert_message, chat["id"], user["id"], text, key, attachment_ids)
|
||||
if message == "conflict":
|
||||
raise HTTPException(409, "Ключ использован для другого сообщения")
|
||||
|
||||
if message is None:
|
||||
raise HTTPException(404, "Чат не найден")
|
||||
|
||||
return message
|
||||
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def list_messages(chat_id: str, request: Request):
|
||||
chat = get_chat(chat_id, request)
|
||||
limit = get_limit(request)
|
||||
cursor = request.query_params.get("cursor")
|
||||
|
||||
last_message_id = None
|
||||
|
||||
if cursor is not None:
|
||||
cursor_chat_id, last_message_id = decode_cursor(cursor)
|
||||
|
||||
if cursor_chat_id != chat["id"]:
|
||||
raise HTTPException(400, "Неверный cursor")
|
||||
|
||||
rows = find_messages(chat["id"], limit, last_message_id)
|
||||
|
||||
if rows is None:
|
||||
raise HTTPException(400, "Неверный cursor")
|
||||
|
||||
has_more = len(rows) > limit
|
||||
page = rows[:limit]
|
||||
|
||||
next_cursor = (
|
||||
encode_cursor(chat["id"], page[-1]["id"])
|
||||
if has_more and page
|
||||
else None
|
||||
)
|
||||
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def start_database_pool():
|
||||
await run_in_threadpool(open_database)
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def stop_database_pool():
|
||||
await run_in_threadpool(close_database)
|
||||
|
||||
from .attachments import register
|
||||
register(app, get_current_user, get_chat)
|
||||
@@ -0,0 +1,16 @@
|
||||
"""One-shot migrations, serialized and recorded in PostgreSQL."""
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from .database import get_database_url
|
||||
|
||||
with psycopg.connect(get_database_url()) as conn:
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT pg_advisory_xact_lock(310026)")
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations(name TEXT PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW())")
|
||||
for path in sorted(Path("/app/db/migrations").glob("*.sql")):
|
||||
if not conn.execute("SELECT 1 FROM schema_migrations WHERE name=%s", (path.name,)).fetchone():
|
||||
conn.execute(path.read_text())
|
||||
conn.execute("INSERT INTO schema_migrations(name) VALUES (%s)", (path.name,))
|
||||
print("Applied", path.name, flush=True)
|
||||
else:
|
||||
print("Already applied", path.name, flush=True)
|
||||
@@ -0,0 +1,48 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import redis
|
||||
|
||||
|
||||
def get_cache_url():
|
||||
secret_file = os.getenv("CACHE_URL_FILE")
|
||||
if secret_file:
|
||||
return Path(secret_file).read_text().strip()
|
||||
return os.getenv("CACHE_URL", "redis://redis:6379/0")
|
||||
|
||||
|
||||
client = redis.Redis.from_url(
|
||||
get_cache_url(),
|
||||
socket_connect_timeout=1,
|
||||
socket_timeout=1,
|
||||
decode_responses=True,
|
||||
)
|
||||
|
||||
|
||||
def get_cached_user(token_hash):
|
||||
try:
|
||||
value = client.get("session:" + token_hash)
|
||||
return json.loads(value) if value else None
|
||||
except (redis.RedisError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def cache_user(token_hash, user, ttl):
|
||||
if ttl <= 0:
|
||||
return
|
||||
try:
|
||||
client.setex(
|
||||
"session:" + token_hash,
|
||||
ttl,
|
||||
json.dumps(user),
|
||||
)
|
||||
except redis.RedisError:
|
||||
pass
|
||||
|
||||
|
||||
def invalidate_session(token_hash):
|
||||
try:
|
||||
client.delete("session:" + token_hash)
|
||||
except redis.RedisError:
|
||||
pass
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Private S3 access; no automatic PUT retries, explicit bounded timeouts."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
|
||||
def secret(name):
|
||||
return Path(os.environ[name + '_FILE']).read_text().strip()
|
||||
|
||||
|
||||
BUCKET = os.getenv('S3_BUCKET', 'messenger-attachments')
|
||||
s3 = boto3.client(
|
||||
's3', endpoint_url=os.getenv('S3_ENDPOINT', 'http://s3:9000'),
|
||||
region_name='us-east-1', aws_access_key_id=secret('S3_ACCESS_KEY_ID'),
|
||||
aws_secret_access_key=secret('S3_SECRET_ACCESS_KEY'),
|
||||
config=Config(connect_timeout=2, read_timeout=5, retries={'total_max_attempts': 1},
|
||||
s3={'addressing_style': 'path'}),
|
||||
)
|
||||
@@ -0,0 +1,136 @@
|
||||
from uuid import uuid4
|
||||
|
||||
from psycopg.errors import UniqueViolation
|
||||
|
||||
from .database import get_connection
|
||||
|
||||
|
||||
def serialize_user(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": row["created_at"].isoformat(
|
||||
timespec="microseconds"
|
||||
).replace("+00:00", "Z"),
|
||||
}
|
||||
|
||||
|
||||
def create_user(username, display_name, password_hash):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
try:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO users (
|
||||
id, username, display_name, password_hash
|
||||
)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
RETURNING id, username, display_name, created_at
|
||||
""",
|
||||
(uuid4(), username, display_name, password_hash),
|
||||
)
|
||||
return serialize_user(cur.fetchone())
|
||||
except UniqueViolation:
|
||||
conn.rollback()
|
||||
return None
|
||||
|
||||
|
||||
def find_user_by_username(username):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, username, display_name,
|
||||
password_hash, created_at
|
||||
FROM users
|
||||
WHERE username = %s
|
||||
""",
|
||||
(username,),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def create_session(user_id, token_hash, expires_at):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sessions (
|
||||
id, user_id, token_hash, expires_at
|
||||
)
|
||||
VALUES (%s, %s, %s, %s)
|
||||
""",
|
||||
(uuid4(), user_id, token_hash, expires_at),
|
||||
)
|
||||
|
||||
|
||||
def revoke_session(token_hash):
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE sessions
|
||||
SET revoked_at = NOW()
|
||||
WHERE token_hash = %s
|
||||
AND revoked_at IS NULL
|
||||
AND expires_at > NOW()
|
||||
RETURNING id
|
||||
""",
|
||||
(token_hash,),
|
||||
)
|
||||
return cur.fetchone() is not None
|
||||
|
||||
|
||||
def find_session_user_cached(token_hash):
|
||||
from datetime import datetime, timezone
|
||||
from .session_cache import cache_user, get_cached_user
|
||||
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT
|
||||
s.user_id,
|
||||
s.expires_at
|
||||
FROM sessions s
|
||||
WHERE s.token_hash = %s
|
||||
AND s.revoked_at IS NULL
|
||||
AND s.expires_at > NOW()
|
||||
""",
|
||||
(token_hash,),
|
||||
)
|
||||
session = cur.fetchone()
|
||||
|
||||
if session is None:
|
||||
return None
|
||||
|
||||
cached = get_cached_user(token_hash)
|
||||
|
||||
if cached is not None and str(cached.get("id")) == str(session["user_id"]):
|
||||
return cached
|
||||
|
||||
with get_connection() as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = %s
|
||||
""",
|
||||
(session["user_id"],),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
|
||||
if row is None:
|
||||
return None
|
||||
|
||||
user = serialize_user(row)
|
||||
ttl = int(
|
||||
(session["expires_at"] - datetime.now(timezone.utc)).total_seconds()
|
||||
)
|
||||
|
||||
if ttl > 0:
|
||||
cache_user(token_hash, user, ttl)
|
||||
|
||||
return user
|
||||
Reference in New Issue
Block a user