fix(auth): normalize mobile digits and whitespace in login, register, and admin user creation
Deploy Canina / deploy (push) Successful in 1m43s

This commit is contained in:
parsa aghaei committed 2026-08-16 15:31:28 +03:30
1 parent 2984b9f637
commit e1f471c978
3 files changed
+69 -21

No files matched your search

+21 -16
View File
@@ -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({
+12 -5
View File
@@ -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) {
+36
View File
@@ -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;
}