Include complete API and frontend sources for unified deployment
This commit is contained in:
1 parent
627b0ae60e
commit
d8fcae32b0
93 files changed
+53270
-3
No files matched your search
@@ -0,0 +1,142 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import admin from '../config/admin.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import { calculatePositions } from '../scripts/calc-positions.js';
|
||||
import { getMissingMarks } from '../scripts/no-marks.js';
|
||||
|
||||
async function main() {
|
||||
for (const model of Object.values(models)) model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
await sequelize.authenticate();
|
||||
const base = process.env.GRADE_API_URL || 'http://127.0.0.1:3080';
|
||||
const suffix = Date.now().toString(36);
|
||||
const created = { cases: [], users: [], teams: [] };
|
||||
let token;
|
||||
async function request(path, { method = 'GET', body, status = 200, auth = token } = {}) {
|
||||
const response = await globalThis.fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
...(auth ? { Authorization: `Bearer ${auth}` } : {}),
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.equal(response.status, status, `${method} ${path}: ${await response.clone().text()}`);
|
||||
const text = await response.text();
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
try {
|
||||
token = (await request('/auth/login', { method: 'POST', body: { login: admin.login, password: admin.password } }))
|
||||
.token;
|
||||
await request('/admin/cases', { method: 'POST', body: { name: ' ' }, status: 400 });
|
||||
const { case: task } = await request('/admin/cases', {
|
||||
method: 'POST',
|
||||
body: { name: 'API test ' + suffix },
|
||||
status: 201,
|
||||
});
|
||||
created.cases.push(task.id);
|
||||
const { team } = await request(`/admin/cases/${task.id}/teams`, {
|
||||
method: 'POST',
|
||||
body: { name: 'Test team' },
|
||||
status: 201,
|
||||
});
|
||||
created.teams.push(team.id);
|
||||
await request(`/admin/cases/${task.id}`, {
|
||||
method: 'PUT',
|
||||
body: { name: 'Updated ' + suffix, description: 'Updated description' },
|
||||
});
|
||||
await request(`/admin/cases/${task.id}/teams/${team.id}`, { method: 'PUT', body: { name: 'Updated team' } });
|
||||
const { user } = await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: 'API ' + suffix, lastName: 'Expert', caseIds: [task.id, task.id] },
|
||||
status: 201,
|
||||
});
|
||||
created.users.push(user.id);
|
||||
assert.deepEqual(
|
||||
(await models.UserInCase.findAll({ where: { userId: user.id } })).map(row => row.caseId),
|
||||
[task.id]
|
||||
);
|
||||
await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: 'Invalid ' + suffix, lastName: 'Expert', caseIds: ['00000000-0000-0000-0000-000000000000'] },
|
||||
status: 400,
|
||||
});
|
||||
assert.equal(await models.User.count({ where: { firstName: 'Invalid ' + suffix }, paranoid: false }), 0);
|
||||
const { user: sameSurname } = await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: 'API second ' + suffix, lastName: 'Expert' },
|
||||
status: 201,
|
||||
});
|
||||
created.users.push(sameSurname.id);
|
||||
assert.notEqual(user.login, sameSurname.login);
|
||||
const assign = caseIds => request(`/admin/users/${user.id}/cases`, { method: 'PUT', body: { caseIds } });
|
||||
await assign([task.id]);
|
||||
await request(`/admin/users/${user.id}/cases`, {
|
||||
method: 'PUT',
|
||||
body: { caseIds: ['00000000-0000-0000-0000-000000000000'] },
|
||||
status: 400,
|
||||
});
|
||||
assert.ok((await request('/admin/users')).users.find(u => u.id === user.id).cases.some(c => c.id === task.id));
|
||||
await assign([]);
|
||||
await assign([task.id]);
|
||||
const listed = (await request('/admin/users')).users.find(u => u.id === user.id);
|
||||
assert.ok(listed.cases.some(c => c.id === task.id));
|
||||
assert.ok(!('password' in listed));
|
||||
const judge = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: user.login, password: listed.passwordForAdmin } })
|
||||
).token;
|
||||
assert.ok((await request('/cases', { auth: judge })).cases.some(c => c.id === task.id));
|
||||
await request('/admin/cases', { auth: judge, status: 403 });
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, {
|
||||
method: 'PUT',
|
||||
auth: judge,
|
||||
body: { marks: [{ markType: 20, mark: 5 }] },
|
||||
status: 403,
|
||||
});
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, {
|
||||
method: 'POST',
|
||||
auth: judge,
|
||||
body: { markType: 30, mark: 5 },
|
||||
status: 403,
|
||||
});
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, {
|
||||
method: 'PUT',
|
||||
auth: judge,
|
||||
body: { marks: [{ markType: 10, mark: 8 }] },
|
||||
status: 400,
|
||||
});
|
||||
|
||||
await request('/admin', { method: 'POST', body: { marks: [{ id: team.id, implementation: 3, work: 4 }] } });
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, {
|
||||
method: 'PUT',
|
||||
auth: judge,
|
||||
body: { marks: [10, 40, 50].map(markType => ({ markType, mark: 5 })) },
|
||||
});
|
||||
await request(`/admin/users/${sameSurname.id}/cases`, { method: 'PUT', body: { caseIds: [task.id] } });
|
||||
const copied = await models.Mark.findAll({ where: { userId: sameSurname.id, caseId: task.id } });
|
||||
assert.equal(copied.length, 2);
|
||||
const result = await request('/admin/positions');
|
||||
assert.equal(result.positions[task.id][team.id], 1);
|
||||
assert.deepEqual(result, await calculatePositions());
|
||||
assert.deepEqual(await request('/admin/marks'), await getMissingMarks());
|
||||
await assign([]);
|
||||
assert.equal((await request('/cases', { auth: judge })).cases.length, 0);
|
||||
await request(`/cases/${task.id}/teams/${team.id}/marks`, { auth: judge, status: 403 });
|
||||
console.log(
|
||||
'PASS: create/update cases and teams; expert credentials and duplicate surnames; assign/remove/reassign; invalid assignment rollback; role guards; organizer mark copying; live expert access; API/script parity.'
|
||||
);
|
||||
} finally {
|
||||
await models.Mark.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.UserInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.TeamInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.Team.destroy({ where: { id: created.teams }, force: true });
|
||||
await models.User.destroy({ where: { id: created.users }, force: true });
|
||||
await models.Case.destroy({ where: { id: created.cases }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import pngjs from 'pngjs';
|
||||
import { validateCaseIcon } from '../utils/case-icon.js';
|
||||
import admin from '../config/admin.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
|
||||
function image(size) {
|
||||
const png = new pngjs.PNG({ width: size, height: size });
|
||||
png.data.fill(120);
|
||||
return pngjs.PNG.sync.write(png, { deflateLevel: 0 });
|
||||
}
|
||||
|
||||
const allowed = image(450);
|
||||
const oversized = image(600);
|
||||
assert.ok(allowed.length > 256 * 1024 && allowed.length <= 1024 * 1024);
|
||||
assert.ok(oversized.length > 1024 * 1024);
|
||||
const icon = 'data:image/png;base64,' + allowed.toString('base64');
|
||||
assert.equal(validateCaseIcon(icon), icon);
|
||||
assert.throws(() => validateCaseIcon('data:image/png;base64,' + oversized.toString('base64')));
|
||||
|
||||
// Use the public proxy too: a 1 MB image exceeds 1 MB after base64 encoding.
|
||||
const base = process.env.GRADE_API_URL || 'http://web/api';
|
||||
let caseId;
|
||||
try {
|
||||
models.Case.initialize(sequelize);
|
||||
const login = await fetch(base + '/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ login: admin.login, password: admin.password }),
|
||||
});
|
||||
assert.equal(login.status, 200);
|
||||
const { token } = await login.json();
|
||||
const response = await fetch(base + '/admin/cases', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token },
|
||||
body: JSON.stringify({ name: 'Icon size regression ' + Date.now(), icon }),
|
||||
});
|
||||
assert.equal(response.status, 201);
|
||||
const { case: task } = await response.json();
|
||||
caseId = task.id;
|
||||
assert.equal(task.icon, icon);
|
||||
const rejected = await fetch(base + '/admin/cases/' + caseId, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + token },
|
||||
body: JSON.stringify({ name: task.name, icon: 'data:image/png;base64,' + oversized.toString('base64') }),
|
||||
});
|
||||
assert.equal(rejected.status, 400);
|
||||
console.log('PASS: PNG above 256 KB accepted through proxy and stored; PNG above 1 MB rejected.');
|
||||
} finally {
|
||||
if (caseId) await models.Case.destroy({ where: { id: caseId }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
import admin from '../config/admin.js';
|
||||
|
||||
async function main() {
|
||||
for (const model of Object.values(models)) model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
const base = process.env.GRADE_API_URL || 'http://127.0.0.1:3080';
|
||||
const created = [];
|
||||
let adminToken;
|
||||
async function request(path, { method = 'GET', body, token = adminToken, status = 200, pdf = false } = {}) {
|
||||
const response = await globalThis.fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
...(token ? { Authorization: 'Bearer ' + token } : {}),
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.equal(response.status, status, `${method} ${path}`);
|
||||
if (pdf) {
|
||||
assert.match(response.headers.get('content-type'), /application\/pdf/);
|
||||
assert.match(response.headers.get('content-disposition'), /attachment/);
|
||||
assert.match(response.headers.get('cache-control'), /no-store/);
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
const text = await response.text();
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
try {
|
||||
adminToken = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: admin.login, password: admin.password } })
|
||||
).token;
|
||||
const suffix = Date.now().toString(36);
|
||||
const { user } = await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: 'Тест', lastName: 'Экспорта' + suffix, middleName: 'Иванович' },
|
||||
status: 201,
|
||||
});
|
||||
created.push(user.id);
|
||||
let stored = await models.User.findByPk(user.id);
|
||||
const oldPassword = stored.passwordForAdmin;
|
||||
const task = await models.Case.findOne({
|
||||
include: { model: models.Team, as: 'teams', through: { attributes: [] } },
|
||||
});
|
||||
let retainedMark;
|
||||
if (task?.teams.length) {
|
||||
await task.addUser(stored);
|
||||
retainedMark = await models.Mark.create({
|
||||
caseId: task.id,
|
||||
teamId: task.teams[0].id,
|
||||
userId: user.id,
|
||||
markType: 10,
|
||||
mark: 4,
|
||||
});
|
||||
}
|
||||
|
||||
const oldToken = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: stored.login, password: oldPassword } })
|
||||
).token;
|
||||
const edit = {
|
||||
firstName: 'Иван',
|
||||
lastName: 'Петров',
|
||||
middleName: 'Сергеевич',
|
||||
login: 'edited-' + suffix,
|
||||
password: 'New+&?#2026!',
|
||||
};
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: edit });
|
||||
await request('/cases', { token: oldToken, status: 401 });
|
||||
await request('/auth/login', { method: 'POST', body: { login: user.login, password: oldPassword }, status: 403 });
|
||||
const currentToken = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: edit.login, password: edit.password } })
|
||||
).token;
|
||||
await request('/cases', { token: currentToken });
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: edit, token: currentToken, status: 403 });
|
||||
await request('/admin/users/qr-pdf', {
|
||||
method: 'POST',
|
||||
body: { baseUrl: 'https://grading.example.ru/' },
|
||||
token: currentToken,
|
||||
status: 403,
|
||||
});
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: { ...edit, login: 'admin' }, status: 400 });
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: { ...edit, password: 'x' }, status: 400 });
|
||||
await request(`/admin/users/${user.id}`, { method: 'PUT', body: { ...edit, password: '' } });
|
||||
stored = await models.User.findByPk(user.id);
|
||||
assert.equal(stored.middleName, 'Сергеевич');
|
||||
assert.ok(stored.validatePassword(edit.password));
|
||||
const pdf = await request('/admin/users/qr-pdf', {
|
||||
method: 'POST',
|
||||
body: { baseUrl: 'https://grading.example.ru/' },
|
||||
pdf: true,
|
||||
});
|
||||
assert.equal(pdf.subarray(0, 5).toString(), '%PDF-');
|
||||
for (const baseUrl of ['javascript:alert(1)', 'https://example.ru/#/login', 'https://u:p@example.ru/'])
|
||||
await request('/admin/users/qr-pdf', { method: 'POST', body: { baseUrl }, status: 400 });
|
||||
await request(`/admin/users/${user.id}`, { method: 'DELETE', status: 204 });
|
||||
await request('/cases', { token: currentToken, status: 401 });
|
||||
await request('/auth/login', { method: 'POST', body: { login: edit.login, password: edit.password }, status: 403 });
|
||||
assert.equal(await models.User.findByPk(user.id), null);
|
||||
if (retainedMark) assert.ok(await models.Mark.findByPk(retainedMark.id));
|
||||
|
||||
await request(`/admin/users/${user.id}/restore`, { method: 'POST' });
|
||||
const restored = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: edit.login, password: edit.password } })
|
||||
).token;
|
||||
await request('/cases', { token: restored });
|
||||
await request('/cases', { token: currentToken, status: 401 });
|
||||
console.log(
|
||||
'PASS expert name/login/password editing; unchanged password; admin-only access; deletion, login revocation and restore; old tokens stay invalid after same-second login; PDF endpoint and URL validation.'
|
||||
);
|
||||
} finally {
|
||||
await models.Mark.destroy({ where: { userId: created }, force: true });
|
||||
await models.UserInCase.destroy({ where: { userId: created }, force: true });
|
||||
await models.User.destroy({ where: { id: created }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,140 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import pngjs from 'pngjs';
|
||||
import admin from '../config/admin.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
|
||||
async function main() {
|
||||
for (const model of Object.values(models)) model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
const base = process.env.GRADE_API_URL || 'http://127.0.0.1:3080';
|
||||
const created = { cases: [], teams: [], users: [] };
|
||||
let adminToken;
|
||||
async function request(path, { method = 'GET', body, status = 200, token = adminToken } = {}) {
|
||||
const res = await globalThis.fetch(base + path, {
|
||||
method,
|
||||
headers: {
|
||||
...(token ? { Authorization: 'Bearer ' + token } : {}),
|
||||
...(body ? { 'Content-Type': 'application/json' } : {}),
|
||||
},
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.equal(res.status, status, `${method} ${path}: ${await res.clone().text()}`);
|
||||
const text = await res.text();
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
try {
|
||||
adminToken = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: admin.login, password: admin.password } })
|
||||
).token;
|
||||
const png = new pngjs.PNG({ width: 2, height: 2 });
|
||||
png.data.fill(120);
|
||||
const icon = 'data:image/png;base64,' + pngjs.PNG.sync.write(png).toString('base64');
|
||||
const { case: task } = await request('/admin/cases', {
|
||||
method: 'POST',
|
||||
body: { name: 'Icons test ' + Date.now(), icon },
|
||||
status: 201,
|
||||
});
|
||||
created.cases.push(task.id);
|
||||
assert.equal(task.icon, icon);
|
||||
await request('/admin/cases/' + task.id, { method: 'PUT', body: { name: task.name } });
|
||||
assert.equal((await models.Case.findByPk(task.id)).icon, icon);
|
||||
for (const invalid of [
|
||||
'data:image/jpeg;base64,AAAA',
|
||||
'data:image/png;base64,AAAA',
|
||||
'data:image/png;base64,' + Buffer.alloc(270000).toString('base64'),
|
||||
])
|
||||
await request('/admin/cases/' + task.id, {
|
||||
method: 'PUT',
|
||||
body: { name: task.name, icon: invalid },
|
||||
status: 400,
|
||||
});
|
||||
for (const name of ['A', 'B']) {
|
||||
const { team } = await request(`/admin/cases/${task.id}/teams`, { method: 'POST', body: { name }, status: 201 });
|
||||
created.teams.push(team.id);
|
||||
}
|
||||
for (const name of ['A', 'B']) {
|
||||
const { user } = await request('/admin/users', {
|
||||
method: 'POST',
|
||||
body: { firstName: name, lastName: 'Details' + Date.now() + name, middleName: 'Иванович' },
|
||||
status: 201,
|
||||
});
|
||||
created.users.push(user.id);
|
||||
await request(`/admin/users/${user.id}/cases`, { method: 'PUT', body: { caseIds: [task.id] } });
|
||||
}
|
||||
const user = await models.User.findByPk(created.users[0]);
|
||||
const judge = (
|
||||
await request('/auth/login', { method: 'POST', body: { login: user.login, password: user.passwordForAdmin } })
|
||||
).token;
|
||||
assert.equal((await request('/cases', { token: judge })).cases[0].icon, icon);
|
||||
await request('/admin/marks/details', { token: judge, status: 403 });
|
||||
await request('/admin', {
|
||||
method: 'POST',
|
||||
body: { marks: [{ id: created.teams[0], implementation: 3, work: 4 }] },
|
||||
});
|
||||
await request(`/cases/${task.id}/teams/${created.teams[0]}/marks`, {
|
||||
token: judge,
|
||||
method: 'PUT',
|
||||
body: {
|
||||
marks: [
|
||||
{ markType: 10, mark: 0 },
|
||||
{ markType: 40, mark: 2 },
|
||||
{ markType: 50, mark: 5 },
|
||||
],
|
||||
},
|
||||
});
|
||||
let report = (await request('/admin/marks/details')).details.find(c => c.id === task.id);
|
||||
assert.equal(report.rows.length, 4);
|
||||
const row = report.rows.find(r => r.teamId === created.teams[0] && r.userId === user.id);
|
||||
assert.equal(row.marks[10], 0);
|
||||
assert.equal(row.total, 14);
|
||||
assert.ok(row.expert.includes('Иванович'));
|
||||
const incomplete = report.rows.find(r => r.teamId === created.teams[0] && r.userId === created.users[1]);
|
||||
assert.equal(incomplete.marks[10], null);
|
||||
assert.equal(incomplete.marks[20], 3);
|
||||
assert.equal(incomplete.total, null);
|
||||
const { zeroMarks } = await request('/admin/marks');
|
||||
assert.ok(zeroMarks[user.firstName + ' ' + user.lastName][task.name].includes('A'));
|
||||
assert.ok(!zeroMarks[user.firstName + ' ' + user.lastName][task.name].includes('B'));
|
||||
const otherUser = await models.User.findByPk(created.users[1]);
|
||||
assert.equal(zeroMarks[otherUser.firstName + ' ' + otherUser.lastName]?.[task.name], undefined);
|
||||
await models.Mark.destroy({ where: { userId: user.id, caseId: task.id, markType: [20, 30] }, force: true });
|
||||
let missing = (await request('/admin/marks')).noMarks;
|
||||
assert.ok(!missing[user.firstName + ' ' + user.lastName][task.name].includes('A'));
|
||||
assert.ok(missing[user.firstName + ' ' + user.lastName][task.name].includes('B'));
|
||||
await request(`/cases/${task.id}/teams/${created.teams[0]}/marks`, {
|
||||
token: judge,
|
||||
method: 'PUT',
|
||||
body: { marks: [10, 40, 50].map(markType => ({ markType, mark: 0 })) },
|
||||
});
|
||||
missing = (await request('/admin/marks')).noMarks;
|
||||
assert.ok(!missing[user.firstName + ' ' + user.lastName][task.name].includes('A'));
|
||||
await models.Mark.destroy({
|
||||
where: { userId: user.id, teamId: created.teams[0], caseId: task.id, markType: 40 },
|
||||
force: true,
|
||||
});
|
||||
missing = (await request('/admin/marks')).noMarks;
|
||||
assert.ok(missing[user.firstName + ' ' + user.lastName][task.name].includes('A'));
|
||||
assert.ok(!JSON.stringify(report).includes(user.passwordForAdmin));
|
||||
await request('/admin/users/' + created.users[1], { method: 'DELETE', status: 204 });
|
||||
report = (await request('/admin/marks/details')).details.find(c => c.id === task.id);
|
||||
assert.equal(report.rows.length, 2);
|
||||
await request('/admin/cases/' + task.id, { method: 'PUT', body: { name: task.name, icon: null } });
|
||||
assert.equal((await models.Case.findByPk(task.id)).icon, null);
|
||||
console.log(
|
||||
'PASS PNG create/preserve/remove/validation; assigned expert icon; all-mark matrix; zero vs missing; totals; technical marks; deleted experts; permissions and no credential exposure.'
|
||||
);
|
||||
} finally {
|
||||
await models.Mark.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.UserInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.TeamInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.Team.destroy({ where: { id: created.teams }, force: true });
|
||||
await models.User.destroy({ where: { id: created.users }, force: true });
|
||||
await models.Case.destroy({ where: { id: created.cases }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
}
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createExpertQrPdf, loginLink } from '../utils/expert-qr-pdf.js';
|
||||
|
||||
async function main() {
|
||||
const users = Array.from({ length: 25 }, (_, i) => ({
|
||||
firstName: 'Александр',
|
||||
lastName: 'Эксперт ' + i,
|
||||
middleName: 'Александрович',
|
||||
login: 'expert-' + i,
|
||||
passwordForAdmin: 'Test+&?#%Ю2026',
|
||||
}));
|
||||
const link = new URL(loginLink('https://grading.example.ru/app/', users[0]));
|
||||
assert.equal(link.origin, 'https://grading.example.ru');
|
||||
assert.equal(link.pathname, '/app/');
|
||||
const query = new URLSearchParams(link.hash.slice('/login?'.length + 1));
|
||||
assert.equal(query.get('l'), users[0].login);
|
||||
assert.equal(query.get('p'), users[0].passwordForAdmin);
|
||||
const pdf = (await createExpertQrPdf(users, 'https://grading.example.ru/app/')).toString('latin1');
|
||||
assert.equal(pdf.slice(0, 5), '%PDF-');
|
||||
assert.equal((pdf.match(/\/Type \/Page\b/g) || []).length, 3);
|
||||
assert.equal((pdf.match(/\/Subtype \/Link\b/g) || []).length, 25);
|
||||
for (const [technicalCount, regularCount, pages] of [
|
||||
[2, 5, 2],
|
||||
[12, 1, 2],
|
||||
[13, 2, 3],
|
||||
[12, 12, 2],
|
||||
[1, 0, 1],
|
||||
]) {
|
||||
const regular = users.slice(0, regularCount).map(user => ({ ...user, role: 'expert' }));
|
||||
const technical = users.slice(0, technicalCount).map((user, i) => ({
|
||||
...user,
|
||||
role: 'technical',
|
||||
login: 'technical-' + i,
|
||||
cases: [{ name: 'Тестовый кейс ' + i }],
|
||||
}));
|
||||
const grouped = (await createExpertQrPdf([...regular, ...technical], 'https://grading.example.ru/')).toString(
|
||||
'latin1'
|
||||
);
|
||||
assert.equal((grouped.match(/\/Type \/Page\b/g) || []).length, pages);
|
||||
const links = [...grouped.matchAll(/\/URI\s*\(([^)]*)\)/g)].map(match => match[1]);
|
||||
assert.deepEqual(
|
||||
links,
|
||||
[...technical, ...regular].map(user => loginLink('https://grading.example.ru/', user))
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
'PASS QR cards and links; technical experts first; role groups start on separate pages; A4 pagination at group boundaries; reserved credentials round-trip.'
|
||||
);
|
||||
}
|
||||
main().catch(error => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,219 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import admin from '../config/admin.js';
|
||||
import { models, sequelize } from '../models/index.js';
|
||||
import setupAssociations from '../models/setupAssociations.js';
|
||||
for (const model of Object.values(models)) model.initialize(sequelize);
|
||||
setupAssociations();
|
||||
const base = process.env.GRADE_API_URL || 'http://127.0.0.1:3080';
|
||||
const suffix = Date.now().toString(36);
|
||||
const created = { cases: [], users: [], teams: [] };
|
||||
let token;
|
||||
async function req(path, body, status = 200, auth = token, method = body ? 'POST' : 'GET') {
|
||||
const res = await fetch(base + path, {
|
||||
method,
|
||||
headers: { Authorization: 'Bearer ' + auth, 'Content-Type': 'application/json' },
|
||||
body: body ? JSON.stringify(body) : undefined,
|
||||
});
|
||||
assert.equal(res.status, status, `${method} ${path}: ${await res.clone().text()}`);
|
||||
const text = await res.text();
|
||||
return text ? JSON.parse(text) : null;
|
||||
}
|
||||
async function expert(firstName, role, caseIds) {
|
||||
const { user } = await req('/admin/users', { firstName, lastName: 'Technical test ' + suffix, role, caseIds }, 201);
|
||||
created.users.push(user.id);
|
||||
return models.User.findByPk(user.id);
|
||||
}
|
||||
async function login(user) {
|
||||
return req('/auth/login', { login: user.login, password: user.passwordForAdmin });
|
||||
}
|
||||
try {
|
||||
token = (await req('/auth/login', { login: admin.login, password: admin.password })).token;
|
||||
for (const name of ['A', 'B']) {
|
||||
const { case: task } = await req('/admin/cases', { name: 'Technical ' + name + ' ' + suffix }, 201);
|
||||
created.cases.push(task.id);
|
||||
}
|
||||
const [caseId, otherCaseId] = created.cases;
|
||||
for (const name of ['A', 'B']) {
|
||||
const { team } = await req(`/admin/cases/${caseId}/teams`, { name }, 201);
|
||||
created.teams.push(team.id);
|
||||
}
|
||||
const [teamId, secondTeamId] = created.teams;
|
||||
const regular = await expert('Regular', 'expert', [caseId]);
|
||||
const technical = await expert('Technical', 'technical', [caseId]);
|
||||
const other = await expert('Other technical', 'technical', [otherCaseId]);
|
||||
await req('/admin/users', { firstName: 'Conflict', lastName: suffix, role: 'technical', caseIds: [caseId] }, 409);
|
||||
assert.equal(await models.User.count({ where: { firstName: 'Conflict', lastName: suffix }, paranoid: false }), 0);
|
||||
await req('/admin/users', { firstName: 'Invalid', lastName: suffix, role: 'admin' }, 400);
|
||||
await req(`/admin/users/${other.id}/cases`, { caseIds: [caseId, otherCaseId] }, 409, token, 'PUT');
|
||||
assert.deepEqual(
|
||||
(await other.getCases()).map(task => task.id),
|
||||
[otherCaseId]
|
||||
);
|
||||
await req(
|
||||
`/admin/users/${regular.id}`,
|
||||
{ firstName: regular.firstName, lastName: regular.lastName, login: regular.login, role: 'technical' },
|
||||
409,
|
||||
token,
|
||||
'PUT'
|
||||
);
|
||||
assert.equal((await regular.reload()).role, 'expert');
|
||||
const techLogin = await login(technical),
|
||||
regularLogin = await login(regular);
|
||||
assert.equal(techLogin.user.role, 'technical');
|
||||
const techToken = techLogin.token,
|
||||
regularToken = regularLogin.token;
|
||||
assert.equal((await req('/auth/user', null, 200, techToken)).user.role, 'technical');
|
||||
const save = (team, marks, auth = techToken, status = 200) =>
|
||||
req(`/cases/${caseId}/teams/${team}/marks`, { marks }, status, auth, 'PUT');
|
||||
await req('/admin/users', null, 403, techToken);
|
||||
await save(teamId, [{ markType: 10, mark: 5 }], techToken, 403);
|
||||
await req(`/cases/${caseId}/teams/${teamId}/marks`, { markType: 50, mark: 5 }, 403, techToken);
|
||||
await save(teamId, [{ markType: 20, mark: 5 }], regularToken, 403);
|
||||
await save(teamId, [{ markType: 20, mark: 6 }], techToken, 400);
|
||||
await save(
|
||||
teamId,
|
||||
[
|
||||
{ markType: 20, mark: 3 },
|
||||
{ markType: 10, mark: 5 },
|
||||
],
|
||||
techToken,
|
||||
403
|
||||
);
|
||||
assert.equal(await models.Mark.count({ where: { caseId } }), 0);
|
||||
const commentPath = `/cases/${caseId}/teams/${teamId}/marks`;
|
||||
const comment = 'Проверить обработку ошибок\nДемо работает локально. <b>Текст, не HTML</b>';
|
||||
await req(commentPath, { technicalComment: ' ' + comment + ' ' }, 200, techToken, 'PUT');
|
||||
assert.equal(await models.Mark.count({ where: { caseId } }), 0);
|
||||
assert.equal((await req(commentPath, null, 200, regularToken)).technicalComment, comment);
|
||||
assert.equal(
|
||||
(await req('/cases', null, 200, regularToken)).cases.find(c => c.id === caseId).teams.find(t => t.id === teamId)
|
||||
.technicalComment,
|
||||
comment
|
||||
);
|
||||
assert.equal(
|
||||
(await req('/admin/cases')).cases.find(c => c.id === caseId).teams.find(t => t.id === teamId).TeamInCase
|
||||
.technicalComment,
|
||||
comment
|
||||
);
|
||||
assert.equal(
|
||||
(await req(`/cases/${caseId}/teams/${secondTeamId}/marks`, null, 200, regularToken)).technicalComment,
|
||||
''
|
||||
);
|
||||
await req(
|
||||
commentPath,
|
||||
{ marks: [{ markType: 10, mark: 3 }], technicalComment: 'Forbidden' },
|
||||
403,
|
||||
regularToken,
|
||||
'PUT'
|
||||
);
|
||||
await req(commentPath, { markType: 10, mark: 3, technicalComment: 'Forbidden' }, 403, regularToken);
|
||||
assert.equal(await models.Mark.count({ where: { caseId } }), 0);
|
||||
for (const invalid of [null, 123, 'x'.repeat(5001)])
|
||||
await req(commentPath, { technicalComment: invalid }, 400, techToken, 'PUT');
|
||||
await req(commentPath, { technicalComment: 'Wrong', marks: [{ markType: 10, mark: 3 }] }, 403, techToken, 'PUT');
|
||||
assert.equal((await req(commentPath, null, 200, techToken)).technicalComment, comment);
|
||||
await req(commentPath, { technicalComment: 'x'.repeat(5000) }, 200, techToken, 'PUT');
|
||||
await req(commentPath, { technicalComment: '', marks: [] }, 200, techToken, 'PUT');
|
||||
assert.equal((await req(commentPath, null, 200, regularToken)).technicalComment, '');
|
||||
await req(commentPath, { technicalComment: comment }, 200, techToken, 'PUT');
|
||||
await req(
|
||||
`/cases/${otherCaseId}/teams/${teamId}/marks`,
|
||||
{ marks: [{ markType: 20, mark: 5 }] },
|
||||
403,
|
||||
techToken,
|
||||
'PUT'
|
||||
);
|
||||
await save(teamId, [
|
||||
{ markType: 20, mark: 0 },
|
||||
{ markType: 30, mark: 3 },
|
||||
]);
|
||||
await save(secondTeamId, [
|
||||
{ markType: 20, mark: 5 },
|
||||
{ markType: 30, mark: 5 },
|
||||
]);
|
||||
const visible = (await req('/cases', null, 200, regularToken)).cases
|
||||
.find(c => c.id === caseId)
|
||||
.teams.find(t => t.id === teamId).marks;
|
||||
assert.equal(visible.find(m => m.markType === 20).mark, 0);
|
||||
assert.equal(visible.find(m => m.markType === 30).mark, 3);
|
||||
const row = (await req('/admin/marks/details')).details
|
||||
.find(c => c.id === caseId)
|
||||
.rows.find(r => r.userId === technical.id && r.teamId === teamId);
|
||||
assert.equal(row.role, 'technical');
|
||||
assert.equal(row.total, 3);
|
||||
assert.equal(row.marks[10], null);
|
||||
let missing = (await req('/admin/marks')).noMarks;
|
||||
assert.equal(missing[technical.firstName + ' ' + technical.lastName]?.['Technical A ' + suffix], undefined);
|
||||
assert.ok(missing[regular.firstName + ' ' + regular.lastName]['Technical A ' + suffix]);
|
||||
await save(
|
||||
teamId,
|
||||
[
|
||||
{ markType: 10, mark: 5 },
|
||||
{ markType: 40, mark: 4 },
|
||||
{ markType: 50, mark: 3 },
|
||||
],
|
||||
regularToken
|
||||
);
|
||||
await save(
|
||||
secondTeamId,
|
||||
[10, 40, 50].map(markType => ({ markType, mark: 0 })),
|
||||
regularToken
|
||||
);
|
||||
missing = (await req('/admin/marks')).noMarks;
|
||||
assert.equal(missing[regular.firstName + ' ' + regular.lastName]?.['Technical A ' + suffix], undefined);
|
||||
const ranking = (await req('/admin/positions')).positions[caseId];
|
||||
assert.equal(ranking[teamId], 1);
|
||||
assert.equal(ranking[secondTeamId], 2);
|
||||
const late = await expert('Late', 'expert', [caseId]);
|
||||
assert.equal(await models.Mark.count({ where: { userId: late.id, caseId } }), 4);
|
||||
assert.equal((await req(commentPath, null, 200, (await login(late)).token)).technicalComment, comment);
|
||||
await req(`/cases/${caseId}/teams/${teamId}/marks`, { markType: 20, mark: 4 }, 200, techToken);
|
||||
assert.equal((await models.Mark.findOne({ where: { userId: late.id, caseId, teamId, markType: 20 } })).mark, 4);
|
||||
assert.equal((await models.Mark.findOne({ where: { userId: regular.id, caseId, teamId, markType: 10 } })).mark, 5);
|
||||
await req(`/admin/users/${technical.id}`, null, 204, token, 'DELETE');
|
||||
await req(`/admin/users/${other.id}/cases`, { caseIds: [caseId, otherCaseId] }, 200, token, 'PUT');
|
||||
await req(`/admin/users/${technical.id}/restore`, {}, 409);
|
||||
assert.ok((await models.User.findByPk(technical.id, { paranoid: false })).deletedAt);
|
||||
await req(`/admin/users/${other.id}/cases`, { caseIds: [otherCaseId] }, 200, token, 'PUT');
|
||||
await req(`/admin/users/${technical.id}/restore`, {});
|
||||
await req('/auth/user', null, 401, techToken);
|
||||
await req(`/admin/users/${technical.id}/cases`, { caseIds: [] }, 200, token, 'PUT');
|
||||
const race = await Promise.all(
|
||||
[technical.id, other.id].map(id =>
|
||||
fetch(base + `/admin/users/${id}/cases`, {
|
||||
method: 'PUT',
|
||||
headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ caseIds: [caseId] }),
|
||||
})
|
||||
)
|
||||
);
|
||||
assert.deepEqual(race.map(r => r.status).sort(), [200, 409]);
|
||||
for (const id of [technical.id, other.id]) await req(`/admin/users/${id}/cases`, { caseIds: [] }, 200, token, 'PUT');
|
||||
await req(
|
||||
`/admin/users/${regular.id}`,
|
||||
{ firstName: regular.firstName, lastName: regular.lastName, login: regular.login, role: 'technical' },
|
||||
200,
|
||||
token,
|
||||
'PUT'
|
||||
);
|
||||
await req('/auth/user', null, 401, regularToken);
|
||||
const converted = await login(regular);
|
||||
assert.equal(converted.user.role, 'technical');
|
||||
await save(teamId, [{ markType: 20, mark: 2 }], converted.token);
|
||||
await save(teamId, [{ markType: 10, mark: 2 }], converted.token, 403);
|
||||
const convertedRow = (await req('/admin/marks/details')).details
|
||||
.find(c => c.id === caseId)
|
||||
.rows.find(row => row.userId === regular.id && row.teamId === teamId);
|
||||
assert.equal(convertedRow.marks[10], null);
|
||||
console.log(
|
||||
'PASS technical role, two criteria only, case access, one technical per case including concurrent assignment/restore/role change, shared and late scores, missing reports, totals, no extra ranking vote and revoked session.'
|
||||
);
|
||||
} finally {
|
||||
await models.Mark.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.UserInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.TeamInCase.destroy({ where: { caseId: created.cases }, force: true });
|
||||
await models.Team.destroy({ where: { id: created.teams }, force: true });
|
||||
await models.User.destroy({ where: { id: created.users }, force: true });
|
||||
await models.Case.destroy({ where: { id: created.cases }, force: true });
|
||||
await sequelize.close();
|
||||
}
|
||||
Reference in new issue
Block a user