Implement lab2 PostgreSQL authentication and Redis sessions

This commit is contained in:
ferraronp
2026-10-23 18:33:06 +03:00
parent 65003b6119
commit 5dd32a77ac
23 changed files with 1126 additions and 55 deletions
+31
View File
@@ -0,0 +1,31 @@
CREATE TABLE users (
id uuid PRIMARY KEY,
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
display_name varchar(100) NOT NULL CHECK (length(btrim(display_name)) > 0),
password_hash text NOT NULL,
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chats (
id uuid PRIMARY KEY,
title varchar(100) NOT NULL CHECK (length(btrim(title)) > 0),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE TABLE chat_members (
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
user_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
position smallint NOT NULL CHECK (position >= 0),
PRIMARY KEY (chat_id,user_id),
UNIQUE (chat_id,position)
);
CREATE INDEX idx_chat_members_user ON chat_members (user_id,chat_id);
CREATE INDEX idx_chats_page ON chats (created_at,id);
CREATE TABLE messages (
id uuid PRIMARY KEY,
chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE RESTRICT,
sender_id uuid NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
CONSTRAINT message_sender_is_member FOREIGN KEY (chat_id,sender_id)
REFERENCES chat_members(chat_id,user_id) ON DELETE RESTRICT,
text varchar(4000) NOT NULL CHECK (length(btrim(text)) > 0),
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
);
CREATE INDEX idx_messages_chat_history ON messages (chat_id,created_at,id);
+17
View File
@@ -0,0 +1,17 @@
-- PostgreSQL text/varchar reject the NUL character, but the public API accepts
-- arbitrary valid UTF-8 code points in display_name, title and message text.
-- Store exact UTF-8 bytes in bytea while enforcing code-point limits at API.
-- Existing rows are converted losslessly; safe with persistent lab2 volumes.
ALTER TABLE users DROP CONSTRAINT users_display_name_check;
ALTER TABLE chats DROP CONSTRAINT chats_title_check;
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
ALTER TABLE users ALTER COLUMN display_name TYPE bytea USING convert_to(display_name, 'UTF8');
ALTER TABLE chats ALTER COLUMN title TYPE bytea USING convert_to(title, 'UTF8');
ALTER TABLE messages ALTER COLUMN text TYPE bytea USING convert_to(text, 'UTF8');
-- A valid UTF-8 code point occupies at most four bytes.
-- Pydantic enforces 1..100/4000 code points and no whitespace-only strings.
ALTER TABLE users ADD CONSTRAINT users_display_name_octets CHECK (octet_length(display_name) BETWEEN 1 AND 400);
ALTER TABLE chats ADD CONSTRAINT chats_title_octets CHECK (octet_length(title) BETWEEN 1 AND 400);
ALTER TABLE messages ADD CONSTRAINT messages_text_octets CHECK (octet_length(text) BETWEEN 1 AND 16000);