fix: harden profile updates and localize public errors in Persian

Preserve actor and user profile fields during partial updates and validate supported personal data.

Add Persian HTTP error handling, validation translations, regression tests, and audit documentation.
This commit is contained in:
SepehrYahyaee
2026-11-04 12:03:04 +03:30
parent 255998097d
commit 2056412efe
16 changed files with 1627 additions and 205 deletions
@@ -0,0 +1,151 @@
import { ActorAuthService } from "./actor.auth.service";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { Types } from "mongoose";
const id = "aaaaaaaaaaaaaaaaaaaaaaaa";
const personalRoles = [
RoleEnum.EXPERT,
RoleEnum.DAMAGE_EXPERT,
RoleEnum.FIELD_EXPERT,
RoleEnum.COMPANY,
RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER,
RoleEnum.CALL_CENTER,
];
function setup(role: RoleEnum, saveDocument = true) {
const document: any = {
_id: new Types.ObjectId(id),
role,
firstName: "نام چند بخشی",
lastName: "نام خانوادگی چند بخشی",
mobile: "09120000000",
phone: "02122222222",
state: "تهران",
city: "تهران",
address: "نشانی قبلی",
email: "account@example.test",
password: "private-password-hash",
otp: "private-otp",
tokens: { token: "private-token" },
ThirdPartyClaimExpertId: "123",
clientKey: new Types.ObjectId("bbbbbbbbbbbbbbbbbbbbbbbb"),
};
if (saveDocument) document.save = jest.fn().mockResolvedValue(document);
const database = {
findOne: jest.fn().mockResolvedValue(document),
updateOne: jest
.fn()
.mockImplementation(async (_filter, update) =>
Object.assign(document, update.$set),
),
};
const client = {
findOne: jest
.fn()
.mockResolvedValue({ clientName: { persian: "بیمه آزمایشی" } }),
};
const service = new ActorAuthService(
{} as any,
{} as any,
database as any,
database as any,
database as any,
database as any,
database as any,
client as any,
{} as any,
{} as any,
database as any,
database as any,
database as any,
database as any,
);
const actor = { sub: id, role, username: "stale-username@example.test" };
return { service, document, database, actor };
}
describe("self profile across actor roles", () => {
it.each(personalRoles)(
"saves supported personal fields for %s and returns only the public profile",
async (role) => {
const { service, document, actor } = setup(role);
const result = await service.modifyProfile(actor, {
firstName: " نام جدید چند بخشی ",
mobile: "۰۹۱۲۳۴۵۶۷۸۹",
state: "البرز",
city: "کرج",
address: "نشانی جدید",
});
expect(document.save).toHaveBeenCalledTimes(1);
expect(document.mobile).toBe("09123456789");
expect(document.lastName).toBe("نام خانوادگی چند بخشی");
expect(result).toMatchObject({
firstName: "نام جدید چند بخشی",
lastName: "نام خانوادگی چند بخشی",
fullName: "نام جدید چند بخشی نام خانوادگی چند بخشی",
mobile: "09123456789",
state: "البرز",
city: "کرج",
insuActivityCo: "بیمه آزمایشی",
});
expect(result.editableFields).toContain("address");
for (const key of [
"password",
"otp",
"tokens",
"clientKey",
"ThirdPartyClaimExpertId",
])
expect(result).not.toHaveProperty(key);
},
);
it("resolves insurers by their subject rather than a stale or non-email username", async () => {
const { service, database, actor } = setup(RoleEnum.COMPANY);
await service.getProfiles(actor);
expect(database.findOne).toHaveBeenCalledWith({
_id: new Types.ObjectId(id),
});
});
it("supports the super-admin's lean record without offering unsupported contact fields", async () => {
const { service, database, actor } = setup(RoleEnum.SUPER_ADMIN, false);
const result = await service.modifyProfile(actor, {
firstName: "نام جدید",
});
expect(database.updateOne).toHaveBeenCalledWith(
{ _id: new Types.ObjectId(id) },
{ $set: { firstName: "نام جدید" } },
);
expect(result.editableFields).toEqual(["firstName", "lastName"]);
await expect(
service.modifyProfile(actor, { mobile: "09123456789" }),
).rejects.toThrow();
});
it.each([
{ role: "super_admin" },
{ clientKey: id },
{ password: "replacement" },
{ ThirdPartyClaimExpertId: "666" },
{ $set: { firstName: "bad" } },
{ city: { $gt: "" } },
{ mobile: "invalid" },
{ address: null },
])("rejects invalid/privileged fields before saving: %j", async (body) => {
const { service, document, actor } = setup(RoleEnum.FILE_MAKER);
await expect(service.modifyProfile(actor, body)).rejects.toThrow();
expect(document.save).not.toHaveBeenCalled();
});
it("does not render undefined names or return data for a missing account", async () => {
const { service, database, document, actor } = setup(RoleEnum.SUPER_ADMIN);
delete document.firstName;
delete document.lastName;
expect((await service.getProfiles(actor)).fullName).toBe(document.email);
database.findOne.mockResolvedValue(null);
await expect(service.getProfiles(actor)).rejects.toThrow(
"حساب کاربری یافت نشد",
);
});
});
+71 -104
View File
@@ -3,6 +3,8 @@ import {
ForbiddenException,
Injectable,
InternalServerErrorException,
ConflictException,
HttpException,
NotFoundException,
UnauthorizedException,
} from "@nestjs/common";
@@ -10,7 +12,13 @@ import { JwtService } from "@nestjs/jwt";
import { Types } from "mongoose";
import { readFileSync } from "node:fs";
import { ForgetPasswordVerifyCodeDtoRs } from "src/auth/dto/actor/forget-password.actor.dto";
import { ProfileActor } from "src/auth/dto/actor/profile.actor.dto";
import {
ActorEditUserProfileDto,
ACTOR_PROFILE_EDITABLE_FIELDS,
ProfileActor,
} from "src/auth/dto/actor/profile.actor.dto";
import { plainToInstance } from "class-transformer";
import { validateSync } from "class-validator";
import {
InsurerRegisterDto,
RegisterDto,
@@ -103,7 +111,9 @@ export class ActorAuthService {
else res = await this.registrarDbService.findOne({ email: username });
break;
case RoleEnum.COMPANY:
res = await this.insurerExpertDbService.findOne({ email: username });
res = await this.insurerExpertDbService.findOne(
userId ? { _id: new Types.ObjectId(userId) } : { email: username },
);
break;
case RoleEnum.FILE_MAKER:
if (username == null && userId)
@@ -440,9 +450,10 @@ export class ActorAuthService {
currentUser.role === "company" ? currentUser.username : null,
currentUser.sub,
);
const profile = new ProfileActor(userDetail);
if (!userDetail) throw new NotFoundException("حساب کاربری یافت نشد.");
const profile = new ProfileActor(userDetail, currentUser.role);
if (currentUser.role !== RoleEnum.COMPANY) {
{
const clientId = [userDetail?.clientKey, userDetail?.insuActivityCo]
.map((value) => String(value ?? "").trim())
.find((value) => Types.ObjectId.isValid(value));
@@ -469,69 +480,33 @@ export class ActorAuthService {
throw new BadRequestException("Invalid actor payload");
}
const allowedFieldsByRole: Record<string, string[]> = {
expert: [
"fullName",
"firstName",
"lastName",
"email",
"phone",
"city",
"state",
"bio",
"nationalCode",
"birthDate",
"avatarUrl",
"address",
],
damage_expert: [
"fullName",
"firstName",
"lastName",
"email",
"phone",
"companyName",
"city",
"state",
"bio",
"nationalCode",
"birthDate",
"avatarUrl",
"address",
],
company: [
"firstName",
"lastName",
"phone",
"mobile",
"city",
"state",
"address",
],
field_expert: ["firstName", "lastName", "email", "phone", "mobile"],
registrar: ["email"],
};
const allowedFields = allowedFieldsByRole[role];
if (!allowedFields) {
throw new ForbiddenException("Profile update not allowed for this role");
const allowedFields = ACTOR_PROFILE_EDITABLE_FIELDS[role];
if (!allowedFields)
throw new ForbiddenException("ویرایش اطلاعات برای این نقش مجاز نیست.");
if (
!update ||
typeof update !== "object" ||
Array.isArray(update) ||
Object.keys(update).some((key) => !allowedFields.includes(key))
) {
throw new BadRequestException(
"فقط اطلاعات شخصی مجاز حساب قابل ویرایش است.",
);
}
// Local validation is necessary: this application has no global ValidationPipe.
const dto = plainToInstance(ActorEditUserProfileDto, update);
const sanitized = Object.fromEntries(
Object.entries(update).filter(([key]) => allowedFields.includes(key)),
Object.keys(update).map((key) => [key, dto[key]]),
);
if (Object.keys(sanitized).length === 0) {
throw new BadRequestException("No valid fields to update");
}
if (sanitized.birthDate && typeof sanitized.birthDate === "string") {
const parsed = new Date(sanitized.birthDate);
if (isNaN(parsed.getTime())) {
throw new BadRequestException("birthDate must be a valid date");
}
sanitized.birthDate = parsed;
}
if (!Object.keys(sanitized).length)
throw new BadRequestException("اطلاعاتی برای ویرایش ارسال نشده است.");
if (Object.values(sanitized).some((value) => value == null))
throw new BadRequestException("مقدار اطلاعات حساب معتبر نیست.");
const errors = validateSync(dto);
if (errors.length)
throw new BadRequestException(
errors.flatMap((error) => Object.values(error.constraints ?? {})),
);
// fetch user detail (document or plain object)
const document = await this.dynamicDbController(
@@ -543,51 +518,43 @@ export class ActorAuthService {
if (!document) throw new NotFoundException("Profile not found");
try {
// if it’s a mongoose document (has .save)
if (typeof document.save === "function") {
Object.assign(document, sanitized);
await document.save();
return document;
} else {
const services: Record<string, any> = {
expert: this.expertDbService,
damage_expert: this.damageExpertDbService,
company: this.insurerExpertDbService,
field_expert: this.fieldExpertDbService,
registrar: this.registrarDbService,
file_maker: this.fileMakerDbService,
file_reviewer: this.fileReviewerDbService,
call_center: this.callCenterAgentDbService,
super_admin: this.superAdminDbService,
};
const service = services[role];
const write = service.updateOne ?? service.findOneAndUpdate;
if (typeof write !== "function")
throw new ForbiddenException(
"ویرایش اطلاعات برای این نقش مجاز نیست.",
);
await write.call(
service,
{ _id: new Types.ObjectId(userId) },
{ $set: sanitized },
);
}
// else, update directly via corresponding DB service
switch (role) {
case "expert":
await this.expertDbService.updateOne(
{ _id: new Types.ObjectId(userId) },
{ $set: sanitized },
);
break;
case "damage_expert":
await this.damageExpertDbService.updateOne(
{ _id: new Types.ObjectId(userId) },
{ $set: sanitized },
);
break;
case "company":
await this.insurerExpertDbService.updateOne(
{ _id: new Types.ObjectId(userId) },
{ $set: sanitized },
);
break;
case "field_expert":
await this.fieldExpertDbService.updateOne(
{ _id: new Types.ObjectId(userId) },
{ $set: sanitized },
);
break;
default:
throw new ForbiddenException("Unsupported role for update");
}
// return the fresh document
return await this.dynamicDbController(role, null, userId);
return await this.getProfiles(currentUser);
} catch (err) {
throw new InternalServerErrorException("Failed to update profile");
if (err instanceof HttpException) throw err;
if (err?.code === 11000)
throw new ConflictException(
"این مشخصات قبلاً برای حساب دیگری ثبت شده است.",
);
throw new InternalServerErrorException(
"ذخیره اطلاعات حساب انجام نشد؛ دوباره تلاش کنید.",
);
}
}
+123 -70
View File
@@ -1,96 +1,149 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsMobilePhone, IsString, Length } from "class-validator";
import { DamageExpertModel } from "src/users/entities/schema/damage-expert.schema";
import { ApiPropertyOptional } from "@nestjs/swagger";
import { Transform } from "class-transformer";
import {
IsEmail,
IsOptional,
IsString,
Matches,
MaxLength,
MinLength,
} from "class-validator";
import { normalizeIranMobile } from "src/helpers/iran-mobile";
export const ACTOR_PERSONAL_PROFILE_FIELDS = [
"firstName",
"lastName",
"mobile",
"phone",
"city",
"state",
"address",
] as const;
export const ACTOR_PROFILE_EDITABLE_FIELDS: Record<string, readonly string[]> =
{
expert: ACTOR_PERSONAL_PROFILE_FIELDS,
damage_expert: ACTOR_PERSONAL_PROFILE_FIELDS,
company: ACTOR_PERSONAL_PROFILE_FIELDS,
field_expert: ACTOR_PERSONAL_PROFILE_FIELDS,
file_maker: ACTOR_PERSONAL_PROFILE_FIELDS,
file_reviewer: ACTOR_PERSONAL_PROFILE_FIELDS,
call_center: ACTOR_PERSONAL_PROFILE_FIELDS,
super_admin: ["firstName", "lastName"],
registrar: ["email"],
};
export const profileDigits = (value: string): string =>
value
.replace(/[۰-۹]/g, (digit) => String(digit.charCodeAt(0) - 1776))
.replace(/[٠-٩]/g, (digit) => String(digit.charCodeAt(0) - 1632));
const trim = ({ value }: { value: unknown }) =>
typeof value === "string" ? value.trim() : value;
/** Public self-profile only. Never serialize the underlying authentication document. */
export class ProfileActor {
public email: string;
public fullName: string;
public nationalCode: string;
public insuActivityCo: string;
public userType: string;
public mobile: string;
public address: string;
public state: string;
public city: string;
public phone?: string;
email?: string;
firstName?: string;
lastName?: string;
fullName: string;
nationalCode?: string;
insuActivityCo?: string;
userType?: string;
mobile?: string;
address?: string;
state?: string;
city?: string;
phone?: string;
editableFields: readonly string[];
constructor(Profile: DamageExpertModel) {
this.email = Profile?.email;
this.fullName = `${Profile?.firstName} ${Profile?.lastName}`;
this.nationalCode = Profile?.nationalCode;
this.insuActivityCo = Profile?.insuActivityCo;
this.userType = Profile?.userType;
this.mobile = Profile?.mobile;
this.address = Profile?.address;
this.state = Profile?.state;
this.city = Profile?.city;
this.phone = Profile?.phone;
constructor(profile: any, role?: string) {
this.email = profile?.email;
this.firstName = profile?.firstName;
this.lastName = profile?.lastName;
this.fullName =
[profile?.firstName, profile?.lastName].filter(Boolean).join(" ") ||
profile?.fullName ||
profile?.email ||
"";
this.nationalCode = profile?.nationalCode;
this.insuActivityCo = profile?.insuActivityCo;
this.userType = profile?.userType || profile?.role;
this.mobile = profile?.mobile;
this.address = profile?.address;
this.state = profile?.state;
this.city = profile?.city;
this.phone = profile?.phone;
this.editableFields =
ACTOR_PROFILE_EDITABLE_FIELDS[role || profile?.role] ?? [];
}
}
export class ActorEditUserProfileDto {
@ApiProperty({
type: "string",
description: "First name of the actor",
example: "heshmat",
nullable: true,
})
@IsString()
@Length(2, 40)
@ApiPropertyOptional()
@IsOptional()
@Transform(trim)
@IsString({ message: "نام باید متن باشد." })
@MinLength(1, { message: "نام را وارد کنید." })
@MaxLength(80, { message: "نام باید حداکثر ۸۰ کاراکتر باشد." })
firstName?: string;
@ApiProperty({
type: "string",
description: "Last name of the actor",
example: "Heshmati",
nullable: true,
})
@IsString()
@Length(1, 10)
@ApiPropertyOptional()
@IsOptional()
@Transform(trim)
@IsString({ message: "نام خانوادگی باید متن باشد." })
@MinLength(1, { message: "نام خانوادگی را وارد کنید." })
@MaxLength(80, { message: "نام خانوادگی باید حداکثر ۸۰ کاراکتر باشد." })
lastName?: string;
@ApiProperty({
type: "string",
description: "Mobile phone of the actor",
example: "09123456789",
nullable: true,
@ApiPropertyOptional()
@IsOptional()
@Transform(({ value }) =>
typeof value === "string" && /^[\d\s+()-]*$/.test(profileDigits(value))
? (normalizeIranMobile(profileDigits(value)) ?? "")
: value,
)
@IsString()
@Matches(/^$|^09\d{9}$/, {
message: "شماره همراه معتبر نیست؛ مانند 09123456789 وارد کنید.",
})
@IsMobilePhone("fa-IR")
mobile?: string;
@ApiProperty({
type: "string",
description: "تلفن خط ثابت",
example: "02122222222",
nullable: true,
})
@ApiPropertyOptional()
@IsOptional()
@Transform(({ value }) =>
typeof value === "string"
? profileDigits(value).replace(/[\s()-]/g, "")
: value,
)
@IsString()
@Matches(/^$|^\+?\d{7,15}$/, { message: "شماره تلفن ثابت معتبر نیست." })
phone?: string;
@ApiProperty({
type: "string",
description: "City of the user",
example: "استان",
nullable: true,
})
@ApiPropertyOptional()
@IsOptional()
@Transform(trim)
@IsString()
@MaxLength(100)
city?: string;
@ApiProperty({
type: "string",
description: "State of the user",
example: "شهر",
nullable: true,
})
@ApiPropertyOptional()
@IsOptional()
@Transform(trim)
@IsString()
@MaxLength(100)
state?: string;
@ApiProperty({
type: "string",
description: "Address of the user",
example: "آدرس",
nullable: true,
})
@ApiPropertyOptional()
@IsOptional()
@Transform(trim)
@IsString()
@MaxLength(1000, { message: "نشانی باید حداکثر ۱۰۰۰ کاراکتر باشد." })
address?: string;
@ApiPropertyOptional({
description: "Editable only for legacy registrar accounts",
})
@IsOptional()
@Transform(trim)
@IsEmail({}, { message: "ایمیل معتبر نیست." })
email?: string;
}