forked from mtusi2026/mtusi2026lab2
lab2 complete
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
import bcrypt
|
||||
import base64
|
||||
import secrets
|
||||
import os
|
||||
|
||||
from datetime import timedelta
|
||||
from fastapi import APIRouter, Request, status
|
||||
from ..exceptions import ApiException
|
||||
from ..db import get_pool
|
||||
from ..utils import get_utc_now, authenticate_user, format_iso
|
||||
|
||||
|
||||
router = APIRouter(tags=["auth"])
|
||||
|
||||
SESSION_TTL_SECONDS = int(os.getenv("SESSION_TTL_SECONDS", "3600"))
|
||||
|
||||
@router.post("/auth/sessions", status_code=status.HTTP_201_CREATED)
|
||||
async def create_session(request: Request):
|
||||
auth = request.headers.get("Authorization")
|
||||
auth_err_headers = {"WWW-Authenticate": 'Basic realm="messenger"'}
|
||||
|
||||
if not auth or not auth.startswith("Basic "):
|
||||
raise ApiException(401, "unauthorized", "Missing Basic auth", headers=auth_err_headers)
|
||||
|
||||
try:
|
||||
decoded = base64.b64decode(auth.split(" ", 1)[1]).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except Exception:
|
||||
raise ApiException(401, "unauthorized", "Invalid Basic format", headers=auth_err_headers)
|
||||
|
||||
pool = get_pool()
|
||||
user = await pool.fetchrow("SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1", username)
|
||||
if not user:
|
||||
raise ApiException(401, "unauthorized", "Invalid credentials", headers=auth_err_headers)
|
||||
|
||||
|
||||
if not bcrypt.checkpw(password.encode("utf-8"), user["password_hash"].encode("utf-8")):
|
||||
raise ApiException(401, "unauthorized", "Invalid credentials", headers=auth_err_headers)
|
||||
|
||||
token = secrets.token_urlsafe(32)
|
||||
now = get_utc_now()
|
||||
expires_at = now + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
|
||||
await pool.execute(
|
||||
"INSERT INTO sessions (token, user_id, expires_at, revoked) VALUES ($1, $2, $3, FALSE)",
|
||||
token, user["id"], expires_at
|
||||
)
|
||||
|
||||
return {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": format_iso(expires_at),
|
||||
"user": {
|
||||
"id": str(user["id"]),
|
||||
"username": user["username"],
|
||||
"display_name": user["display_name"],
|
||||
"created_at": format_iso(user["created_at"])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/auth/sessions/current", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_current_session(request: Request):
|
||||
await authenticate_user(request)
|
||||
token = request.state.current_token
|
||||
pool = get_pool()
|
||||
await pool.execute("UPDATE sessions SET revoked = TRUE WHERE token = $1", token)
|
||||
return None
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, Request, status
|
||||
from ..models import CreateChatRequest
|
||||
from ..utils import authenticate_user, validate_uuid, format_iso, get_utc_now
|
||||
from ..exceptions import ApiException
|
||||
from ..db import get_pool
|
||||
|
||||
router = APIRouter(tags=["chats"])
|
||||
|
||||
@router.post("/chats", status_code=status.HTTP_201_CREATED)
|
||||
async def create_chat(body: CreateChatRequest, request: Request):
|
||||
caller_id = await authenticate_user(request)
|
||||
|
||||
if not body.title.strip() or len(body.title) > 128:
|
||||
raise ApiException(400, "invalid_request", "Invalid title")
|
||||
|
||||
if len(body.member_ids) != len(set(body.member_ids)):
|
||||
raise ApiException(400, "invalid_request", "Duplicate member_ids")
|
||||
|
||||
if caller_id not in body.member_ids:
|
||||
raise ApiException(400, "invalid_request", "Caller must be included in member_ids")
|
||||
|
||||
pool = get_pool()
|
||||
member_uuids = []
|
||||
for mid in body.member_ids:
|
||||
validate_uuid(mid)
|
||||
u = uuid.UUID(mid)
|
||||
exists = await pool.fetchval("SELECT id FROM users WHERE id = $1", u)
|
||||
if not exists:
|
||||
raise ApiException(400, "invalid_request", f"Member {mid} not found")
|
||||
member_uuids.append(u)
|
||||
|
||||
cid = uuid.uuid4()
|
||||
now = get_utc_now()
|
||||
|
||||
|
||||
async with pool.acquire() as conn:
|
||||
async with conn.transaction():
|
||||
await conn.execute("INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)", cid, body.title, now)
|
||||
for m in member_uuids:
|
||||
await conn.execute("INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)", cid, m)
|
||||
|
||||
return {
|
||||
"id": str(cid),
|
||||
"title": body.title,
|
||||
"member_ids": body.member_ids,
|
||||
"created_at": format_iso(now)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/chats")
|
||||
async def list_chats(request: Request, limit: int = 50):
|
||||
caller_id = await authenticate_user(request)
|
||||
if limit < 1 or limit > 100:
|
||||
raise ApiException(400, "invalid_request", "Limit must be between 1 and 100")
|
||||
|
||||
pool = get_pool()
|
||||
rows = await pool.fetch("""
|
||||
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON c.id = cm.chat_id
|
||||
WHERE c.id IN (SELECT chat_id FROM chat_members WHERE user_id = $1)
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
ORDER BY c.created_at ASC, c.id ASC
|
||||
LIMIT $2
|
||||
""", uuid.UUID(caller_id), limit)
|
||||
|
||||
items = [
|
||||
{
|
||||
"id": str(r["id"]),
|
||||
"title": r["title"],
|
||||
"member_ids": list(r["member_ids"]),
|
||||
"created_at": format_iso(r["created_at"])
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
result = {
|
||||
"items": items,
|
||||
"next_cursor": None
|
||||
}
|
||||
|
||||
print("API RESPONSE:", result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
|
||||
@router.get("/chats/{chat_id}")
|
||||
async def get_chat(chat_id: str, request: Request):
|
||||
caller_id = await authenticate_user(request)
|
||||
validate_uuid(chat_id)
|
||||
|
||||
pool = get_pool()
|
||||
row = await pool.fetchrow("""
|
||||
SELECT c.id, c.title, c.created_at, array_agg(cm.user_id::text) as member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON c.id = cm.chat_id
|
||||
WHERE c.id = $1
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
""", uuid.UUID(chat_id))
|
||||
|
||||
if not row or caller_id not in row["member_ids"]:
|
||||
raise ApiException(404, "not_found", "Chat not found")
|
||||
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": list(row["member_ids"]),
|
||||
"created_at": format_iso(row["created_at"])
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import uuid
|
||||
import json
|
||||
import base64
|
||||
|
||||
|
||||
from datetime import timezone, datetime
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, status, Request
|
||||
from ..utils import authenticate_user, validate_uuid, get_utc_now, format_iso
|
||||
from ..exceptions import ApiException
|
||||
from ..models import SendMessageRequest
|
||||
from ..db import get_pool
|
||||
|
||||
router = APIRouter(tags=["messages"])
|
||||
|
||||
|
||||
@router.post("/chats/{chat_id}/messages", status_code=status.HTTP_201_CREATED)
|
||||
async def send_message(chat_id: str, body: SendMessageRequest, request: Request):
|
||||
caller_id = await authenticate_user(request)
|
||||
validate_uuid(chat_id)
|
||||
|
||||
pool = get_pool()
|
||||
is_member = await pool.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
uuid.UUID(chat_id), uuid.UUID(caller_id)
|
||||
)
|
||||
if not is_member:
|
||||
raise ApiException(404, "not_found", "Chat not found")
|
||||
|
||||
if not body.text.strip() or len(body.text) > 4000:
|
||||
raise ApiException(400, "invalid_request", "Invalid text")
|
||||
|
||||
mid = uuid.uuid4()
|
||||
now = get_utc_now()
|
||||
|
||||
await pool.execute(
|
||||
"INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)",
|
||||
mid, uuid.UUID(chat_id), uuid.UUID(caller_id), body.text, now
|
||||
)
|
||||
|
||||
return {
|
||||
"id": str(mid),
|
||||
"chat_id": chat_id,
|
||||
"sender_id": caller_id,
|
||||
"text": body.text,
|
||||
"created_at": format_iso(now)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/chats/{chat_id}/messages")
|
||||
async def get_messages(
|
||||
chat_id: str,
|
||||
request: Request,
|
||||
limit: int = 50,
|
||||
cursor: Optional[str] = None
|
||||
):
|
||||
caller_id = await authenticate_user(request)
|
||||
validate_uuid(chat_id)
|
||||
|
||||
pool = get_pool()
|
||||
chat_uuid = uuid.UUID(chat_id)
|
||||
|
||||
is_member = await pool.fetchval(
|
||||
"SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2",
|
||||
chat_uuid,
|
||||
uuid.UUID(caller_id)
|
||||
)
|
||||
|
||||
if not is_member:
|
||||
raise ApiException(404, "not_found", "Chat not found")
|
||||
|
||||
if limit < 1 or limit > 100:
|
||||
raise ApiException(400, "invalid_request", "Invalid limit")
|
||||
|
||||
cursor_time = None
|
||||
cursor_id = None
|
||||
|
||||
if cursor is not None:
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(
|
||||
cursor + "=" * (-len(cursor) % 4)
|
||||
)
|
||||
data = json.loads(decoded)
|
||||
|
||||
cursor_time = datetime.fromisoformat(
|
||||
data["created_at"].replace("Z", "+00:00")
|
||||
)
|
||||
cursor_id = uuid.UUID(data["id"])
|
||||
|
||||
if cursor_time.tzinfo is None:
|
||||
raise ValueError()
|
||||
|
||||
cursor_time = cursor_time.astimezone(timezone.utc)
|
||||
|
||||
except (ValueError, KeyError, TypeError, UnicodeDecodeError):
|
||||
raise ApiException(
|
||||
400, "invalid_request", "Invalid cursor"
|
||||
)
|
||||
|
||||
rows = await pool.fetch(
|
||||
"""
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND (
|
||||
$2::timestamptz IS NULL
|
||||
OR (created_at, id) > ($2::timestamptz, $3::uuid)
|
||||
)
|
||||
ORDER BY created_at ASC, id ASC
|
||||
LIMIT $4
|
||||
""",
|
||||
chat_uuid,
|
||||
cursor_time,
|
||||
cursor_id,
|
||||
limit + 1
|
||||
)
|
||||
|
||||
has_more = len(rows) > limit
|
||||
rows = rows[:limit]
|
||||
|
||||
items = [
|
||||
{
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": format_iso(row["created_at"])
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
next_cursor = None
|
||||
|
||||
if has_more and rows:
|
||||
last = rows[-1]
|
||||
|
||||
cursor_data = {
|
||||
"created_at": format_iso(last["created_at"]),
|
||||
"id": str(last["id"])
|
||||
}
|
||||
|
||||
next_cursor = base64.urlsafe_b64encode(
|
||||
json.dumps(cursor_data).encode("utf-8")
|
||||
).decode("ascii").rstrip("=")
|
||||
|
||||
return {
|
||||
"items": items,
|
||||
"next_cursor": next_cursor
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from . import auth, chats, users, messages
|
||||
|
||||
api_v1_router = APIRouter(prefix="/api/v1")
|
||||
|
||||
api_v1_router.include_router(auth.router)
|
||||
api_v1_router.include_router(chats.router)
|
||||
api_v1_router.include_router(users.router)
|
||||
api_v1_router.include_router(messages.router)
|
||||
@@ -0,0 +1,58 @@
|
||||
import bcrypt
|
||||
import uuid
|
||||
|
||||
from fastapi import APIRouter, status, Request
|
||||
from ..utils import authenticate_user, get_utc_now, USERNAME_REGEX, format_iso
|
||||
from ..db import get_pool
|
||||
from ..exceptions import ApiException
|
||||
from ..models import CreateUserRequest
|
||||
|
||||
router = APIRouter(tags=["users"])
|
||||
|
||||
@router.post("/users", status_code=status.HTTP_201_CREATED)
|
||||
async def create_user(body: CreateUserRequest):
|
||||
if not USERNAME_REGEX.match(body.username):
|
||||
raise ApiException(400, "invalid_request", "Invalid username format")
|
||||
if not body.password or len(body.password) < 4:
|
||||
raise ApiException(400, "invalid_request", "Password too short")
|
||||
|
||||
display_name = body.display_name if body.display_name is not None else body.username
|
||||
if len(display_name) < 1 or len(display_name) > 100 or not display_name.strip():
|
||||
raise ApiException(400, "invalid_request", "Invalid display_name")
|
||||
|
||||
pool = get_pool()
|
||||
existing = await pool.fetchval("SELECT id FROM users WHERE username = $1", body.username)
|
||||
if existing:
|
||||
raise ApiException(409, "conflict", "Username already taken")
|
||||
|
||||
|
||||
salt = bcrypt.gensalt()
|
||||
pw_hash = bcrypt.hashpw(body.password.encode("utf-8"), salt).decode("utf-8")
|
||||
|
||||
uid = uuid.uuid4()
|
||||
now = get_utc_now()
|
||||
|
||||
await pool.execute(
|
||||
"INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)",
|
||||
uid, body.username, display_name, pw_hash, now
|
||||
)
|
||||
|
||||
return {
|
||||
"id": str(uid),
|
||||
"username": body.username,
|
||||
"display_name": display_name,
|
||||
"created_at": format_iso(now)
|
||||
}
|
||||
|
||||
|
||||
@router.get("/users/me")
|
||||
async def get_me(request: Request):
|
||||
caller_id = await authenticate_user(request)
|
||||
pool = get_pool()
|
||||
row = await pool.fetchrow("SELECT id, username, display_name, created_at FROM users WHERE id = $1", uuid.UUID(caller_id))
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": format_iso(row["created_at"])
|
||||
}
|
||||
Reference in New Issue
Block a user