feat(admin): implement authenticated Stage author restoration API
Deploy Canina / deploy (push) Failing after 2m1s

This commit is contained in:
Canina Automation committed 2026-10-28 14:55:19 +00:00
1 parent bee9c4d6e1
commit 6ed0e73311
9 files changed
+477

No files matched your search

@@ -0,0 +1,43 @@
import { Test, TestingModule } from "@nestjs/testing";
import { AdminController } from "./admin.controller";
import { AdminService } from "./admin.service";
import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
describe("AdminController - Stage Author Restoration endpoint", () => {
let controller: AdminController;
let mockStageAuthorRestorationService: any;
beforeEach(async () => {
mockStageAuthorRestorationService = {
restoreStageAuthors: jest.fn().mockResolvedValue({
success: true,
totalConfigured: 5,
restoredCount: 5,
existingCount: 0,
authors: [],
}),
};
const module: TestingModule = await Test.createTestingModule({
controllers: [AdminController],
providers: [
{ provide: AdminService, useValue: {} },
{ provide: SettingsService, useValue: {} },
{
provide: StageAuthorRestorationService,
useValue: mockStageAuthorRestorationService,
},
],
}).compile();
controller = module.get<AdminController>(AdminController);
});
it("delegates restoreStageAuthors to StageAuthorRestorationService", async () => {
const result = await controller.restoreStageAuthors();
expect(mockStageAuthorRestorationService.restoreStageAuthors).toHaveBeenCalledTimes(1);
expect(result.success).toBe(true);
expect(result.restoredCount).toBe(5);
});
});
@@ -2,6 +2,7 @@ import { Test, TestingModule } from "@nestjs/testing";
import { AdminController } from "./admin.controller";
import { AdminService } from "./admin.service";
import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
describe("AdminController", () => {
let controller: AdminController;
@@ -12,6 +13,7 @@ describe("AdminController", () => {
providers: [
{ provide: AdminService, useValue: {} },
{ provide: SettingsService, useValue: {} },
{ provide: StageAuthorRestorationService, useValue: {} },
],
}).compile();
+14
View File
@@ -30,6 +30,7 @@ import {
import { CreateUserDto, UpdateUserDto } from "./dto/user.dto";
import type { UserAdminActor } from "./user-role-policy";
import { SettingsService } from "../settings/settings.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
import { RolesGuard } from "../common/guards/roles.guard";
import { Roles } from "../common/decorators/roles.decorator";
@@ -43,6 +44,7 @@ export class AdminController {
constructor(
private readonly adminService: AdminService,
private readonly settingsService: SettingsService,
private readonly stageAuthorRestorationService?: StageAuthorRestorationService,
) {}
@Get("dashboard/stats")
@@ -73,6 +75,18 @@ export class AdminController {
};
}
@Post("users/stage-author-restoration")
@ApiOperation({
summary:
"بازیابی شناسه و مشخصات عمومی پنج نویسنده اورجینال مقالات در محیط استیج",
})
async restoreStageAuthors() {
if (!this.stageAuthorRestorationService) {
throw new Error("StageAuthorRestorationService not initialized");
}
return this.stageAuthorRestorationService.restoreStageAuthors();
}
@Get("users/:id")
@ApiOperation({ summary: "جزئیات کاربر" })
async getUserDetails(@Param("id") id: string) {
+2
View File
@@ -28,6 +28,7 @@ import { RedisModule } from "../redis/redis.module";
import { SettingsModule } from "../settings/settings.module";
import { SupportChatAnalyticsController } from "./support-chat-analytics.controller";
import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
import { StageAuthorRestorationService } from "./stage-author-restoration.service";
@Module({
imports: [PrismaModule, RedisModule, SettingsModule],
@@ -60,6 +61,7 @@ import { SupportChatAnalyticsService } from "./support-chat-analytics.service";
SslService,
ApiKeysService,
SupportChatAnalyticsService,
StageAuthorRestorationService,
],
exports: [ApiKeysService, MediaService],
})
@@ -0,0 +1,168 @@
import {
ConflictException,
ForbiddenException,
} from "@nestjs/common";
import {
StageAuthorRestorationService,
GENUINE_STAGE_AUTHORS,
STAGE_AUTHOR_ROLE,
assertStageScope,
} from "./stage-author-restoration.service";
import { Prisma } from "@prisma/client";
describe("StageAuthorRestorationService (Unit & TDD)", () => {
let service: StageAuthorRestorationService;
let mockPrisma: any;
let mockTx: any;
beforeEach(() => {
mockTx = {
user: {
findUnique: jest.fn(),
create: jest.fn(),
},
};
mockPrisma = {
$transaction: jest.fn(async (cb) => cb(mockTx)),
};
service = new StageAuthorRestorationService(mockPrisma as any);
});
describe("assertStageScope environment gating", () => {
it("denies execution in default production environment", () => {
expect(() =>
assertStageScope({ NODE_ENV: "production", APP_ENV: "production" }),
).toThrow(ForbiddenException);
});
it("denies execution when neither APP_ENV nor STAGE flag is set", () => {
expect(() => assertStageScope({})).toThrow(ForbiddenException);
});
it("allows execution when APP_ENV is stage", () => {
expect(() => assertStageScope({ APP_ENV: "stage" })).not.toThrow();
});
it("allows execution when STAGE_AUTHOR_RESTORATION_ENABLED is true", () => {
expect(() =>
assertStageScope({ STAGE_AUTHOR_RESTORATION_ENABLED: "true" }),
).not.toThrow();
});
it("allows execution when DATABASE_URL points to caninodb_stage", () => {
expect(() =>
assertStageScope({
DATABASE_URL: "postgresql://user:pass@db:5432/caninodb_stage",
}),
).not.toThrow();
});
});
describe("restoreStageAuthors TDD lifecycle", () => {
const stageEnv = { APP_ENV: "stage" };
it("restores all 5 genuine authors when none exist in Stage", async () => {
mockTx.user.findUnique.mockResolvedValue(null);
mockTx.user.create.mockImplementation(async ({ data }: any) => ({
id: data.id,
firstName: data.firstName,
lastName: data.lastName,
role: data.role,
}));
const res = await service.restoreStageAuthors(stageEnv);
expect(res.success).toBe(true);
expect(res.totalConfigured).toBe(5);
expect(res.restoredCount).toBe(5);
expect(res.existingCount).toBe(0);
expect(mockTx.user.create).toHaveBeenCalledTimes(5);
// Verify safe non-login fields: no credentials, no contact, no elevated role
for (const call of mockTx.user.create.mock.calls) {
const payload = call[0].data;
expect(payload.role).toBe(STAGE_AUTHOR_ROLE);
expect(payload.mobile).toBeNull();
expect(payload.email).toBeNull();
expect(payload.password).toBeNull();
expect(payload.walletBalance).toEqual(new Prisma.Decimal(0));
// Verify genuine author ID is preserved
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === payload.id);
expect(match).toBeDefined();
expect(payload.firstName).toBe(match!.firstName);
expect(payload.lastName).toBe(match!.lastName);
}
});
it("is strictly idempotent: repeated calls report existing and perform no creates", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
const match = GENUINE_STAGE_AUTHORS.find((a) => a.id === where.id);
if (!match) return null;
return {
id: match.id,
firstName: match.firstName,
lastName: match.lastName,
role: STAGE_AUTHOR_ROLE,
mobile: null,
email: null,
};
});
const res = await service.restoreStageAuthors(stageEnv);
expect(res.success).toBe(true);
expect(res.totalConfigured).toBe(5);
expect(res.restoredCount).toBe(0);
expect(res.existingCount).toBe(5);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("fails closed with 409 Conflict when existing record has conflicting name", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
if (where.id === GENUINE_STAGE_AUTHORS[0].id) {
return {
id: where.id,
firstName: "Fake",
lastName: "Impersonator",
role: "Admin",
};
}
return null;
});
await expect(service.restoreStageAuthors(stageEnv)).rejects.toThrow(
ConflictException,
);
expect(mockTx.user.create).not.toHaveBeenCalled();
});
it("handles partial restoration: restores only missing authors and retains existing identical ones", async () => {
mockTx.user.findUnique.mockImplementation(async ({ where }: any) => {
if (where.id === GENUINE_STAGE_AUTHORS[0].id) {
return {
id: where.id,
firstName: GENUINE_STAGE_AUTHORS[0].firstName,
lastName: GENUINE_STAGE_AUTHORS[0].lastName,
role: STAGE_AUTHOR_ROLE,
};
}
return null;
});
mockTx.user.create.mockImplementation(async ({ data }: any) => ({
id: data.id,
firstName: data.firstName,
lastName: data.lastName,
role: data.role,
}));
const res = await service.restoreStageAuthors(stageEnv);
expect(res.success).toBe(true);
expect(res.totalConfigured).toBe(5);
expect(res.restoredCount).toBe(4);
expect(res.existingCount).toBe(1);
expect(mockTx.user.create).toHaveBeenCalledTimes(4);
});
});
});
@@ -0,0 +1,160 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
HttpStatus,
Injectable,
} from "@nestjs/common";
import { PrismaService } from "../prisma/prisma.service";
import { Prisma } from "@prisma/client";
export const GENUINE_STAGE_AUTHORS = [
{
id: "14490d36-52fc-40be-8637-b7b04b8302f8",
firstName: "کارشناس",
lastName: "تغذیه تیم کنینا",
},
{
id: "4e0d830c-0125-4f08-8cb7-c5ae0a38cee7",
firstName: "آرزو",
lastName: "فراشیانی",
},
{
id: "63d38117-f864-4af6-afa0-ae5b05255f57",
firstName: "کارشناس",
lastName: "تحقیقات و کنترل کیفیت کنینا",
},
{
id: "7b1e51d1-8c32-4a3c-804f-948d706aef36",
firstName: "کارشناس",
lastName: "رفتار و نگهداری تیم کنینا",
},
{
id: "f57e0f98-efee-4fa1-90ef-67bf84cafad4",
firstName: "دکتر",
lastName: "دامپزشک تیم کنینا",
},
] as const;
export const STAGE_AUTHOR_ROLE = "User_Vet";
export function assertStageScope(env: NodeJS.ProcessEnv = process.env): void {
const isStageEnv =
env.APP_ENV === "stage" ||
env.STAGE_AUTHOR_RESTORATION_ENABLED === "true" ||
(env.DATABASE_URL && env.DATABASE_URL.includes("caninodb_stage"));
const isProduction =
env.NODE_ENV === "production" &&
env.APP_ENV !== "stage" &&
env.STAGE_AUTHOR_RESTORATION_ENABLED !== "true";
if (!isStageEnv || isProduction) {
throw new ForbiddenException(
"Stage author restoration is strictly restricted to authorized Stage environments",
);
}
}
export interface StageAuthorRestoreResult {
success: boolean;
totalConfigured: number;
restoredCount: number;
existingCount: number;
authors: Array<{
id: string;
firstName: string;
lastName: string;
role: string;
status: "restored" | "already_present";
}>;
}
@Injectable()
export class StageAuthorRestorationService {
constructor(private readonly prisma: PrismaService) {}
async restoreStageAuthors(
env: NodeJS.ProcessEnv = process.env,
): Promise<StageAuthorRestoreResult> {
assertStageScope(env);
return this.prisma.$transaction(async (tx) => {
const results: StageAuthorRestoreResult["authors"] = [];
let restoredCount = 0;
let existingCount = 0;
for (const author of GENUINE_STAGE_AUTHORS) {
const existing = await tx.user.findUnique({
where: { id: author.id },
select: {
id: true,
firstName: true,
lastName: true,
role: true,
mobile: true,
email: true,
},
});
if (existing) {
if (
existing.firstName !== author.firstName ||
existing.lastName !== author.lastName
) {
throw new ConflictException(
`Identity conflict for author UUID ${author.id}: existing name '${existing.firstName} ${existing.lastName}' conflicts with genuine name '${author.firstName} ${author.lastName}'`,
);
}
results.push({
id: existing.id,
firstName: existing.firstName,
lastName: existing.lastName,
role: existing.role,
status: "already_present",
});
existingCount++;
} else {
// Create author with safe non-login profile fields only
// No synthetic mobile, no synthetic email, no password, no admin privileges
const created = await tx.user.create({
data: {
id: author.id,
firstName: author.firstName,
lastName: author.lastName,
role: STAGE_AUTHOR_ROLE,
mobile: null as any,
email: null,
password: null,
walletBalance: new Prisma.Decimal(0),
},
select: {
id: true,
firstName: true,
lastName: true,
role: true,
},
});
results.push({
id: created.id,
firstName: created.firstName,
lastName: created.lastName,
role: created.role,
status: "restored",
});
restoredCount++;
}
}
return {
success: true,
totalConfigured: GENUINE_STAGE_AUTHORS.length,
restoredCount,
existingCount,
authors: results,
};
});
}
}