feat: add admin panel dto & validation

This commit is contained in:
2026-11-14 22:43:12 +03:30
parent 2d32e2679b
commit 8d6834f44c
18 changed files with 1832 additions and 52 deletions
@@ -0,0 +1,76 @@
import { describe, expect, it, jest } from '@jest/globals';
import { Repository } from 'typeorm';
import { I18nService } from 'nestjs-i18n';
import { TestsService } from '@/modules/tests/providers/tests.service';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { ResultRangeCommandProvider } from '@/modules/scoring/providers/result-range-command.provider';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionRangeRuleCommandProvider } from '@/modules/questions/providers/range-rule/question-range-rule-command.provider';
describe.each(['result', 'question'] as const)('%s range updates', (kind) => {
function setup(overlaps: unknown[]) {
const andWhere = jest.fn<(...args: unknown[]) => unknown>();
const builder = {
where: jest.fn<(...args: unknown[]) => unknown>(),
andWhere,
getMany: jest.fn<() => Promise<unknown[]>>().mockResolvedValue(overlaps),
};
builder.where.mockReturnValue(builder);
andWhere.mockReturnValue(builder);
const save = jest
.fn<(value: unknown) => Promise<unknown>>()
.mockImplementation((value) => Promise.resolve(value));
const repository = {
createQueryBuilder: () => builder,
findOne: () =>
Promise.resolve({
id: 7,
test: { id: 2 },
question: { id: 3 },
minScore: 0,
maxScore: 5,
min: 0,
max: 5,
}),
save,
};
const update =
kind === 'result'
? () =>
new ResultRangeCommandProvider(
repository as unknown as Repository<ResultRange>,
{} as TestsService,
{} as I18nService,
).updateOne(7, { minScore: 20, maxScore: 30 })
: () =>
new QuestionRangeRuleCommandProvider(
repository as unknown as Repository<QuestionRangeRule>,
{} as Repository<Question>,
{} as I18nService,
).updateOne(7, { min: 20, max: 30 });
return { update, andWhere, save };
}
it('rejects even one overlapping different record after moving a range', async () => {
const { update, andWhere, save } = setup([{ id: 99 }]);
await expect(update()).rejects.toThrow();
expect(andWhere).toHaveBeenCalledWith(
expect.stringContaining('id != :excludeId'),
{ excludeId: 7 },
);
expect(save).not.toHaveBeenCalled();
});
it('allows non-overlapping edits and preserves entity relations', async () => {
const { update, save } = setup([]);
await update();
expect(save).toHaveBeenCalledWith(
expect.objectContaining(
kind === 'result'
? { test: { id: 2 }, testId: 2, minScore: 20, maxScore: 30 }
: { question: { id: 3 }, questionId: 3, min: 20, max: 30 },
),
);
});
});
@@ -0,0 +1,103 @@
import { Resource } from '@adminjs/typeorm';
import { BaseRecord, Filter, ValidationError, flat } from 'adminjs';
import { BaseEntity } from 'typeorm';
export type PanelWrite = (
operation: 'new' | 'edit' | 'delete',
params: Record<string, unknown>,
id?: number,
) => Promise<Record<string, unknown>>;
/** No AdminJS write is allowed to fall back to the raw TypeORM adapter. */
export class AdminPanelResource extends Resource {
constructor(
model: typeof BaseEntity,
private readonly write?: PanelWrite,
) {
super(model);
}
private async persist(
operation: 'new' | 'edit' | 'delete',
params: Record<string, unknown>,
id?: string | number,
) {
if (!this.write)
throw new ValidationError({}, { message: 'این منبع فقط خواندنی است.' });
if (
id !== undefined &&
(!Number.isSafeInteger(Number(id)) || Number(id) < 1)
) {
throw new ValidationError({}, { message: 'شناسه نامعتبر است.' });
}
if (
Object.keys(params).some((key) =>
key
.split('.')
.some((part) =>
['__proto__', 'prototype', 'constructor'].includes(part),
),
)
) {
throw new ValidationError({}, { message: 'فیلد نامعتبر است.' });
}
const unflatten = (
flat as unknown as {
unflatten: (input: Record<string, unknown>) => Record<string, unknown>;
}
).unflatten;
return this.write(
operation,
unflatten(params),
id === undefined ? undefined : Number(id),
);
}
override create(params: Record<string, unknown>) {
return this.persist('new', params);
}
override update(id: string | number, params: Record<string, unknown> = {}) {
return this.persist('edit', params, id);
}
override delete(id: string | number) {
return this.persist('delete', {}, id);
}
// Visibility settings only affect the UI. Remove credentials from the
// actual records too, including reference-population and search responses.
private redact(record: BaseRecord | null) {
if (record) {
delete record.params.password;
for (const key of ['metadata', 'condition']) {
const value: unknown = record.get(key);
if (value && typeof value === 'object') {
Object.keys(record.params)
.filter((path) => path === key || path.startsWith(`${key}.`))
.forEach((path) => {
delete record.params[path];
});
record.params[key] = JSON.stringify(value);
}
}
}
return record;
}
override async findOne(id: string | number) {
return this.redact(await super.findOne(id));
}
override async find(filter: Filter, params: unknown) {
const records = await super.find(filter, params);
records.forEach((record) => this.redact(record));
return records;
}
override async findMany(ids: Array<string | number>) {
const records = await super.findMany(ids);
records.forEach((record) => this.redact(record));
return records;
}
}
@@ -0,0 +1,371 @@
import {
beforeAll,
beforeEach,
describe,
expect,
it,
jest,
} from '@jest/globals';
import AdminJS, {
ActionContext,
ActionRequest,
ResourceWithOptions,
} from 'adminjs';
import { INestApplication } from '@nestjs/common';
import { DataSource } from 'typeorm';
import { I18nService } from 'nestjs-i18n';
import { Role } from '@/common/enums/roles.enum';
import { User } from '@/modules/users/entities/user.entity';
import { UsersService } from '@/modules/users/providers/users.service';
import { Test } from '@/modules/tests/entities/test.entity';
import { TestStatus } from '@/modules/tests/enums/test-status.enum';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionType } from '@/modules/questions/enums/question-type.enum';
import { Choice } from '@/modules/questions/entities/choice.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionTransition } from '@/modules/questions/entities/question-transition.entity';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { Submission } from '@/modules/submissions/entities/submission.entity';
import { SubmissionAnswer } from '@/modules/submissions/entities/submission-answer.entity';
import { SubmissionResult } from '@/modules/submissions/entities/submission-result.entity';
import { Conversation } from '@/modules/conversation/entities/conversation.entity';
import { Message } from '@/modules/conversation/entities/message.entity';
import { buildAdminPanelResources } from './admin-panel.resources';
import { AdminPanelResource } from './admin-panel.resource';
import { panelValues, redactPanelSecrets } from './admin-panel.validation';
describe('AdminJS validated resources', () => {
const database = new DataSource({
type: 'postgres',
entities: [
User,
Test,
Question,
Choice,
QuestionRangeRule,
QuestionTransition,
ResultRange,
Submission,
SubmissionAnswer,
SubmissionResult,
Conversation,
Message,
],
});
let definitions: ResourceWithOptions[];
let query: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
let commands: {
createOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
updateOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
deleteOne: jest.Mock<(...args: unknown[]) => Promise<unknown>>;
};
let users: {
findOneById: jest.Mock<UsersService['findOneById']>;
updateProfile: jest.Mock<UsersService['updateProfile']>;
};
const resource = (name: string) =>
definitions.find(
({ resource: entry }) => (entry as AdminPanelResource).id() === name,
)!.resource as AdminPanelResource;
beforeAll(async () => {
// Build real TypeORM relation metadata without connecting to a database.
await (
database as unknown as { buildMetadatas(): Promise<void> }
).buildMetadatas();
});
beforeEach(() => {
jest.restoreAllMocks();
commands = {
createOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue({ data: { id: 11 } }),
updateOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue({ id: 11 }),
deleteOne: jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue(undefined),
};
users = {
findOneById: jest.fn<UsersService['findOneById']>().mockResolvedValue(
Object.assign(new User(), {
id: 1,
phone: '09121111111',
role: Role.USER,
password: 'secret-hash',
}),
),
updateProfile: jest
.fn<UsersService['updateProfile']>()
.mockResolvedValue({ message: 'updated' }),
};
query = jest
.fn<(...args: unknown[]) => Promise<unknown>>()
.mockResolvedValue([{ acquired: true }]);
jest.spyOn(database, 'createQueryRunner').mockReturnValue({
connect: () => Promise.resolve(undefined),
query,
release: () => Promise.resolve(undefined),
} as unknown as ReturnType<DataSource['createQueryRunner']>);
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), { id: 2, status: TestStatus.IN_PROGRESS }),
);
jest
.spyOn(database.getRepository(Submission), 'existsBy')
.mockResolvedValue(false);
jest
.spyOn(database.getRepository(Question), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Question(), {
id: 11,
testId: 2,
type: QuestionType.SINGLE_CHOICE,
content: 'Question',
weight: 1,
required: true,
metadata: null,
}),
);
const app = {
get: (token: unknown) =>
token === DataSource
? database
: token === UsersService
? users
: token === I18nService
? { translate: (message: string) => message }
: commands,
} as unknown as INestApplication;
definitions = buildAdminPanelResources(app);
});
it('builds the real AdminJS schema without duplicates or an OTP resource', () => {
const admin = new AdminJS({ resources: definitions });
const ids = admin.resources.map((entry) => entry.id());
expect(new Set(ids).size).toBe(ids.length);
expect(ids).not.toContain('OTP');
expect(
resource('QuestionTransition')
.properties()
.map((property) => property.path()),
).toContain('test.id');
});
it('validates and converts form values before using the question provider', async () => {
await resource('Question').create({
testId: '2',
content: 'New question',
type: QuestionType.SINGLE_CHOICE,
required: 'false',
weight: '2',
metadata: '{"allowOther":false}',
});
expect(commands.createOne).toHaveBeenCalledWith(
expect.objectContaining({
test: 2,
required: false,
weight: 2,
metadata: { allowOther: false },
}),
);
expect(query.mock.calls.map(([sql]) => sql)).toEqual([
'SELECT pg_try_advisory_lock(724091, 1) AS acquired',
'SELECT pg_advisory_unlock(724091, 1)',
]);
});
it('rejects invalid DTOs and forged system fields without calling providers', async () => {
await expect(
resource('Question').create({ testId: 2, content: '' }),
).rejects.toThrow();
await expect(
resource('Test').create({
title: 'Test',
description: 'Description',
questionsCount: 999,
}),
).rejects.toThrow();
expect(commands.createOne).not.toHaveBeenCalled();
});
it('rejects concurrent panel writes without waiting and holding the connection pool', async () => {
query.mockResolvedValue([{ acquired: false }]);
await expect(
resource('Question').create({ testId: 2, content: 'Question' }),
).rejects.toThrow();
expect(commands.createOne).not.toHaveBeenCalled();
expect(query).toHaveBeenCalledTimes(1);
});
it('converts the generated test.id reference and null transition endpoints', async () => {
await resource('QuestionTransition').create({
'test.id': '2',
fromQuestionId: '',
toQuestionId: '11',
type: 'start',
condition: '',
});
expect(commands.createOne).toHaveBeenCalledWith(
expect.objectContaining({
test: 2,
fromQuestion: null,
toQuestion: 11,
conditionValue: null,
}),
);
});
it('blocks structural changes to published tests', async () => {
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), { id: 2, status: TestStatus.PUBLISHED }),
);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('keeps previously published structure locked even after unpublishing', async () => {
jest
.spyOn(database.getRepository(Test), 'findOneByOrFail')
.mockResolvedValue(
Object.assign(new Test(), {
id: 2,
status: TestStatus.IN_PROGRESS,
structureLocked: true,
}),
);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('blocks structural changes and cascaded deletion when a test has submissions', async () => {
jest
.spyOn(database.getRepository(Submission), 'existsBy')
.mockResolvedValue(true);
await expect(
resource('Question').update(11, { content: 'Changed' }),
).rejects.toThrow();
await expect(resource('Test').delete(2)).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
expect(commands.deleteOne).not.toHaveBeenCalled();
});
it('rejects moving questions between tests', async () => {
await expect(
resource('Question').update(11, { testId: 3 }),
).rejects.toThrow();
expect(commands.updateOne).not.toHaveBeenCalled();
});
it('disables direct writes to history, conversations and users creation/deletion', async () => {
for (const name of [
'Submission',
'SubmissionAnswer',
'SubmissionResult',
'Conversation',
'Message',
]) {
await expect(resource(name).update(1, {})).rejects.toThrow();
await expect(resource(name).delete(1)).rejects.toThrow();
}
await expect(resource('User').create({})).rejects.toThrow();
await expect(resource('User').delete(1)).rejects.toThrow();
});
it('routes password changes through profile validation and hashing provider path', async () => {
const result = await resource('User').update(1, {
newPassword: 'StrongPass1!',
confirmPassword: 'StrongPass1!',
});
expect(users.updateProfile).toHaveBeenCalledWith(
expect.objectContaining({ id: 1 }),
expect.objectContaining({
password: 'StrongPass1!',
confirmPassword: 'StrongPass1!',
}),
);
expect(result).not.toHaveProperty('password');
await expect(
resource('User').update(1, { role: Role.SUPERUSER }),
).rejects.toThrow();
await expect(
resource('User').update(1, { newPassword: 'StrongPass1!' }),
).rejects.toThrow();
});
it('rechecks the current database role instead of trusting the session', async () => {
jest
.spyOn(database.getRepository(User), 'findOneBy')
.mockResolvedValue(Object.assign(new User(), { id: 1, role: Role.USER }));
const action = definitions.find(
({ resource: entry }) => (entry as AdminPanelResource).id() === 'Test',
)!.options.actions!.list!;
const context = {
currentAdmin: { id: '1', role: Role.SUPERUSER },
} as unknown as ActionContext;
const before = action.before as (
request: ActionRequest,
context: ActionContext,
) => Promise<ActionRequest>;
await expect(
before(
{ method: 'get', params: { resourceId: 'Test', action: 'list' } },
context,
),
).rejects.toThrow();
});
it('does not leak secrets through nested or failed-form responses', () => {
const response = {
record: {
params: {
password: 'hash',
newPassword: 'plain',
confirmPassword: 'plain',
firstName: 'Name',
},
populated: { user: { params: { password: 'hash' } } },
},
};
redactPanelSecrets(response);
expect(JSON.stringify(response)).not.toMatch(/hash|plain/);
expect(response.record.params.firstName).toBe('Name');
});
it('does not leak submitted passwords through i18n validation errors', async () => {
try {
await resource('User').update(1, {
newPassword: 'secret',
confirmPassword: 'secret',
});
throw new Error('Expected validation failure');
} catch (error) {
expect(error).toHaveProperty('propertyErrors.newPassword');
expect(JSON.stringify(error)).not.toContain('secret');
}
expect(users.updateProfile).not.toHaveBeenCalled();
});
it('rejects false-like boolean coercion and unsafe numeric values', () => {
expect(
panelValues([{ name: 'required', kind: 'boolean' }], {
required: 'false',
}),
).toEqual({ required: false });
expect(() =>
panelValues([{ name: 'weight', kind: 'number' }], { weight: '1.5' }),
).toThrow();
expect(() =>
panelValues([{ name: 'required', kind: 'boolean' }], { required: 'no' }),
).toThrow();
});
});
@@ -0,0 +1,553 @@
import { HttpException, INestApplication } from '@nestjs/common';
import { BaseEntity, DataSource } from 'typeorm';
import { ClassConstructor } from 'class-transformer';
import {
ActionContext,
ActionRequest,
ActionResponse,
ForbiddenError,
ResourceWithOptions,
ValidationError,
} from 'adminjs';
import { I18nService } from 'nestjs-i18n';
import { Role } from '@/common/enums/roles.enum';
import { User } from '@/modules/users/entities/user.entity';
import { UsersService } from '@/modules/users/providers/users.service';
import { UpdateProfileDTO } from '@/modules/users/dtos/update-profile.dto';
import { Test } from '@/modules/tests/entities/test.entity';
import { TestStatus } from '@/modules/tests/enums/test-status.enum';
import { TestsService } from '@/modules/tests/providers/tests.service';
import { CreateTestDTO } from '@/modules/tests/dtos/create-test.dto';
import { UpdateTestDTO } from '@/modules/tests/dtos/update-test.dto';
import { Question } from '@/modules/questions/entities/question.entity';
import { QuestionType } from '@/modules/questions/enums/question-type.enum';
import { Choice } from '@/modules/questions/entities/choice.entity';
import { QuestionRangeRule } from '@/modules/questions/entities/question-range-rule.entity';
import { QuestionTransition } from '@/modules/questions/entities/question-transition.entity';
import { QuestionsService } from '@/modules/questions/providers/questions.service';
import { ChoicesService } from '@/modules/questions/providers/choices/choices.service';
import { QuestionRangeRuleService } from '@/modules/questions/providers/range-rule/question-range-rule.service';
import { QuestionTransitionService } from '@/modules/questions/providers/transition/question-transition.service';
import { CreateQuestionDTO } from '@/modules/questions/dtos/create-question.dto';
import { CreateChoiceDTO } from '@/modules/questions/dtos/create-choice.dto';
import { CreateQuestionRangeRuleDTO } from '@/modules/questions/dtos/create-question-range-rule.dto';
import { CreateQuestionTransitionDTO } from '@/modules/questions/dtos/create-question-transition.dto';
import { ResultRange } from '@/modules/scoring/entities/result-range.entity';
import { ResultRangeService } from '@/modules/scoring/providers/result-range.service';
import { CreateResultRangeDTO } from '@/modules/scoring/dtos/create-result-range.dto';
import { Submission } from '@/modules/submissions/entities/submission.entity';
import { SubmissionAnswer } from '@/modules/submissions/entities/submission-answer.entity';
import { SubmissionResult } from '@/modules/submissions/entities/submission-result.entity';
import { Conversation } from '@/modules/conversation/entities/conversation.entity';
import { Message } from '@/modules/conversation/entities/message.entity';
import { AdminPanelResource, PanelWrite } from './admin-panel.resource';
import {
panelValues,
PanelField,
redactPanelSecrets,
validatePanelDto,
} from './admin-panel.validation';
const field = (
name: string,
kind?: PanelField['kind'],
dto?: string,
): PanelField => ({ name, kind, dto });
const reject = (message: string): never => {
throw new ValidationError({}, { message });
};
export function buildAdminPanelResources(
app: INestApplication,
): ResourceWithOptions[] {
const database = app.get(DataSource);
const users = app.get(UsersService);
const i18n: I18nService = app.get(I18nService);
const authorize = async (request: ActionRequest, context: ActionContext) => {
const id = Number(context.currentAdmin?.id);
const actor = Number.isSafeInteger(id)
? await database.getRepository(User).findOneBy({ id })
: null;
if (!actor || ![Role.ADMIN, Role.SUPERUSER].includes(actor.role))
throw new ForbiddenError('دسترسی مدیریت ندارید.');
// Refresh authorization on every request rather than trusting a stale session.
context.currentAdmin = { ...context.currentAdmin!, role: actor.role };
return request;
};
const staff = ({ currentAdmin }: ActionContext) =>
[Role.ADMIN, Role.SUPERUSER].includes(currentAdmin?.role as Role);
const superuser = ({ currentAdmin }: ActionContext) =>
currentAdmin?.role === Role.SUPERUSER;
const redact = (response: ActionResponse) => {
redactPanelSecrets(response);
return response;
};
const protectTest = async (id: number, structure: boolean) => {
const test = await database.getRepository(Test).findOneByOrFail({ id });
if (
structure &&
(test.structureLocked || test.status === TestStatus.PUBLISHED)
)
reject(
'ساختار آزمونی که منتشر شده قابل تغییر یا حذف نیست؛ آزمون جدید بسازید.',
);
if (await database.getRepository(Submission).existsBy({ testId: id }))
reject(
'این آزمون سابقه پاسخ دارد؛ برای تغییر ساختار یا حذف، آزمون جدید بسازید.',
);
};
// Providers use their own repositories. A shared session-level advisory lock
// serializes all panel writes across app instances without bypassing providers.
const serialize =
(write: PanelWrite): PanelWrite =>
async (...args) => {
const runner = database.createQueryRunner();
await runner.connect();
let locked = false;
try {
const locks = (await runner.query(
'SELECT pg_try_advisory_lock(724091, 1) AS acquired',
)) as Array<{ acquired: boolean }>;
if (!locks[0]?.acquired)
reject(
'درخواست مدیریتی دیگری در حال ذخیره‌سازی است؛ دوباره تلاش کنید.',
);
locked = true;
return await write(...args);
} catch (error) {
if (error instanceof ValidationError) throw error;
if (error instanceof HttpException && error.getStatus() < 500) {
const response = error.getResponse();
const details =
typeof response === 'string'
? { message: response }
: (response as {
message?: string;
params?: Record<string, unknown>;
});
const message = i18n.translate(details.message ?? error.message, {
lang: 'fa',
args: details.params,
});
return reject(String(message));
}
// Do not expose SQL, password hashes or database internals to the browser.
return reject(
'ذخیره‌سازی انجام نشد؛ داده‌ها و وابستگی‌های رکورد را بررسی کنید.',
);
} finally {
try {
if (locked)
await runner.query('SELECT pg_advisory_unlock(724091, 1)');
} finally {
await runner.release();
}
}
};
function resource(
model: typeof BaseEntity,
fields: PanelField[],
write?: PanelWrite,
sensitive = false,
): ResourceWithOptions {
const canRead = sensitive ? superuser : staff;
return {
resource: new AdminPanelResource(model, write && serialize(write)),
options: {
editProperties: fields.map(({ name }) =>
name === 'test' ? 'test.id' : name,
),
properties: {
password: { isVisible: false },
newPassword: {
type: 'password',
isVisible: {
list: false,
filter: false,
show: false,
edit: model === User,
},
},
confirmPassword: {
type: 'password',
isVisible: {
list: false,
filter: false,
show: false,
edit: model === User,
},
},
...(model === QuestionTransition
? { condition: { type: 'textarea' } }
: {}),
...(model === Question ? { metadata: { type: 'textarea' } } : {}),
},
actions: {
list: { before: authorize, after: redact, isAccessible: canRead },
show: { before: authorize, after: redact, isAccessible: canRead },
search: { before: authorize, after: redact, isAccessible: canRead },
new: {
before: authorize,
after: redact,
isAccessible: write && model !== User ? staff : false,
},
edit: {
before: authorize,
after: redact,
isAccessible: write ? (model === User ? superuser : staff) : false,
},
// Destructive cascades and account removal need a dedicated workflow.
delete: {
before: authorize,
after: redact,
isAccessible: write && model !== User ? staff : false,
},
bulkDelete: { isAccessible: false, isVisible: false },
},
},
};
}
function catalog<T extends object>(
model: typeof BaseEntity,
fields: PanelField[],
dto: ClassConstructor<T>,
commands: {
createOne: (values: T) => Promise<unknown>;
updateOne: (id: number, values: T) => Promise<unknown>;
deleteOne: (id: number) => Promise<unknown>;
},
) {
return resource(model, fields, async (operation, params, id) => {
const repository = database.getRepository(model);
const existing =
id === undefined
? undefined
: await repository.findOneByOrFail({ id } as never);
const current = (existing ?? {}) as unknown as Record<string, unknown>;
const input = panelValues(fields, params, current);
const original = panelValues(
fields,
Object.fromEntries(
fields
.filter(({ name }) => Object.hasOwn(current, name))
.map(({ name }) => [name, current[name]]),
),
);
// The generated transition FK is named test.id by TypeORM.
if (model === QuestionTransition && existing) {
const transition = await database
.getRepository(QuestionTransition)
.findOneOrFail({ where: { id }, relations: { test: true } });
original.test = transition.test.id;
}
const merged = { ...original, ...input };
const parent =
model === Question ||
model === ResultRange ||
model === QuestionTransition
? 'test'
: 'question';
if (
existing &&
input[parent] !== undefined &&
merged[parent] !== undefined
) {
const previous = original[parent];
if (Number(input[parent]) !== Number(previous))
reject(
'جابجایی این رکورد به آزمون یا سؤال دیگر مجاز نیست؛ رکورد جدید بسازید.',
);
}
const parentId = Number(merged[parent]);
const testId =
parent === 'test'
? parentId
: (
await database
.getRepository(Question)
.findOneByOrFail({ id: parentId })
).testId;
await protectTest(testId, true);
if (model === Choice || model === QuestionRangeRule) {
const question = await database
.getRepository(Question)
.findOneByOrFail({ id: parentId });
if (
model === Choice &&
![QuestionType.SINGLE_CHOICE, QuestionType.MULTI_CHOICE].includes(
question.type,
)
)
reject('گزینه فقط برای سؤال انتخابی قابل تعریف است.');
if (
model === QuestionRangeRule &&
question.type !== QuestionType.NUMERIC
)
reject('قانون بازه فقط برای سؤال عددی قابل تعریف است.');
}
if (model === Question && existing && merged.type !== current.type) {
const question = await database.getRepository(Question).findOneOrFail({
where: { id },
relations: {
choices: true,
rangeRules: true,
outgoingTransitions: true,
incomingTransitions: true,
},
});
if (
question.choices.length ||
question.rangeRules?.length ||
question.outgoingTransitions.length ||
question.incomingTransitions.length
)
reject(
'قبل از تغییر نوع سؤال، گزینه‌ها، قوانین و مسیرهای وابسته را تعیین تکلیف کنید.',
);
}
if (operation === 'delete') {
if (model === Choice) {
const transitions = await database
.getRepository(QuestionTransition)
.findBy({ fromQuestionId: parentId });
if (
transitions.some(
({ condition }) =>
condition &&
(('choiceId' in condition && condition.choiceId === id) ||
('choiceIds' in condition &&
condition.choiceIds.includes(id!))),
)
)
reject(
'این گزینه در شرط یک مسیر استفاده شده است؛ ابتدا مسیر را اصلاح کنید.',
);
}
await commands.deleteOne(id!);
return {};
}
const validated = await validatePanelDto(
dto,
merged,
i18n,
Object.fromEntries(
fields.map(({ name, dto: dtoName }) => [
dtoName ?? name,
name === 'test' ? 'test.id' : name,
]),
),
);
const result =
operation === 'new'
? await commands.createOne(validated)
: await commands.updateOne(id!, validated);
if (operation === 'edit')
return (await repository.findOneByOrFail({
id,
} as never)) as unknown as Record<string, unknown>;
const entity =
result && typeof result === 'object' && 'data' in result
? result.data
: result;
return entity as Record<string, unknown>;
});
}
const tests = app.get(TestsService);
const testFields = [
field('title'),
field('description'),
field('accessType'),
field('price'),
field('isActive', 'boolean'),
field('status'),
];
const testResource = resource(
Test,
testFields,
async (operation, params, id) => {
const existing =
id === undefined
? undefined
: await database.getRepository(Test).findOneByOrFail({ id });
const values = panelValues(
testFields,
params,
existing as unknown as Record<string, unknown>,
);
if (typeof values.price === 'number') {
if (!Number.isSafeInteger(values.price))
reject('مبلغ را به صورت عدد صحیح وارد کنید.');
values.price = values.price.toString();
}
if (operation === 'delete') {
await protectTest(id!, true);
await tests.deleteOne(id!);
return {};
}
const complete = {
...(existing &&
panelValues(
testFields,
Object.fromEntries(
testFields.map(({ name }) => [
name,
(existing as unknown as Record<string, unknown>)[name],
]),
),
)),
...values,
};
const status = complete.status;
delete complete.status;
const validated = await validatePanelDto(CreateTestDTO, complete, i18n);
if (
validated.price != null &&
BigInt(validated.price) > 9223372036854775807n
)
reject('مبلغ خارج از محدوده مجاز است.');
if (
validated.isActive &&
(status ?? TestStatus.IN_PROGRESS) !== TestStatus.PUBLISHED
)
reject('فقط آزمون منتشرشده می‌تواند فعال باشد.');
if (operation === 'new') {
if (status !== undefined && status !== TestStatus.IN_PROGRESS)
reject('آزمون جدید باید ابتدا پیش‌نویس باشد.');
return (await tests.createOne(validated)).data as unknown as Record<
string,
unknown
>;
}
const update = await validatePanelDto(
UpdateTestDTO,
{
...validated,
status,
},
i18n,
);
return (await tests.updateOne(id!, update)) as unknown as Record<
string,
unknown
>;
},
);
const userFields = [
field('firstName'),
field('lastName'),
field('newPassword', undefined, 'password'),
field('confirmPassword'),
];
const userResource = resource(
User,
userFields,
async (operation, params, id) => {
if (operation !== 'edit')
reject('ساخت و حذف مستقیم حساب کاربری مجاز نیست.');
const user = await users.findOneById(id!);
const input = panelValues(
userFields,
params,
user as unknown as Record<string, unknown>,
);
if (input.password === '') delete input.password;
if (input.confirmPassword === '') delete input.confirmPassword;
if (input.password !== undefined && input.confirmPassword === undefined)
reject('تکرار رمز عبور الزامی است.');
if (input.password === undefined && input.confirmPassword !== undefined)
reject('رمز عبور جدید را هم وارد کنید.');
if (
typeof input.password === 'string' &&
Buffer.byteLength(input.password, 'utf8') > 72
)
reject('رمز عبور نباید بیشتر از ۷۲ بایت باشد.');
const validated = await validatePanelDto(UpdateProfileDTO, input, i18n, {
password: 'newPassword',
});
if (Object.keys(input).length) await users.updateProfile(user, validated);
const updated = await users.findOneById(id!);
const safe = { ...updated };
delete safe.password;
return safe;
},
true,
);
return [
testResource,
catalog(
Question,
[
field('testId', 'number', 'test'),
field('type'),
field('content'),
field('weight', 'number'),
field('required', 'boolean'),
field('metadata', 'json'),
],
CreateQuestionDTO,
app.get(QuestionsService),
),
catalog(
Choice,
[
field('questionId', 'number', 'question'),
field('text'),
field('order', 'number'),
field('score', 'number'),
],
CreateChoiceDTO,
app.get(ChoicesService),
),
catalog(
QuestionRangeRule,
[
field('questionId', 'number', 'question'),
field('min', 'number'),
field('max', 'number'),
field('score', 'number'),
],
CreateQuestionRangeRuleDTO,
app.get(QuestionRangeRuleService),
),
catalog(
QuestionTransition,
[
field('test', 'number'),
field('fromQuestionId', 'number', 'fromQuestion'),
field('toQuestionId', 'number', 'toQuestion'),
field('type'),
field('condition', 'json', 'conditionValue'),
],
CreateQuestionTransitionDTO,
app.get(QuestionTransitionService),
),
catalog(
ResultRange,
[
field('testId', 'number', 'test'),
field('minScore', 'number'),
field('maxScore', 'number'),
field('title'),
field('description'),
],
CreateResultRangeDTO,
app.get(ResultRangeService),
),
userResource,
...[
Submission,
SubmissionAnswer,
SubmissionResult,
Conversation,
Message,
].map((model) => resource(model, [], undefined, true)),
];
}
+2 -32
View File
@@ -5,7 +5,7 @@ import type { Express, Request, Response, NextFunction } from 'express';
import AdminJS from 'adminjs';
import AdminJSExpress from '@adminjs/express';
import { Database, Resource } from '@adminjs/typeorm';
import { User } from '@/modules/users/entities/user.entity';
import { buildAdminPanelResources } from './admin-panel.resources';
import { RedisService } from '@/common/modules/redis/providers/redis.service';
import { AdminPanelAuthenticator } from './providers/admin-panel-auth.provider';
import { AdminPanelSessionStore } from './admin-panel-session.store';
@@ -72,18 +72,6 @@ export class AdminPanelSetup {
baseEntity.useDataSource?.(dataSource);
}
// Register every real entity automatically (new entities show up without
// any change here). Auto-generated ManyToMany junction metadatas have no
// entity class behind them and are skipped — they are managed through the
// owning relation instead.
const autoResources = dataSource.entityMetadatas
.map((m) => m.target)
.filter(
(target) =>
typeof (target as { getRepository?: unknown }).getRepository ===
'function',
);
const adminJs = new AdminJS({
rootPath: configService.get<string>('admin.rootPath'),
locale: {
@@ -95,25 +83,7 @@ export class AdminPanelSetup {
withMadeWithLove: false,
logo: false,
},
resources: [
...autoResources,
{
resource: User,
options: {
properties: {
// Never expose password hashes in tables and detail views
password: {
isVisible: {
list: false,
filter: false,
show: false,
edit: true,
},
},
},
},
},
],
resources: buildAdminPanelResources(app),
});
const authenticator = app.get(AdminPanelAuthenticator);
@@ -0,0 +1,136 @@
import { plainToInstance, ClassConstructor } from 'class-transformer';
import { validate, ValidationError as DtoError } from 'class-validator';
import { ValidationError } from 'adminjs';
import { I18nService } from 'nestjs-i18n';
export async function validatePanelDto<T extends object>(
type: ClassConstructor<T>,
values: Record<string, unknown>,
i18n?: I18nService,
aliases: Record<string, string> = {},
): Promise<T> {
const dto = plainToInstance(type, values);
const errors = await validate(dto, {
whitelist: true,
forbidNonWhitelisted: true,
forbidUnknownValues: true,
});
if (errors.length) {
const fields: Record<string, { message: string }> = {};
const collect = (items: DtoError[], prefix = '') => {
for (const error of items) {
const key = prefix + (aliases[error.property] ?? error.property);
if (error.constraints)
fields[key] = {
message: Object.values(error.constraints)
.map((message) => {
const separator = message.indexOf('|');
if (separator < 0) return message;
const translationKey = message.slice(0, separator);
// i18nValidationMessage embeds the submitted value in JSON.
// Never return that raw payload (especially for passwords).
const args = JSON.parse(message.slice(separator + 1)) as Record<
string,
unknown
>;
delete args.value;
return i18n
? String(i18n.translate(translationKey, { lang: 'fa', args }))
: 'مقدار این فیلد معتبر نیست.';
})
.join('؛ '),
};
collect(error.children ?? [], `${key}.`);
}
};
collect(errors);
throw new ValidationError(fields, {
message: 'اطلاعات فرم معتبر نیست؛ فیلدهای مشخص‌شده را بررسی کنید.',
});
}
return dto;
}
export type PanelField = {
name: string;
dto?: string;
kind?: 'number' | 'boolean' | 'json';
};
export function redactPanelSecrets(value: unknown): void {
if (!value || typeof value !== 'object') return;
for (const [key, nested] of Object.entries(value)) {
// Validation errors contain safe, rendered messages, not submitted values.
if (key === 'errors') continue;
if (
['password', 'newPassword', 'confirmPassword'].includes(key.split('.')[0])
)
delete (value as Record<string, unknown>)[key];
else redactPanelSecrets(nested);
}
}
/** Convert only declared editable fields; reject mass assignment server-side. */
export function panelValues(
fields: PanelField[],
params: Record<string, unknown>,
existing: Record<string, unknown> = {},
) {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(params)) {
const field = fields.find((item) => item.name === key);
if (!field) {
const previous = existing[key];
const comparable = (input: unknown) =>
input instanceof Date ? input.toISOString() : String(input);
if (
Object.hasOwn(existing, key) &&
comparable(previous) === comparable(value)
)
continue;
throw new ValidationError({
[key]: { message: 'تغییر این فیلد مجاز نیست.' },
});
}
if (value === undefined) continue;
let converted: unknown = value;
if (field.kind === 'number' && value !== null && value !== '') {
const numeric =
value &&
typeof value === 'object' &&
Object.keys(value).length === 1 &&
'id' in value
? value.id
: value;
converted =
typeof numeric === 'number'
? numeric
: typeof numeric === 'string'
? Number(numeric)
: NaN;
if (!Number.isFinite(converted) || !Number.isSafeInteger(converted))
throw new ValidationError({
[key]: { message: 'عدد صحیح معتبر وارد کنید.' },
});
}
if (field.kind === 'number' && value === '') converted = null;
if (field.kind === 'boolean') {
if (![true, false, 'true', 'false'].includes(value as boolean))
throw new ValidationError({
[key]: { message: 'مقدار بولی معتبر وارد کنید.' },
});
converted = value === true || value === 'true';
}
if (field.kind === 'json' && typeof value === 'string') {
try {
converted = value === '' ? null : (JSON.parse(value) as unknown);
} catch {
throw new ValidationError({
[key]: { message: 'JSON معتبر وارد کنید.' },
});
}
}
result[field.dto ?? key] = converted;
}
return result;
}
@@ -8,7 +8,7 @@ import { ValidationError } from '@nestjs/common';
export const validateMetadata = async (
type: QuestionType,
metadata: QuestionMetadata,
metadata: QuestionMetadata | null | undefined,
): Promise<ValidationError[]> => {
if (!metadata) {
return [];
@@ -100,7 +100,12 @@ export class ChoicesCommandProvider {
}
}
Object.assign(choice, updateChoiceDto);
const { question: questionId, ...changes } = updateChoiceDto;
Object.assign(choice, changes);
if (questionId !== undefined) {
choice.questionId = questionId;
choice.question = { id: questionId } as Question;
}
try {
const updatedChoice = await this.choicesRepository.save(choice);
@@ -12,6 +12,7 @@ import { UpdateQuestionDTO } from '../dtos/update-question.dto';
import { validateMetadata } from '../helpers/validate-metadata.helper';
import { AppException } from '@/common/exceptions/app.exception';
import { Test } from '@/modules/tests/entities/test.entity';
import { QuestionType } from '../enums/question-type.enum';
@Injectable()
export class QuestionsCommandProvider {
@@ -39,6 +40,16 @@ export class QuestionsCommandProvider {
) {}
public async createOne(createQuestionDto: CreateQuestionDTO) {
const metadataErrors = await validateMetadata(
createQuestionDto.type ?? QuestionType.SINGLE_CHOICE,
createQuestionDto.metadata ?? null,
);
if (metadataErrors.length)
throw new AppException(
'validation.wrongFieldFormat',
HttpStatus.BAD_REQUEST,
{ field: '$t(questions.fields.metadata)' },
);
const test = await this.testsService.adminGetOne(createQuestionDto.test);
const newQuestion = this.questionsRepository.create({
@@ -84,7 +95,11 @@ export class QuestionsCommandProvider {
}
if (updateQuestionDto.test) {
await this.testsService.adminGetOne(updateQuestionDto.test);
if (updateQuestionDto.test !== question.testId) {
throw new ConflictException(
'جابجایی سؤال به آزمون دیگر مجاز نیست؛ سؤال جدید بسازید.',
);
}
}
const type =
@@ -107,7 +122,9 @@ export class QuestionsCommandProvider {
);
}
Object.assign(question, updateQuestionDto);
const changes = { ...updateQuestionDto };
delete changes.test;
Object.assign(question, changes);
try {
return await this.questionsRepository.save(question);
@@ -57,7 +57,7 @@ export class QuestionRangeRuleCommandProvider {
question: number,
min: number,
max: number,
excludeSelf: boolean = false,
excludeId?: number,
): Promise<void> {
const queryBuilder = this.questionRangeRulesRepository
.createQueryBuilder('rule')
@@ -72,6 +72,9 @@ export class QuestionRangeRuleCommandProvider {
{ min, max },
);
if (excludeId !== undefined)
queryBuilder.andWhere('rule.id != :excludeId', { excludeId });
let overlappingRules: Array<QuestionRangeRule>;
try {
@@ -80,7 +83,7 @@ export class QuestionRangeRuleCommandProvider {
throw new AppTimeoutException(err);
}
if (overlappingRules.length > (excludeSelf ? 1 : 0)) {
if (overlappingRules.length > 0) {
throw new AppException(
'questions.errors.rangeRuleIntersectionConstraint',
HttpStatus.CONFLICT,
@@ -178,9 +181,14 @@ export class QuestionRangeRuleCommandProvider {
);
}
await this.checkRangeOverlap(questionId, min, max, true);
await this.checkRangeOverlap(questionId, min, max, id);
Object.assign(questionRangeRule, updateQuestionRangeRuleDto);
const changes = { ...updateQuestionRangeRuleDto };
delete changes.question;
Object.assign(questionRangeRule, changes, {
question: { id: questionId },
questionId,
});
try {
return await this.questionRangeRulesRepository.save(questionRangeRule);
@@ -50,7 +50,7 @@ export class QuestionTransitionCommandProvider {
type !== QuestionTransitionType.MULTI_CHOICE
? conditionValue
: {
...conditionValue,
...(conditionValue as MultiChoiceCondition),
choiceIds: [
...(conditionValue as MultiChoiceCondition).choiceIds,
].sort((a, b) => a - b),
@@ -88,7 +88,15 @@ export class QuestionTransitionCommandProvider {
transition.fromQuestion = fromQuestion;
transition.toQuestion = toQuestion;
transition.type = type;
transition.condition = conditionValue;
transition.condition =
type === QuestionTransitionType.MULTI_CHOICE
? {
...(conditionValue as MultiChoiceCondition),
choiceIds: [
...(conditionValue as MultiChoiceCondition).choiceIds,
].sort((a, b) => a - b),
}
: conditionValue;
try {
await this.transitionsRepository.save(transition);
@@ -117,7 +117,9 @@ export class QuestionTransitionTypeValidator {
);
}
const choiceId = (conditionValue as SingleChoiceCondition).choiceId;
const choiceId = (
conditionValue as SingleChoiceCondition | null | undefined
)?.choiceId;
if (typeof choiceId !== 'number') {
throw new AppException(
@@ -34,16 +34,19 @@ export class ResultRangeCommandProvider {
test: number,
minScore: number,
maxScore: number,
excludeSelf: boolean = false,
excludeId?: number,
): Promise<void> {
const queryBuilder = this.resultRangeRepository
.createQueryBuilder('resultRange')
.where('resultRange.testId = :test', { test })
.andWhere(
'(resultRange.minScore BETWEEN :minScore AND :maxScore) OR (resultRange.maxScore BETWEEN :minScore AND :maxScore) OR (:minScore BETWEEN resultRange.minScore AND resultRange.maxScore) OR (:maxScore BETWEEN resultRange.minScore AND resultRange.maxScore)',
'(resultRange.minScore <= :maxScore AND resultRange.maxScore >= :minScore)',
{ minScore, maxScore },
);
if (excludeId !== undefined)
queryBuilder.andWhere('resultRange.id != :excludeId', { excludeId });
let overlappingRanges: Array<ResultRange>;
try {
@@ -52,7 +55,7 @@ export class ResultRangeCommandProvider {
throw new AppTimeoutException(err);
}
if (overlappingRanges.length > (excludeSelf ? 1 : 0)) {
if (overlappingRanges.length > 0) {
throw new AppException(
'scoring.errors.resultRangeOverlappingConstraint',
HttpStatus.CONFLICT,
@@ -145,9 +148,11 @@ export class ResultRangeCommandProvider {
);
}
await this.checkRangeOverlap(testId, minScore, maxScore, true);
await this.checkRangeOverlap(testId, minScore, maxScore, id);
Object.assign(resultRange, updateResultRangeDto);
const changes = { ...updateResultRangeDto };
delete changes.test;
Object.assign(resultRange, changes, { test: { id: testId }, testId });
try {
return await this.resultRangeRepository.save(resultRange);
@@ -69,6 +69,11 @@ export class Test extends BaseEntity {
@Column({ type: 'int', nullable: false, default: 0 })
questionsCount!: number;
// Published questionnaires have no versioned snapshots. Keep their structure
// immutable even after unpublishing, including for active guest sessions.
@Column({ type: 'boolean', default: false })
structureLocked!: boolean;
@OneToMany(() => ResultRange, (range) => range.test)
resultRanges!: Array<ResultRange>;
@@ -72,19 +72,21 @@ export class TestsCommandProvider {
}
const accessType = updateTestDto.accessType ?? test.accessType;
const price = updateTestDto.price ?? test.price;
const price =
updateTestDto.price !== undefined ? updateTestDto.price : test.price;
if (
(accessType === AccessType.PAID && !price) ||
(accessType !== AccessType.PAID && price)
(accessType === AccessType.PAID && price == null) ||
(accessType !== AccessType.PAID && price != null)
) {
throw new BadRequestException('tests.errors.priceAccessConstraint');
}
Object.assign(test, updateTestDto);
if (updateTestDto.status === TestStatus.PUBLISHED) {
if (test.status === TestStatus.PUBLISHED) {
await this.publishTestValidatorProvider.validate(test.id);
test.structureLocked = true;
}
try {