forked from Yara724/api
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:
@@ -14,6 +14,8 @@ export class ProfileUserRs {
|
||||
birthDay: string;
|
||||
gender?: "male" | "female";
|
||||
city: string;
|
||||
state: string;
|
||||
address: string;
|
||||
constructor(profile: UserModel) {
|
||||
this.userId = profile["_id"];
|
||||
this.fullName = profile.fullName;
|
||||
@@ -22,5 +24,7 @@ export class ProfileUserRs {
|
||||
this.birthDay = profile.birthDay;
|
||||
this.gender = profile.gender;
|
||||
this.city = profile.city;
|
||||
this.state = profile.state;
|
||||
this.address = profile.address;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,42 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsDateString } from "class-validator";
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import {
|
||||
IsDateString,
|
||||
IsIn,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
} from "class-validator";
|
||||
|
||||
export class UpdateUserProfileDtoRq {
|
||||
// @ApiProperty({})
|
||||
// mobile: string;
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "Birth date of the user",
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Gregorian birth date (YYYY-MM-DD). Legacy packed Jalali dates are also accepted.",
|
||||
example: "1999-03-05",
|
||||
nullable: true,
|
||||
})
|
||||
@IsDateString()
|
||||
birthDay: string;
|
||||
@IsOptional()
|
||||
@IsDateString({ strict: true }, { message: "تاریخ تولد معتبر نیست." })
|
||||
birthDay?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@ApiPropertyOptional({ enum: ["male", "female"] })
|
||||
@IsOptional()
|
||||
@IsIn(["male", "female"], { message: "جنسیت معتبر نیست." })
|
||||
gender?: "male" | "female";
|
||||
|
||||
@ApiProperty()
|
||||
city: string;
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
city?: string;
|
||||
|
||||
@ApiProperty()
|
||||
state: string;
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
state?: string;
|
||||
|
||||
@ApiProperty()
|
||||
address: string;
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(1000, { message: "نشانی باید حداکثر ۱۰۰۰ کاراکتر باشد." })
|
||||
address?: string;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ export class ProfileController {
|
||||
@Get()
|
||||
@UseGuards(GlobalGuard)
|
||||
async getProfile(@CurrentUser() user) {
|
||||
return await this.profileService.getProfileDetail(user.username);
|
||||
return await this.profileService.getProfileDetail(user.username, user.sub);
|
||||
}
|
||||
|
||||
@Patch()
|
||||
@@ -26,6 +26,10 @@ export class ProfileController {
|
||||
@CurrentUser() user,
|
||||
@Body() body: UpdateUserProfileDtoRq,
|
||||
) {
|
||||
return await this.profileService.updateProfile(user.username, body);
|
||||
return await this.profileService.updateProfile(
|
||||
user.username,
|
||||
body as Record<string, unknown>,
|
||||
user.sub,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,11 +60,89 @@ describe("ProfileService", () => {
|
||||
state: "Tehran",
|
||||
address: "Test address",
|
||||
};
|
||||
users.findOne.mockResolvedValue({ _id: "user-id", ...update, plates: [] });
|
||||
const profile = await service.updateProfile("09120000000", update);
|
||||
expect(users.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ username: "09120000000" },
|
||||
{ $set: update },
|
||||
);
|
||||
expect(profile).not.toHaveProperty("plates");
|
||||
expect(profile).toMatchObject({
|
||||
city: "Tehran",
|
||||
state: "Tehran",
|
||||
address: "Test address",
|
||||
birthDay: "1999-03-05",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns saved province/address and reports deleted accounts without crashing", async () => {
|
||||
users.findOne
|
||||
.mockResolvedValueOnce({
|
||||
_id: "user-id",
|
||||
state: "تهران",
|
||||
city: "تهران",
|
||||
address: "نشانی",
|
||||
})
|
||||
.mockResolvedValueOnce(null);
|
||||
expect(await service.getProfileDetail("09120000000")).toMatchObject({
|
||||
state: "تهران",
|
||||
address: "نشانی",
|
||||
});
|
||||
await expect(service.getProfileDetail("09120000000")).rejects.toThrow(
|
||||
"حساب کاربری یافت نشد",
|
||||
);
|
||||
});
|
||||
|
||||
it("supports partial updates and identifies the current user by their JWT subject", async () => {
|
||||
users.findOneAndUpdate.mockResolvedValue({
|
||||
_id: "user-id",
|
||||
address: "old address",
|
||||
});
|
||||
users.findOne.mockResolvedValue({
|
||||
_id: "user-id",
|
||||
address: "نشانی جدید",
|
||||
state: "تهران",
|
||||
});
|
||||
expect(
|
||||
await service.updateProfile(
|
||||
"old-phone",
|
||||
{ address: "نشانی جدید" },
|
||||
"user-id",
|
||||
),
|
||||
).toMatchObject({ address: "نشانی جدید", state: "تهران" });
|
||||
expect(users.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: "user-id" },
|
||||
{ $set: { address: "نشانی جدید" } },
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts legacy Persian birth dates/gender and stores canonical ISO/enum values", async () => {
|
||||
users.findOneAndUpdate.mockResolvedValue({ _id: "user-id" });
|
||||
users.findOne.mockResolvedValue({
|
||||
_id: "user-id",
|
||||
birthDay: "1998-09-15",
|
||||
gender: "male",
|
||||
});
|
||||
await service.updateProfile("09120000000", {
|
||||
birthDay: 13770624,
|
||||
gender: "مرد",
|
||||
});
|
||||
expect(users.findOneAndUpdate).toHaveBeenCalledWith(expect.anything(), {
|
||||
$set: { birthDay: "1998-09-15", gender: "male" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ birthDay: "1999-02-30" },
|
||||
{ birthDay: 13771301 },
|
||||
{ birthDay: "2999-01-01" },
|
||||
{ gender: "unknown" },
|
||||
{ address: { $gt: "" } },
|
||||
{ city: null },
|
||||
])("rejects invalid personal data before writing: %j", async (update) => {
|
||||
await expect(
|
||||
service.updateProfile("09120000000", update),
|
||||
).rejects.toThrow();
|
||||
expect(users.findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,25 +1,87 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { validateSync } from "class-validator";
|
||||
import { UserDbService } from "src/users/entities/db-service/user.db.service";
|
||||
import { ProfileUserRs } from "./dto/user/profile.dto";
|
||||
import { UpdateUserProfileDtoRq } from "./dto/user/update-profile.dto";
|
||||
import { jalaliToGregorianDate, toJalaliDate } from "src/helpers/date-jalali";
|
||||
import { profileDigits } from "src/auth/dto/actor/profile.actor.dto";
|
||||
|
||||
@Injectable()
|
||||
export class ProfileService {
|
||||
constructor(private readonly userDbService: UserDbService) {}
|
||||
|
||||
async getProfileDetail(username: string) {
|
||||
const userDetail = await this.userDbService.findOne({ username });
|
||||
async getProfileDetail(username: string, userId?: string) {
|
||||
const userDetail = await this.userDbService.findOne(
|
||||
userId ? { _id: userId } : { username },
|
||||
);
|
||||
if (!userDetail) throw new NotFoundException("حساب کاربری یافت نشد.");
|
||||
return new ProfileUserRs(userDetail);
|
||||
}
|
||||
|
||||
async updateProfile(username: string, update) {
|
||||
async updateProfile(
|
||||
username: string,
|
||||
update: Record<string, unknown>,
|
||||
userId?: string,
|
||||
) {
|
||||
const allowedFields = ["birthDay", "gender", "city", "state", "address"];
|
||||
if (Object.keys(update).some((field) => !allowedFields.includes(field))) {
|
||||
throw new BadRequestException("Only personal profile fields can be updated");
|
||||
if (
|
||||
!update ||
|
||||
typeof update !== "object" ||
|
||||
Array.isArray(update) ||
|
||||
Object.keys(update).some((field) => !allowedFields.includes(field))
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
"Only personal profile fields can be updated",
|
||||
);
|
||||
}
|
||||
const userDetail = await this.userDbService.findOneAndUpdate(
|
||||
{ username },
|
||||
{ $set: update },
|
||||
const values: Record<string, unknown> = Object.fromEntries(
|
||||
Object.entries(update).map(([key, value]) => [
|
||||
key,
|
||||
typeof value === "string" ? value.trim() : value,
|
||||
]),
|
||||
);
|
||||
return new ProfileUserRs(userDetail);
|
||||
if (
|
||||
!Object.keys(values).length ||
|
||||
Object.values(values).some((value) => value == null)
|
||||
)
|
||||
throw new BadRequestException("اطلاعات حساب معتبر نیست.");
|
||||
if (values.birthDay !== undefined) {
|
||||
const raw = profileDigits(String(values.birthDay));
|
||||
if (!/^(?:\d{8}|\d{4}[-/]\d{1,2}[-/]\d{1,2})$/.test(raw))
|
||||
throw new BadRequestException("تاریخ تولد معتبر نیست.");
|
||||
const date = jalaliToGregorianDate(raw);
|
||||
const packed = raw.replace(/[/-]/g, "");
|
||||
const isJalali = /^1[2345]\d{6}$/.test(packed);
|
||||
if (
|
||||
!date ||
|
||||
(isJalali &&
|
||||
toJalaliDate(new Date(`${date}T12:00:00Z`)).replace(/\//g, "") !==
|
||||
packed)
|
||||
)
|
||||
throw new BadRequestException("تاریخ تولد معتبر نیست.");
|
||||
values.birthDay = date;
|
||||
if (date > new Date().toISOString().slice(0, 10))
|
||||
throw new BadRequestException("تاریخ تولد نمیتواند در آینده باشد.");
|
||||
}
|
||||
if (values.gender === "مرد") values.gender = "male";
|
||||
if (values.gender === "زن") values.gender = "female";
|
||||
const dto = plainToInstance(UpdateUserProfileDtoRq, values);
|
||||
const errors = validateSync(dto);
|
||||
if (errors.length)
|
||||
throw new BadRequestException(
|
||||
errors.flatMap((error) => Object.values(error.constraints ?? {})),
|
||||
);
|
||||
const filter = userId ? { _id: userId } : { username };
|
||||
const existing = await this.userDbService.findOneAndUpdate(filter, {
|
||||
$set: values,
|
||||
});
|
||||
if (!existing) throw new NotFoundException("حساب کاربری یافت نشد.");
|
||||
// The shared DB helper returns the pre-update document. Read the saved values.
|
||||
return this.getProfileDetail(username, userId);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user