From e1f471c978d55545f660a2beefea932d90b98077 Mon Sep 17 00:00:00 2001
From: parsa aghaei
Date: Sun, 16 Aug 2026 15:31:28 +0330
Subject: [PATCH] fix(auth): normalize mobile digits and whitespace in login,
register, and admin user creation
---
backend/src/admin/admin.service.ts | 37 ++++++++++++++-----------
backend/src/auth/auth.service.ts | 17 ++++++++----
backend/src/common/utils/phone.utils.ts | 36 ++++++++++++++++++++++++
3 files changed, 69 insertions(+), 21 deletions(-)
create mode 100644 backend/src/common/utils/phone.utils.ts
diff --git a/backend/src/admin/admin.service.ts b/backend/src/admin/admin.service.ts
index de524293..74f87cd5 100644
--- a/backend/src/admin/admin.service.ts
+++ b/backend/src/admin/admin.service.ts
@@ -9,6 +9,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import * as bcrypt from 'bcryptjs';
import { CreateUserDto, UpdateUserDto } from './dto/user.dto';
+import { normalizeMobile } from '../common/utils/phone.utils';
export class PaginationQuery {
page?: number | string;
@@ -177,8 +178,9 @@ export class AdminService {
}
async createUser(dto: CreateUserDto) {
+ const mobile = normalizeMobile(dto.mobile);
const existingMobile = await this.prisma.user.findUnique({
- where: { mobile: dto.mobile },
+ where: { mobile },
});
if (existingMobile) {
throw new BadRequestException('کاربری با این شماره موبایل قبلاً در سیستم ثبت شده است');
@@ -186,21 +188,22 @@ export class AdminService {
if (dto.email) {
const existingEmail = await this.prisma.user.findUnique({
- where: { email: dto.email },
+ where: { email: dto.email.trim().toLowerCase() },
});
if (existingEmail) {
throw new BadRequestException('کاربری با این آدرس ایمیل قبلاً در سیستم ثبت شده است');
}
}
- const hashedPassword = dto.password ? await bcrypt.hash(dto.password, 10) : '';
+ const passwordToHash = dto.password?.trim();
+ const hashedPassword = passwordToHash ? await bcrypt.hash(passwordToHash, 10) : '';
return this.prisma.user.create({
data: {
- firstName: dto.firstName,
- lastName: dto.lastName,
- mobile: dto.mobile,
- email: dto.email || null,
+ firstName: dto.firstName.trim(),
+ lastName: dto.lastName.trim(),
+ mobile,
+ email: dto.email ? dto.email.trim().toLowerCase() : null,
password: hashedPassword,
role: dto.role || 'User_PetOwner',
walletBalance:
@@ -221,18 +224,20 @@ export class AdminService {
throw new NotFoundException(`کاربری با شناسه ${id} یافت نشد`);
}
- if (dto.mobile && dto.mobile !== user.mobile) {
+ const normalizedMobile = dto.mobile ? normalizeMobile(dto.mobile) : undefined;
+ if (normalizedMobile && normalizedMobile !== user.mobile) {
const existingMobile = await this.prisma.user.findUnique({
- where: { mobile: dto.mobile },
+ where: { mobile: normalizedMobile },
});
if (existingMobile && existingMobile.id !== id) {
throw new BadRequestException('این شماره موبایل متعلق به کاربر دیگری است');
}
}
- if (dto.email && dto.email !== user.email) {
+ const normalizedEmail = dto.email ? dto.email.trim().toLowerCase() : undefined;
+ if (normalizedEmail && normalizedEmail !== user.email) {
const existingEmail = await this.prisma.user.findUnique({
- where: { email: dto.email },
+ where: { email: normalizedEmail },
});
if (existingEmail && existingEmail.id !== id) {
throw new BadRequestException('این آدرس ایمیل متعلق به کاربر دیگری است');
@@ -240,16 +245,16 @@ export class AdminService {
}
const updateData: Prisma.UserUpdateInput = {};
- if (dto.firstName !== undefined) updateData.firstName = dto.firstName;
- if (dto.lastName !== undefined) updateData.lastName = dto.lastName;
- if (dto.mobile !== undefined) updateData.mobile = dto.mobile;
- if (dto.email !== undefined) updateData.email = dto.email || null;
+ if (dto.firstName !== undefined) updateData.firstName = dto.firstName.trim();
+ if (dto.lastName !== undefined) updateData.lastName = dto.lastName.trim();
+ if (normalizedMobile !== undefined) updateData.mobile = normalizedMobile;
+ if (normalizedEmail !== undefined) updateData.email = normalizedEmail || null;
if (dto.role !== undefined) updateData.role = dto.role;
if (dto.walletBalance !== undefined) {
updateData.walletBalance = new Prisma.Decimal(dto.walletBalance);
}
if (dto.password && dto.password.trim().length >= 6) {
- updateData.password = await bcrypt.hash(dto.password, 10);
+ updateData.password = await bcrypt.hash(dto.password.trim(), 10);
}
return this.prisma.user.update({
diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts
index c4378cbe..277f2f2c 100644
--- a/backend/src/auth/auth.service.ts
+++ b/backend/src/auth/auth.service.ts
@@ -7,6 +7,7 @@ import { VerifyOtpDto } from './dto/verify-otp.dto';
import { SmsService } from '../common/services/sms.service';
import * as bcrypt from 'bcryptjs';
import * as crypto from 'crypto';
+import { normalizeMobile } from '../common/utils/phone.utils';
export class RegisterInput {
firstName!: string;
@@ -36,7 +37,7 @@ export class AuthService {
) {}
async sendOtp(sendOtpDto: SendOtpDto) {
- const { phoneNumber } = sendOtpDto;
+ const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber);
const code = crypto.randomInt(10000, 100000).toString();
@@ -62,7 +63,8 @@ export class AuthService {
}
async verifyOtp(verifyOtpDto: VerifyOtpDto) {
- const { phoneNumber, code } = verifyOtpDto;
+ const phoneNumber = normalizeMobile(verifyOtpDto.phoneNumber);
+ const code = String(verifyOtpDto.code).trim();
const savedCode = await this.redisService.get(`otp:${phoneNumber}`);
@@ -102,7 +104,11 @@ export class AuthService {
}
async register(registerDto: RegisterInput) {
- const { firstName, lastName, email, mobile, password } = registerDto;
+ const firstName = registerDto.firstName.trim();
+ const lastName = registerDto.lastName.trim();
+ const mobile = normalizeMobile(registerDto.mobile);
+ const email = registerDto.email ? registerDto.email.trim().toLowerCase() : null;
+ const password = registerDto.password?.trim();
const existingUser = await this.prisma.user.findUnique({
where: { mobile },
@@ -132,7 +138,7 @@ export class AuthService {
data: {
firstName,
lastName,
- email: email || null,
+ email,
mobile,
password: hashedPassword,
},
@@ -151,7 +157,8 @@ export class AuthService {
}
async login(loginDto: LoginInput) {
- const { mobile, password } = loginDto;
+ const mobile = normalizeMobile(loginDto.mobile);
+ const password = loginDto.password ? loginDto.password.trim() : '';
const user = await this.prisma.user.findUnique({ where: { mobile } });
if (!user) {
diff --git a/backend/src/common/utils/phone.utils.ts b/backend/src/common/utils/phone.utils.ts
new file mode 100644
index 00000000..e03c15bd
--- /dev/null
+++ b/backend/src/common/utils/phone.utils.ts
@@ -0,0 +1,36 @@
+/**
+ * Normalizes Iranian phone numbers:
+ * 1. Converts Persian and Arabic digits to English digits
+ * 2. Removes spaces, dashes, parentheses
+ * 3. Converts +98 or 0098 prefixes to 0
+ */
+export function normalizeMobile(mobile: string | undefined | null): string {
+ if (!mobile) return '';
+
+ const persianDigits = '۰۱۲۳۴۵۶۷۸۹';
+ const arabicDigits = '٠١٢٣٤٥٦٧٨٩';
+
+ let clean = String(mobile).trim();
+
+ // Convert Persian & Arabic numbers
+ for (let i = 0; i < 10; i++) {
+ clean = clean.replace(new RegExp(persianDigits[i], 'g'), String(i));
+ clean = clean.replace(new RegExp(arabicDigits[i], 'g'), String(i));
+ }
+
+ // Remove non-digits except +
+ clean = clean.replace(/[^\d+]/g, '');
+
+ // Normalize prefix
+ if (clean.startsWith('+98')) {
+ clean = '0' + clean.slice(3);
+ } else if (clean.startsWith('0098')) {
+ clean = '0' + clean.slice(4);
+ } else if (clean.startsWith('98') && clean.length === 12) {
+ clean = '0' + clean.slice(2);
+ } else if (clean.length === 10 && !clean.startsWith('0')) {
+ clean = '0' + clean;
+ }
+
+ return clean;
+}