forked from mtusi2026/mtusi2026lab2
ЛР 2 — БВТ2302 — Макаренко — PostgreSQL и сессии
This commit is contained in:
+108
@@ -0,0 +1,108 @@
|
||||
import hashlib
|
||||
import os
|
||||
import secrets
|
||||
import uuid
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
from psycopg.types.json import Jsonb
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError
|
||||
from fastapi import HTTPException
|
||||
|
||||
kdf = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
dummy = kdf.hash(secrets.token_hex(16))
|
||||
|
||||
|
||||
def db():
|
||||
return psycopg.connect(os.environ["DATABASE_URL"], connect_timeout=3)
|
||||
|
||||
|
||||
def stamp(moment=None):
|
||||
return (moment or datetime.now(timezone.utc)).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def entity(**fields):
|
||||
return dict(id=str(uuid.uuid4()), created_at=stamp(), **fields)
|
||||
|
||||
|
||||
def digest(token):
|
||||
return hashlib.sha256(token.encode()).hexdigest()
|
||||
|
||||
|
||||
class Store:
|
||||
def migrate(self):
|
||||
with db() as c:
|
||||
c.execute("select pg_advisory_xact_lock(2081)")
|
||||
c.execute(Path(__file__).with_name("001.sql").read_text())
|
||||
|
||||
def create_user(self, username, display_name, password):
|
||||
user = entity(username=username, display_name=display_name)
|
||||
with db() as c:
|
||||
row = c.execute("insert into users values (%s,%s,%s,%s) on conflict do nothing returning id",
|
||||
(user["id"], username, kdf.hash(password), Jsonb(user))).fetchone()
|
||||
return (user, None) if row else (None, "conflict")
|
||||
|
||||
def login(self, username, password):
|
||||
with db() as c:
|
||||
row = c.execute("select password_hash,doc from users where username=%s",(username,)).fetchone()
|
||||
try:
|
||||
kdf.verify(row[0] if row else dummy, password)
|
||||
except VerificationError:
|
||||
return None
|
||||
if not row:
|
||||
return None
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires = datetime.now(timezone.utc) + timedelta(seconds=int(os.getenv("SESSION_TTL_SECONDS","3600")))
|
||||
c.execute("insert into sessions values (%s,%s,%s)",(digest(token),row[1]["id"],expires))
|
||||
return dict(token=token,token_type="Bearer",expires_at=stamp(expires),user=row[1])
|
||||
|
||||
def session(self, token):
|
||||
with db() as c:
|
||||
row = c.execute("select doc from users join sessions on owner=id where digest=%s and expires>now()", (digest(token),)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def create_chat(self, owner, title, members):
|
||||
if owner not in members or len(set(members)) != len(members):
|
||||
return None, "invalid_request"
|
||||
chat = entity(title=title, member_ids=members)
|
||||
with db() as c:
|
||||
if c.execute("select count(*) from users where id=any(%s)",(members,)).fetchone()[0] != len(members):
|
||||
return None, "invalid_request"
|
||||
c.execute("insert into chats values(%s,%s)",(chat["id"],Jsonb(chat)))
|
||||
c.execute("insert into members select %s,unnest(%s::text[])",(chat["id"],members))
|
||||
return chat, None
|
||||
|
||||
def list_chats(self, owner):
|
||||
with db() as c:
|
||||
return [r[0] for r in c.execute("select doc from chats join members on chat=id where owner=%s",(owner,))]
|
||||
|
||||
def member_chat(self, chat, owner):
|
||||
with db() as c:
|
||||
row = c.execute("select doc from chats join members on chat=id where id=%s and owner=%s",(chat,owner)).fetchone()
|
||||
return row[0] if row else None
|
||||
|
||||
def add_message(self, chat, sender, text, key, attachments):
|
||||
message = entity(chat_id=chat,sender_id=sender,text=text)
|
||||
if attachments is not None:
|
||||
message["attachment_ids"] = attachments
|
||||
with db() as c:
|
||||
for att in attachments or []:
|
||||
row = c.execute("select doc->>'status' from attachments where id=%s and chat=%s",(att,chat)).fetchone()
|
||||
if not row:
|
||||
raise HTTPException(404)
|
||||
if row[0]=="failed":
|
||||
raise HTTPException(409)
|
||||
result = c.execute("insert into messages values (%s,%s,%s,%s,%s) on conflict(chat,sender,retry_key) do nothing returning doc",
|
||||
(message["id"],chat,sender,key,Jsonb(message))).fetchone()
|
||||
if result:
|
||||
return result[0]
|
||||
prev = c.execute("select doc from messages where chat=%s and sender=%s and retry_key=%s",(chat,sender,key)).fetchone()[0]
|
||||
if prev["text"] != text or prev.get("attachment_ids") != attachments:
|
||||
raise HTTPException(409)
|
||||
return prev
|
||||
|
||||
def list_messages(self, chat):
|
||||
with db() as c:
|
||||
return [r[0] for r in c.execute("select doc from messages where chat=%s",(chat,))]
|
||||
Reference in New Issue
Block a user