forked from mtusi2026/mtusi2026lab2
ЛР 2: PostgreSQL и сессии, оценка 3
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import hashlib
|
||||
from fastapi import Header, HTTPException
|
||||
from app.storage import db
|
||||
|
||||
BEARER_CHALLENGE = {"WWW-Authenticate": 'Bearer realm="messenger"'}
|
||||
BASIC_CHALLENGE = {"WWW-Authenticate": 'Basic realm="messenger", charset="UTF-8"'}
|
||||
|
||||
|
||||
def unauthorized(basic=False):
|
||||
raise HTTPException(status_code=401, detail="Unauthorized", headers=BASIC_CHALLENGE if basic else BEARER_CHALLENGE)
|
||||
|
||||
|
||||
def current_user(authorization: str | None = Header(default=None)):
|
||||
if not authorization or not authorization.startswith("Bearer "):
|
||||
unauthorized()
|
||||
token = authorization[7:]
|
||||
if not token or " " in token:
|
||||
unauthorized()
|
||||
with db() as conn:
|
||||
user = conn.execute("""SELECT u.id,u.username,u.display_name,u.created_at FROM sessions s
|
||||
JOIN users u ON u.id=s.user_id
|
||||
WHERE s.token_hash=%s AND s.expires_at > now()""",
|
||||
(hashlib.sha256(token.encode()).hexdigest(),)).fetchone()
|
||||
if user is None:
|
||||
unauthorized()
|
||||
return user
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from uuid import uuid4
|
||||
from fastapi import FastAPI, Request, HTTPException
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from psycopg import OperationalError
|
||||
from app.routers import users,chats,messages
|
||||
from app.storage import db,migrate
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
migrate()
|
||||
yield
|
||||
|
||||
app=FastAPI(lifespan=lifespan)
|
||||
|
||||
|
||||
def error_code(status):
|
||||
return {400:'invalid_request',401:'unauthorized',404:'not_found',409:'conflict',503:'unavailable'}.get(status,'internal_error')
|
||||
|
||||
|
||||
def error_response(request,status,message,headers=None):
|
||||
result=JSONResponse(status_code=status,content={'error':{
|
||||
'code':error_code(status),'message':message,'request_id':request.state.request_id}},headers=headers)
|
||||
result.headers['X-Request-Id']=request.state.request_id
|
||||
return result
|
||||
|
||||
|
||||
@app.middleware('http')
|
||||
async def add_request_id(request:Request,call_next):
|
||||
request.state.request_id=str(uuid4())
|
||||
try:
|
||||
response=await call_next(request)
|
||||
except OperationalError:
|
||||
response=error_response(request,503,'Database unavailable')
|
||||
except Exception:
|
||||
response=error_response(request,500,'Internal server error')
|
||||
response.headers['X-Request-Id']=request.state.request_id
|
||||
return response
|
||||
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error(request,exc):
|
||||
return error_response(request,exc.status_code,str(exc.detail),exc.headers)
|
||||
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request,exc):
|
||||
return error_response(request,400,'Invalid request')
|
||||
|
||||
app.include_router(users.router)
|
||||
app.include_router(chats.router)
|
||||
app.include_router(messages.router)
|
||||
|
||||
@app.get('/health/live')
|
||||
def live():
|
||||
return {'status':'ok'}
|
||||
|
||||
@app.get('/health/ready')
|
||||
def ready():
|
||||
with db() as conn:
|
||||
conn.execute('SELECT 1')
|
||||
return {'status':'ok'}
|
||||
@@ -0,0 +1,39 @@
|
||||
from datetime import datetime
|
||||
from app.models.time_format import utc_z
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, field_serializer
|
||||
|
||||
class CreateChat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
title: str = Field(min_length=1, max_length=100)
|
||||
member_ids: list[UUID] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("title")
|
||||
@classmethod
|
||||
def title_must_not_be_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("title must not be blank")
|
||||
return value
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def member_ids_must_be_unique(cls, value: list[UUID]) -> list[UUID]:
|
||||
if len(value) != len(set(value)):
|
||||
raise ValueError("member_ids must be unique")
|
||||
return value
|
||||
|
||||
class Chat(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
title: str
|
||||
member_ids: list[UUID]
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at", when_used="json")
|
||||
def serialize_created_at(self, value: datetime) -> str:
|
||||
return utc_z(value)
|
||||
|
||||
class ChatPage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
items: list[Chat]
|
||||
next_cursor: str | None
|
||||
@@ -0,0 +1,33 @@
|
||||
from datetime import datetime
|
||||
from app.models.time_format import utc_z
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, field_serializer
|
||||
|
||||
class CreateMessage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
text: str = Field(min_length=1, max_length=4000)
|
||||
|
||||
@field_validator("text")
|
||||
@classmethod
|
||||
def text_must_not_be_blank(cls, value: str) -> str:
|
||||
if not value.strip():
|
||||
raise ValueError("text must not be blank")
|
||||
return value
|
||||
|
||||
class Message(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at", when_used="json")
|
||||
def serialize_created_at(self, value: datetime) -> str:
|
||||
return utc_z(value)
|
||||
|
||||
class MessagePage(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
items: list[Message]
|
||||
next_cursor: str | None
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Contract requires RFC3339 UTC timestamps with a literal Z suffix."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
|
||||
def utc_z(value: datetime) -> str:
|
||||
if value.tzinfo is None:
|
||||
# Database columns are TIMESTAMPTZ, but keep the serializer defensive.
|
||||
value = value.replace(tzinfo=timezone.utc)
|
||||
return value.astimezone(timezone.utc).isoformat().replace('+00:00', 'Z')
|
||||
@@ -0,0 +1,28 @@
|
||||
from datetime import datetime
|
||||
from app.models.time_format import utc_z
|
||||
from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, field_serializer
|
||||
|
||||
class CreateUser(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
username: str = Field(pattern=r"^[a-z0-9_]{3,32}$")
|
||||
display_name: str = Field(min_length=1, max_length=100)
|
||||
password: str = Field(min_length=12, max_length=128)
|
||||
|
||||
@field_validator("display_name")
|
||||
@classmethod
|
||||
def nonempty(cls, value):
|
||||
if not value.strip():
|
||||
raise ValueError("Blank display name")
|
||||
return value
|
||||
|
||||
class User(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
id: UUID
|
||||
username: str
|
||||
display_name: str
|
||||
created_at: datetime
|
||||
|
||||
@field_serializer("created_at", when_used="json")
|
||||
def serialize_created_at(self, value: datetime) -> str:
|
||||
return utc_z(value)
|
||||
@@ -0,0 +1,52 @@
|
||||
from uuid import UUID, uuid4
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from app.dependencies import current_user
|
||||
from app.models.chats import Chat, ChatPage, CreateChat
|
||||
from app.storage import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def get_chat_row(conn, chat_id, user_id):
|
||||
return conn.execute("""SELECT c.id,c.title,c.created_at FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s""",
|
||||
(chat_id,user_id)).fetchone()
|
||||
|
||||
|
||||
def chat_output(conn,row):
|
||||
members=conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id',(row['id'],)).fetchall()
|
||||
return {**row, 'member_ids':[m['user_id'] for m in members]}
|
||||
|
||||
|
||||
@router.post('/api/v1/chats', response_model=Chat, status_code=201)
|
||||
def create_chat(payload:CreateChat,user=Depends(current_user)):
|
||||
if user['id'] not in payload.member_ids:
|
||||
raise HTTPException(status_code=400,detail='Creator must be a chat member')
|
||||
with db() as conn:
|
||||
rows=conn.execute('SELECT id FROM users WHERE id = ANY(%s)',(payload.member_ids,)).fetchall()
|
||||
if len(rows)!=len(payload.member_ids):
|
||||
raise HTTPException(status_code=400,detail='Unknown member')
|
||||
chat=conn.execute('INSERT INTO chats(id,title) VALUES (%s,%s) RETURNING id,title,created_at',
|
||||
(uuid4(),payload.title)).fetchone()
|
||||
for member in payload.member_ids:
|
||||
conn.execute('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)',(chat['id'],member))
|
||||
return chat_output(conn,chat)
|
||||
|
||||
|
||||
@router.get('/api/v1/chats',response_model=ChatPage)
|
||||
def list_chats(limit:int=Query(default=50,ge=1,le=100),user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
rows=conn.execute("""SELECT c.id,c.title,c.created_at FROM chats c
|
||||
JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=%s
|
||||
ORDER BY c.created_at,c.id LIMIT %s""",(user['id'],limit+1)).fetchall()
|
||||
items=[chat_output(conn,row) for row in rows[:limit]]
|
||||
return {'items':items,'next_cursor':None}
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}',response_model=Chat)
|
||||
def get_chat(chat_id:UUID,user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
row=get_chat_row(conn,chat_id,user['id'])
|
||||
if row is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
return chat_output(conn,row)
|
||||
@@ -0,0 +1,60 @@
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
from datetime import datetime
|
||||
from uuid import UUID,uuid4
|
||||
from fastapi import APIRouter,Depends,HTTPException,Query
|
||||
from app.dependencies import current_user
|
||||
from app.models.messages import CreateMessage,Message,MessagePage
|
||||
from app.routers.chats import get_chat_row
|
||||
from app.storage import db
|
||||
|
||||
router=APIRouter()
|
||||
|
||||
|
||||
def encode_cursor(chat_id,row):
|
||||
raw=json.dumps({'chat_id':str(chat_id),'created_at':row['created_at'].isoformat(),'id':str(row['id'])}).encode()
|
||||
return base64.urlsafe_b64encode(raw).decode().rstrip('=')
|
||||
|
||||
|
||||
def decode_cursor(chat_id,cursor):
|
||||
try:
|
||||
raw=base64.b64decode(cursor+'='*(-len(cursor)%4),altchars=b'-_',validate=True)
|
||||
data=json.loads(raw)
|
||||
ts=datetime.fromisoformat(data['created_at'])
|
||||
ident=UUID(data['id'])
|
||||
if data['chat_id']!=str(chat_id) or ts.tzinfo is None:
|
||||
raise ValueError('Wrong cursor')
|
||||
return ts,ident
|
||||
except (ValueError,KeyError,TypeError,UnicodeDecodeError,binascii.Error):
|
||||
raise HTTPException(status_code=400,detail='Invalid cursor')
|
||||
|
||||
|
||||
@router.post('/api/v1/chats/{chat_id}/messages',response_model=Message,status_code=201)
|
||||
def create_message(chat_id:UUID,payload:CreateMessage,user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
if get_chat_row(conn,chat_id,user['id']) is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
row=conn.execute("""INSERT INTO messages(id,chat_id,sender_id,text)
|
||||
VALUES (%s,%s,%s,%s) RETURNING id,chat_id,sender_id,text,created_at""",
|
||||
(uuid4(),chat_id,user['id'],payload.text)).fetchone()
|
||||
return row
|
||||
|
||||
|
||||
@router.get('/api/v1/chats/{chat_id}/messages',response_model=MessagePage)
|
||||
def list_messages(chat_id:UUID,limit:int=Query(default=50,ge=1,le=100),
|
||||
cursor:str|None=Query(default=None,min_length=1),user=Depends(current_user)):
|
||||
with db() as conn:
|
||||
if get_chat_row(conn,chat_id,user['id']) is None:
|
||||
raise HTTPException(status_code=404,detail='Chat not found')
|
||||
if cursor is not None:
|
||||
ts,ident=decode_cursor(chat_id,cursor)
|
||||
rows=conn.execute("""SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=%s AND (created_at,id)>(%s,%s)
|
||||
ORDER BY created_at,id LIMIT %s""",(chat_id,ts,ident,limit+1)).fetchall()
|
||||
else:
|
||||
rows=conn.execute("""SELECT id,chat_id,sender_id,text,created_at FROM messages
|
||||
WHERE chat_id=%s ORDER BY created_at,id LIMIT %s""",(chat_id,limit+1)).fetchall()
|
||||
items=rows[:limit]
|
||||
next_cursor=encode_cursor(chat_id,items[-1]) if len(rows)>limit else None
|
||||
return {'items':items,'next_cursor':next_cursor}
|
||||
@@ -0,0 +1,78 @@
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import hmac
|
||||
import os
|
||||
import secrets
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from uuid import uuid4
|
||||
from fastapi import APIRouter, Depends, Header, HTTPException, Response
|
||||
from psycopg.errors import UniqueViolation
|
||||
from app.dependencies import current_user, unauthorized
|
||||
from app.models.users import CreateUser, User
|
||||
from app.models.time_format import utc_z
|
||||
from app.storage import db
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def password_hash(password):
|
||||
salt = os.urandom(16)
|
||||
derived = hashlib.scrypt(password.encode('utf-8'), salt=salt, n=2**14, r=8, p=1, dklen=32)
|
||||
return 'scrypt$' + salt.hex() + '$' + derived.hex()
|
||||
|
||||
|
||||
def verify_password(password, encoded):
|
||||
try:
|
||||
_, salt_hex, expected_hex = encoded.split('$')
|
||||
actual = hashlib.scrypt(password.encode('utf-8'),salt=bytes.fromhex(salt_hex),n=2**14,r=8,p=1,dklen=32)
|
||||
return hmac.compare_digest(actual, bytes.fromhex(expected_hex))
|
||||
except (ValueError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
@router.post('/api/v1/users', response_model=User, status_code=201)
|
||||
def register_user(payload: CreateUser):
|
||||
with db() as conn:
|
||||
try:
|
||||
user = conn.execute("""INSERT INTO users(id,username,display_name,password_hash)
|
||||
VALUES (%s,%s,%s,%s) RETURNING id,username,display_name,created_at""",
|
||||
(uuid4(),payload.username,payload.display_name,password_hash(payload.password))).fetchone()
|
||||
except UniqueViolation:
|
||||
raise HTTPException(status_code=409,detail='Username already exists')
|
||||
return user
|
||||
|
||||
|
||||
@router.get('/api/v1/users/me', response_model=User)
|
||||
def get_current_user(user=Depends(current_user)):
|
||||
return user
|
||||
|
||||
|
||||
@router.post('/api/v1/auth/sessions', status_code=201)
|
||||
def create_session(authorization: str | None = Header(default=None)):
|
||||
if not authorization or not authorization.startswith('Basic '):
|
||||
unauthorized(basic=True)
|
||||
try:
|
||||
raw = base64.b64decode(authorization[6:],validate=True).decode('utf-8')
|
||||
username, password = raw.split(':',1)
|
||||
except (ValueError, UnicodeDecodeError, binascii.Error):
|
||||
unauthorized(basic=True)
|
||||
with db() as conn:
|
||||
row = conn.execute('SELECT * FROM users WHERE username=%s',(username,)).fetchone()
|
||||
if row is None or not verify_password(password,row['password_hash']):
|
||||
unauthorized(basic=True)
|
||||
token = secrets.token_urlsafe(48)
|
||||
ttl = int(os.getenv('SESSION_TTL_SECONDS','3600'))
|
||||
expires = datetime.now(timezone.utc)+timedelta(seconds=ttl)
|
||||
conn.execute('INSERT INTO sessions(token_hash,user_id,expires_at) VALUES (%s,%s,%s)',
|
||||
(hashlib.sha256(token.encode()).hexdigest(),row['id'],expires))
|
||||
return {'token':token,'token_type':'Bearer','expires_at':utc_z(expires),
|
||||
'user':User.model_validate({key:row[key] for key in ('id','username','display_name','created_at')})}
|
||||
|
||||
|
||||
@router.delete('/api/v1/auth/sessions/current',status_code=204)
|
||||
def logout(authorization: str | None = Header(default=None),user=Depends(current_user)):
|
||||
token=authorization[7:]
|
||||
with db() as conn:
|
||||
conn.execute('DELETE FROM sessions WHERE token_hash=%s',(hashlib.sha256(token.encode()).hexdigest(),))
|
||||
return Response(status_code=204)
|
||||
@@ -0,0 +1,29 @@
|
||||
"""PostgreSQL is the source of truth, including bearer sessions."""
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
|
||||
def database_url():
|
||||
secret_file = os.getenv("DATABASE_URL_FILE")
|
||||
if secret_file:
|
||||
return Path(secret_file).read_text().strip()
|
||||
return os.environ["DATABASE_URL"]
|
||||
|
||||
|
||||
@contextmanager
|
||||
def db():
|
||||
with psycopg.connect(database_url(), row_factory=dict_row, connect_timeout=5) as conn:
|
||||
yield conn
|
||||
|
||||
|
||||
def migrate():
|
||||
with db() as conn:
|
||||
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version TEXT PRIMARY KEY)")
|
||||
for file in sorted((Path(__file__).parent.parent / "migrations").glob("*.sql")):
|
||||
if conn.execute("SELECT 1 FROM schema_migrations WHERE version=%s", (file.name,)).fetchone():
|
||||
continue
|
||||
conn.execute(file.read_text())
|
||||
conn.execute("INSERT INTO schema_migrations(version) VALUES (%s)", (file.name,))
|
||||
Reference in New Issue
Block a user