feat: add admin panel dto & validation
This commit is contained in:
@@ -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)),
|
||||
];
|
||||
}
|
||||
Reference in New Issue
Block a user