This commit is contained in:
Getlles
2026-11-05 17:31:01 +03:00
parent 4080e2110a
commit 99079c94c9
5 changed files with 203 additions and 109 deletions
+74 -80
View File
@@ -14,11 +14,16 @@ from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from pydantic import BaseModel, Field, field_validator, ConfigDict
import redis
app = FastAPI(title="MTUSI Messenger — lab2", version="1.2.0")
DATABASE_URL = os.getenv("DATABASE_URL", "postgresql://postgres:postgres@postgres:5432/messenger")
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
REDIS_URL = os.getenv("REDIS_URL", "redis://redis:6379/0")
redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
def get_db_connection():
conn = psycopg2.connect(DATABASE_URL, cursor_factory=psycopg2.extras.RealDictCursor)
return conn
@@ -52,12 +57,6 @@ def init_db():
created_at TIMESTAMPTZ NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_messages_chat_pagination ON messages(chat_id, created_at, id);
CREATE TABLE IF NOT EXISTS sessions (
token VARCHAR(128) PRIMARY KEY,
user_id UUID REFERENCES users(id) ON DELETE CASCADE,
expires_at TIMESTAMPTZ NOT NULL,
created_at TIMESTAMPTZ NOT NULL
);
""")
conn.commit()
conn.close()
@@ -184,8 +183,9 @@ def health_ready(response: Response):
try:
conn = get_db_connection()
conn.close()
redis_client.ping()
except Exception:
raise HTTPException(status_code=503, detail="Database unavailable")
raise HTTPException(status_code=503, detail="Database or Redis unavailable")
return {"status": "ok"}
@app.post("/api/v1/users", status_code=201)
@@ -256,19 +256,12 @@ def create_session(authorization: Optional[str] = Header(None), response: Respon
headers={"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
)
token = secrets.token_urlsafe(48) # >= 256 bits entropy
token = secrets.token_urlsafe(48)
redis_client.setex(f"session:{token}", SESSION_TTL_SECONDS, user['id'])
expires_at = datetime.now(timezone.utc) + timedelta(seconds=SESSION_TTL_SECONDS)
expires_at_str = expires_at.isoformat().replace("+00:00", "Z")
created_at_str = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
with conn.cursor() as cur:
cur.execute(
"INSERT INTO sessions (token, user_id, expires_at, created_at) VALUES (%s, %s, %s, %s)",
(token, user['id'], expires_at_str, created_at_str)
)
conn.commit()
conn.close()
return {
"token": token,
"token_type": "Bearer",
@@ -290,30 +283,28 @@ def get_current_user_from_token(authorization: Optional[str] = Header(None)) ->
)
token = authorization.split(" ")[1]
try:
user_id = redis_client.get(f"session:{token}")
except Exception:
raise HTTPException(status_code=503, detail="Session store unavailable")
if not user_id:
raise HTTPException(
status_code=401,
detail="Invalid or expired session token",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
conn = get_db_connection()
with conn.cursor() as cur:
cur.execute("""
SELECT u.*, s.expires_at FROM sessions s
JOIN users u ON s.user_id = u.id
WHERE s.token = %s
""", (token,))
cur.execute("SELECT * FROM users WHERE id = %s", (user_id,))
row = cur.fetchone()
conn.close()
if not row:
raise HTTPException(
status_code=401,
detail="Invalid session token",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
expires_at = row['expires_at']
if isinstance(expires_at, str):
expires_at = datetime.fromisoformat(expires_at.replace("Z", "+00:00"))
if expires_at < datetime.now(timezone.utc):
raise HTTPException(
status_code=401,
detail="Session expired",
detail="User not found",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
@@ -325,23 +316,33 @@ def get_current_user_from_token(authorization: Optional[str] = Header(None)) ->
}
@app.delete("/api/v1/auth/sessions/current", status_code=204)
def revoke_session(response: Response, authorization: Optional[str] = Header(None)):
def revoke_session(authorization: Optional[str] = Header(None)):
req_id = generate_request_id()
if not authorization or not authorization.startswith("Bearer "):
raise HTTPException(
status_code=401,
detail="Unauthorized",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
user = get_current_user_from_token(authorization)
token = authorization.split(" ")[1]
deleted = redis_client.delete(f"session:{token}")
conn = get_db_connection()
try:
with conn.cursor() as cur:
cur.execute("DELETE FROM sessions WHERE token = %s", (token,))
conn.commit()
finally:
conn.close()
if not deleted:
raise HTTPException(
status_code=401,
detail="Invalid session token",
headers={"WWW-Authenticate": 'Bearer realm="messenger"'}
)
return Response(
status_code=204,
headers={"X-Request-Id": req_id, "X-Instance-Id": "instance-1"},
headers={
"X-Request-Id": req_id,
"X-Instance-Id": "instance-1"
},
)
@app.get("/api/v1/users/me")
@@ -425,7 +426,6 @@ def list_chats(limit: int = 50, cursor: Optional[str] = None, response: Response
user_chats = []
for r in rows:
# Get members for each chat
conn = get_db_connection()
with conn.cursor() as cur:
cur.execute("SELECT user_id FROM chat_members WHERE chat_id = %s", (r['id'],))
@@ -538,29 +538,40 @@ def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
chat_id_str = str(chat_id)
conn = get_db_connection()
with conn.cursor() as cur:
cur.execute("""
SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s
""", (chat_id_str, user["id"]))
if not cur.fetchone():
conn.close()
raise HTTPException(status_code=404, detail="Chat not found")
if limit < 1 or limit > 100:
conn.close()
raise HTTPException(status_code=400, detail="Invalid limit")
query = """
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = %s
"""
params = [chat_id_str]
if cursor:
try:
parts = cursor.split("_")
c_time, c_id = parts[0], parts[1]
query += " AND (created_at, id) > (%s, %s)"
params.extend([c_time, c_id])
except Exception:
conn.close()
raise HTTPException(status_code=400, detail="Invalid cursor format")
query += " ORDER BY created_at ASC, id ASC LIMIT %s"
params.append(limit + 1)
with conn.cursor() as cur:
cur.execute("""
SELECT id, chat_id, sender_id, text, created_at FROM messages
WHERE chat_id = %s
ORDER BY created_at ASC, id ASC
""", (chat_id_str,))
msgs = cur.fetchall()
cur.execute(query, tuple(params))
rows = cur.fetchall()
conn.close()
has_next = len(rows) > limit
page_items = rows[:limit]
formatted_msgs = []
for m in msgs:
for m in page_items:
formatted_msgs.append({
"id": m['id'],
"chat_id": m['chat_id'],
@@ -569,26 +580,9 @@ def list_messages(chat_id: UUID, limit: int = 50, cursor: Optional[str] = None,
"created_at": m['created_at'].isoformat().replace("+00:00", "Z") if isinstance(m['created_at'], datetime) else m['created_at']
})
start_idx = 0
if cursor:
try:
parts = cursor.split("_")
c_time, c_id = parts[0], parts[1]
found = False
for idx, m in enumerate(formatted_msgs):
if (m["created_at"], m["id"]) >= (c_time, c_id):
start_idx = idx if (m["created_at"], m["id"]) > (c_time, c_id) else idx + 1
found = True
break
if not found:
start_idx = len(formatted_msgs)
except Exception:
raise HTTPException(status_code=400, detail="Invalid cursor format")
page_items = formatted_msgs[start_idx:start_idx + limit]
next_cursor = None
if start_idx + limit < len(formatted_msgs):
last = page_items[-1]
if has_next and formatted_msgs:
last = formatted_msgs[-1]
next_cursor = f"{last['created_at']}_{last['id']}"
return {"items": page_items, "next_cursor": next_cursor}
return {"items": formatted_msgs, "next_cursor": next_cursor}