feat(quizzes): публичные ссылки по токену и флаг no_shuffle
- quizzes.public_token (VARCHAR 32, уникальный индекс) вместо числового id в публичных роутах /api/public-quizzes/:token - бэкилл токенов для существующих строк в db/migration.sql + ensureQuizTables - quiz_questions.no_shuffle — вопрос исключён из перемешивания - POST /api/quizzes/:id/public-token/rotate — сброс утёкшей ссылки (автор/админ) - restore: no_shuffle в INSERT quiz_questions, backup.selftest обновлён - документация AGENTS.md + handoff
This commit is contained in:
+60
-25
@@ -195,6 +195,7 @@ async function ensureQuizTables(pool) {
|
||||
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
|
||||
stats_public BOOLEAN NOT NULL DEFAULT false,
|
||||
access_code VARCHAR(64),
|
||||
public_token VARCHAR(32),
|
||||
grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL,
|
||||
author_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -215,6 +216,8 @@ async function ensureQuizTables(pool) {
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS allow_anonymous BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS stats_public BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS access_code VARCHAR(64)');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS public_token VARCHAR(32)');
|
||||
await pool.query(`UPDATE quizzes SET public_token = md5(random()::text || clock_timestamp()::text || id::text) WHERE public_token IS NULL`);
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ');
|
||||
@@ -230,6 +233,7 @@ async function ensureQuizTables(pool) {
|
||||
required BOOLEAN NOT NULL DEFAULT true,
|
||||
min_length INT NOT NULL DEFAULT 0,
|
||||
options_inline BOOLEAN NOT NULL DEFAULT false,
|
||||
no_shuffle BOOLEAN NOT NULL DEFAULT false,
|
||||
text_match VARCHAR(16) NOT NULL DEFAULT 'exact',
|
||||
accepted_answers TEXT[] NOT NULL DEFAULT '{}',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
@@ -245,6 +249,7 @@ async function ensureQuizTables(pool) {
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS accepted_answers TEXT[] NOT NULL DEFAULT \'{}\'');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS min_length INT NOT NULL DEFAULT 0');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS options_inline BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS no_shuffle BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_options (
|
||||
id SERIAL PRIMARY KEY,
|
||||
question_id INT NOT NULL REFERENCES quiz_questions(id) ON DELETE CASCADE,
|
||||
@@ -316,6 +321,7 @@ async function ensureQuizTables(pool) {
|
||||
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS question_text TEXT NOT NULL DEFAULT \'\'');
|
||||
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS answer_snapshot JSONB NOT NULL DEFAULT \'{}\'::jsonb');
|
||||
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS answer_id INT');
|
||||
await pool.query('CREATE UNIQUE INDEX IF NOT EXISTS idx_quizzes_public_token ON quizzes(public_token)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_author ON quizzes(author_id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_kind ON quizzes(kind, is_published)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_purge ON quizzes(purge_at) WHERE purge_at IS NOT NULL');
|
||||
@@ -412,6 +418,7 @@ async function loadQuizStructure(pool, quizId) {
|
||||
required: q.required !== false,
|
||||
min_length: Number(q.min_length) || 0,
|
||||
options_inline: q.options_inline === true,
|
||||
no_shuffle: q.no_shuffle === true,
|
||||
text_match: q.text_match === 'contains' ? 'contains' : 'exact',
|
||||
accepted_answers: Array.isArray(q.accepted_answers) ? q.accepted_answers : [],
|
||||
sort_order: q.sort_order,
|
||||
@@ -446,6 +453,7 @@ function stripAnswers(structure) {
|
||||
function quizMeta(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
public_token: row.public_token || null,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
kind: row.kind,
|
||||
@@ -531,18 +539,36 @@ async function listQuizzes(pool, user, params = {}) {
|
||||
return { items, total: totalRes.rows[0].c };
|
||||
}
|
||||
|
||||
function publicToken() {
|
||||
return crypto.randomBytes(QUIZ_ANON_TOKEN_BYTES).toString('hex');
|
||||
}
|
||||
|
||||
function normalizePublicToken(raw) {
|
||||
const value = typeof raw === 'string' ? raw.trim() : '';
|
||||
return /^[a-f0-9]{32}$/i.test(value) ? value.toLowerCase() : null;
|
||||
}
|
||||
|
||||
async function createQuiz(pool, user, body = {}) {
|
||||
const kind = body.kind === 'survey' ? 'survey' : 'test';
|
||||
const title = typeof body.title === 'string' && body.title.trim()
|
||||
? body.title.trim().slice(0, QUIZ_TITLE_MAX)
|
||||
: (kind === 'survey' ? 'Новый опрос' : 'Новый тест');
|
||||
const { rows } = await pool.query(
|
||||
'INSERT INTO quizzes (title, description, kind, author_id) VALUES ($1, $2, $3, $4) RETURNING id',
|
||||
[title, null, kind, user.id]
|
||||
'INSERT INTO quizzes (title, description, kind, author_id, public_token) VALUES ($1, $2, $3, $4, $5) RETURNING id',
|
||||
[title, null, kind, user.id, publicToken()]
|
||||
);
|
||||
return getQuiz(pool, rows[0].id, user);
|
||||
}
|
||||
|
||||
async function rotatePublicToken(pool, id, user) {
|
||||
const row = await findQuizRow(pool, id);
|
||||
if (!row) throw httpError(404, 'Тест не найден');
|
||||
if (!canEditQuiz(row, user)) throw httpError(403, 'Изменять тест может только автор или администратор');
|
||||
const token = publicToken();
|
||||
await pool.query('UPDATE quizzes SET public_token = $2, updated_at = now() WHERE id = $1', [id, token]);
|
||||
return { id, public_token: token };
|
||||
}
|
||||
|
||||
async function getQuiz(pool, id, user, opts = {}) {
|
||||
const row = await findQuizRow(pool, id);
|
||||
if (!row) throw httpError(404, 'Тест не найден');
|
||||
@@ -683,6 +709,7 @@ function validateQuestion(q, quizKind, index) {
|
||||
required,
|
||||
min_length: minLength,
|
||||
options_inline: optionsInline,
|
||||
no_shuffle: asBool(q.no_shuffle, false),
|
||||
text_match: textMatch,
|
||||
accepted_answers: acceptedAnswers,
|
||||
asset_ids: normalizeIdList(q.asset_ids, QUIZ_ASSETS_MAX),
|
||||
@@ -819,17 +846,17 @@ async function saveQuiz(pool, id, user, body = {}) {
|
||||
await client.query(
|
||||
`UPDATE quiz_questions SET sort_order = $2, kind = $3, text = $4, description = $5,
|
||||
weight = $6, partial_credit = $7, required = $8, min_length = $12,
|
||||
options_inline = $13, text_match = $10, accepted_answers = $11::text[], updated_at = now()
|
||||
options_inline = $13, no_shuffle = $14, text_match = $10, accepted_answers = $11::text[], updated_at = now()
|
||||
WHERE id = $1 AND quiz_id = $9`,
|
||||
[qid, i, q.kind, q.text, q.description, q.weight, q.partial_credit, q.required, id,
|
||||
q.text_match, q.accepted_answers, q.min_length, q.options_inline]
|
||||
q.text_match, q.accepted_answers, q.min_length, q.options_inline, q.no_shuffle]
|
||||
);
|
||||
} else {
|
||||
const ins = await client.query(
|
||||
`INSERT INTO quiz_questions (quiz_id, sort_order, kind, text, description, weight, partial_credit, required, text_match, accepted_answers, min_length, options_inline)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10::text[],$11,$12) RETURNING id`,
|
||||
`INSERT INTO quiz_questions (quiz_id, sort_order, kind, text, description, weight, partial_credit, required, text_match, accepted_answers, min_length, options_inline, no_shuffle)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10::text[],$11,$12,$13) RETURNING id`,
|
||||
[id, i, q.kind, q.text, q.description, q.weight, q.partial_credit, q.required,
|
||||
q.text_match, q.accepted_answers, q.min_length, q.options_inline]
|
||||
q.text_match, q.accepted_answers, q.min_length, q.options_inline, q.no_shuffle]
|
||||
);
|
||||
qid = ins.rows[0].id;
|
||||
}
|
||||
@@ -1209,19 +1236,24 @@ function guestNameValue(raw) {
|
||||
return value || null;
|
||||
}
|
||||
|
||||
async function findPublicQuiz(pool, quizId) {
|
||||
const row = await findQuizRow(pool, quizId);
|
||||
if (!row) throw httpError(404, 'Тест не найден');
|
||||
async function findPublicQuiz(pool, token) {
|
||||
const value = normalizePublicToken(token);
|
||||
if (!value) throw httpError(404, 'Тест не найден');
|
||||
const { rows } = await pool.query('SELECT * FROM quizzes WHERE public_token = $1 AND deleted_at IS NULL', [value]);
|
||||
if (!rows.length) throw httpError(404, 'Тест не найден');
|
||||
const row = rows[0];
|
||||
if (row.allow_anonymous !== true || row.is_published !== true) {
|
||||
throw httpError(404, 'Тест не найден');
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
async function getPublicQuiz(pool, quizId) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
const structure = stripAnswers(await loadQuizStructure(pool, quizId));
|
||||
async function getPublicQuiz(pool, token) {
|
||||
const row = await findPublicQuiz(pool, token);
|
||||
const structure = stripAnswers(await loadQuizStructure(pool, row.id));
|
||||
const meta = quizMeta(row);
|
||||
delete meta.id;
|
||||
delete meta.public_token;
|
||||
delete meta.author_id;
|
||||
delete meta.deleted_at;
|
||||
delete meta.purge_at;
|
||||
@@ -1236,18 +1268,18 @@ async function getPublicQuiz(pool, quizId) {
|
||||
};
|
||||
}
|
||||
|
||||
async function startPublicAttempt(pool, quizId, opts = {}) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
async function startPublicAttempt(pool, token, opts = {}) {
|
||||
const row = await findPublicQuiz(pool, token);
|
||||
if (!accessCodeMatches(row.access_code, opts.code)) throw httpError(403, 'Неверный код доступа');
|
||||
const guestName = row.kind === 'test' ? guestNameValue(opts.name) : null;
|
||||
const token = crypto.randomBytes(QUIZ_ANON_TOKEN_BYTES).toString('hex');
|
||||
const attemptToken = crypto.randomBytes(QUIZ_ANON_TOKEN_BYTES).toString('hex');
|
||||
const { rows } = await pool.query(
|
||||
'INSERT INTO quiz_attempts (quiz_id, user_id, anon_token, guest_name) VALUES ($1, NULL, $2, $3) RETURNING id, started_at',
|
||||
[quizId, token, guestName]
|
||||
[row.id, attemptToken, guestName]
|
||||
);
|
||||
return {
|
||||
attempt: { id: rows[0].id, started_at: rows[0].started_at, anon_token: token, guest_name: guestName },
|
||||
quiz: await getPublicQuiz(pool, quizId),
|
||||
attempt: { id: rows[0].id, started_at: rows[0].started_at, anon_token: attemptToken, guest_name: guestName },
|
||||
quiz: await getPublicQuiz(pool, token),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1258,13 +1290,13 @@ function anonTokenMatches(expected, given) {
|
||||
return crypto.timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
async function submitPublicAttempt(pool, quizId, attemptId, token, body = {}) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
const { rows } = await pool.query('SELECT * FROM quiz_attempts WHERE id = $1 AND quiz_id = $2', [attemptId, quizId]);
|
||||
async function submitPublicAttempt(pool, token, attemptId, attemptToken, body = {}) {
|
||||
const row = await findPublicQuiz(pool, token);
|
||||
const { rows } = await pool.query('SELECT * FROM quiz_attempts WHERE id = $1 AND quiz_id = $2', [attemptId, row.id]);
|
||||
if (!rows.length) throw httpError(404, 'Попытка не найдена');
|
||||
const attempt = rows[0];
|
||||
if (attempt.user_id != null) throw httpError(403, 'Нет доступа к попытке');
|
||||
if (!anonTokenMatches(attempt.anon_token, token)) throw httpError(403, 'Нет доступа к попытке');
|
||||
if (!anonTokenMatches(attempt.anon_token, attemptToken)) throw httpError(403, 'Нет доступа к попытке');
|
||||
if (attempt.status === 'done') throw httpError(409, 'Попытка уже завершена');
|
||||
return performSubmit(pool, row, attempt, body);
|
||||
}
|
||||
@@ -1312,8 +1344,8 @@ async function lookupSystemOptions(pool, field, query, branchIds = null) {
|
||||
return { items: rows.map(r => ({ id: r.id, name: r.name, sub: r.sub || null })) };
|
||||
}
|
||||
|
||||
async function lookupPublicQuizOptions(pool, quizId, opts = {}) {
|
||||
const row = await findPublicQuiz(pool, quizId);
|
||||
async function lookupPublicQuizOptions(pool, token, opts = {}) {
|
||||
const row = await findPublicQuiz(pool, token);
|
||||
if (!row.access_code) throw httpError(403, 'Подсказки недоступны: автор не задал код доступа');
|
||||
if (!accessCodeMatches(row.access_code, opts.code)) throw httpError(403, 'Неверный код доступа');
|
||||
let branchIds = null;
|
||||
@@ -1846,6 +1878,9 @@ module.exports = {
|
||||
quizWriteBlocked,
|
||||
listQuizzes,
|
||||
createQuiz,
|
||||
rotatePublicToken,
|
||||
publicToken,
|
||||
normalizePublicToken,
|
||||
getQuiz,
|
||||
saveQuiz,
|
||||
softDeleteQuiz,
|
||||
|
||||
Reference in New Issue
Block a user