feat: implement backend auth and fix pet profile payload

This commit is contained in:
parsa committed 2026-06-12 22:37:35 +03:30
1 parent 82ab454647
commit 6027e635db
13 files changed
+493 -114

No files matched your search

+16
View File
@@ -2,6 +2,8 @@ import { Controller, Post, Body, HttpCode, HttpStatus } from '@nestjs/common';
import { AuthService } from './auth.service';
import { SendOtpDto } from './dto/send-otp.dto';
import { VerifyOtpDto } from './dto/verify-otp.dto';
import { RegisterDto } from './dto/register.dto';
import { LoginDto } from './dto/login.dto';
import { ApiTags, ApiOperation, ApiResponse, ApiOkResponse, ApiBadRequestResponse } from '@nestjs/swagger';
@ApiTags('Auth - احراز هویت')
@@ -92,6 +94,20 @@ export class AuthController {
return this.authService.verifyOtp(verifyOtpDto);
}
@Post('register')
@HttpCode(HttpStatus.CREATED)
@ApiOperation({ summary: 'ثبت‌نام با ایمیل/موبایل و رمز عبور' })
register(@Body() registerDto: RegisterDto) {
return this.authService.register(registerDto);
}
@Post('login')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'ورود با موبایل و رمز عبور' })
login(@Body() loginDto: LoginDto) {
return this.authService.login(loginDto);
}
@Post('admin-login')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: 'ورود ادمین به پنل مدیریت' })
+69
View File
@@ -4,6 +4,7 @@ import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
import { SendOtpDto } from './dto/send-otp.dto';
import { VerifyOtpDto } from './dto/verify-otp.dto';
import * as bcrypt from 'bcryptjs';
@Injectable()
export class AuthService {
@@ -64,6 +65,74 @@ export class AuthService {
};
}
async register(registerDto: any) {
const { firstName, lastName, email, mobile, password } = registerDto;
const existingUser = await this.prisma.user.findUnique({ where: { mobile } });
if (existingUser) {
throw new BadRequestException({ message: 'کاربری با این شماره موبایل قبلا ثبت نام کرده است', error: 'MOBILE_EXISTS' });
}
if (email) {
const existingEmail = await this.prisma.user.findUnique({ where: { email } });
if (existingEmail) {
throw new BadRequestException({ message: 'کاربری با این ایمیل قبلا ثبت نام کرده است', error: 'EMAIL_EXISTS' });
}
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await this.prisma.user.create({
data: {
firstName,
lastName,
email: email || null,
mobile,
password: hashedPassword,
},
});
const payload = { sub: user.id, phoneNumber: user.mobile };
const accessToken = this.jwtService.sign(payload);
return {
success: true,
data: {
user,
accessToken,
},
};
}
async login(loginDto: any) {
const { mobile, password } = loginDto;
const user = await this.prisma.user.findUnique({ where: { mobile } });
if (!user) {
throw new BadRequestException({ message: 'نام کاربری یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
}
if (!user.password) {
throw new BadRequestException({ message: 'شما با رمز عبور ثبت نام نکرده‌اید. لطفاً با موبایل وارد شوید', error: 'NO_PASSWORD' });
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new BadRequestException({ message: 'نام کاربری یا رمز عبور اشتباه است', error: 'INVALID_CREDENTIALS' });
}
const payload = { sub: user.id, phoneNumber: user.mobile };
const accessToken = this.jwtService.sign(payload);
return {
success: true,
data: {
user,
accessToken,
},
};
}
async adminLogin(body: any) {
if (body.email === 'admin@canina-iran.com' && body.password === 'admin123') {
const payload = { sub: '12345678-1234-1234-1234-123456789012', email: body.email, role: 'Admin' };
+11
View File
@@ -0,0 +1,11 @@
import { IsNotEmpty, IsString, MinLength } from 'class-validator';
export class LoginDto {
@IsNotEmpty({ message: 'شماره موبایل الزامی است' })
@IsString()
mobile: string;
@IsNotEmpty({ message: 'رمز عبور الزامی است' })
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
password: string;
}
+23
View File
@@ -0,0 +1,23 @@
import { IsEmail, IsNotEmpty, IsOptional, IsString, MinLength } from 'class-validator';
export class RegisterDto {
@IsNotEmpty({ message: 'نام الزامی است' })
@IsString()
firstName: string;
@IsNotEmpty({ message: 'نام خانوادگی الزامی است' })
@IsString()
lastName: string;
@IsOptional()
@IsEmail({}, { message: 'ایمیل نامعتبر است' })
email?: string;
@IsNotEmpty({ message: 'شماره موبایل الزامی است' })
@IsString()
mobile: string;
@IsNotEmpty({ message: 'رمز عبور الزامی است' })
@MinLength(6, { message: 'رمز عبور باید حداقل ۶ کاراکتر باشد' })
password: string;
}
+12 -16
View File
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsNotEmpty, IsString, IsOptional, IsNumber, IsBoolean, IsDateString } from 'class-validator';
import { IsNotEmpty, IsString, IsOptional, IsNumber, IsArray } from 'class-validator';
export class CreatePetDto {
@ApiProperty({ description: 'نام حیوان خانگی', example: 'بادی' })
@@ -17,28 +17,24 @@ export class CreatePetDto {
@IsString()
breed?: string;
@ApiPropertyOptional({ description: 'جنسیت', example: 'نر' })
@IsOptional()
@IsString()
gender?: string;
@ApiPropertyOptional({ description: 'وزن (کیلوگرم)', example: 25.5 })
@IsOptional()
@IsNumber()
weight?: number;
@ApiPropertyOptional({ description: 'تاریخ تولد' })
@ApiPropertyOptional({ description: 'سن (سال)', example: 3 })
@IsOptional()
@IsDateString()
birthDate?: string;
@IsNumber()
age?: number;
@ApiPropertyOptional({ description: 'عقیم شده است؟', example: false })
@IsOptional()
@IsBoolean()
isNeutered?: boolean;
@ApiPropertyOptional({ description: 'سوابق پزشکی مختصر' })
@ApiPropertyOptional({ description: 'سطح فعالیت', example: 'متوسط' })
@IsOptional()
@IsString()
medicalHistory?: string;
activityLevel?: string;
@ApiPropertyOptional({ description: 'سوابق پزشکی', type: [String] })
@IsOptional()
@IsArray()
@IsString({ each: true })
medicalConditions?: string[];
}
+24 -7
View File
@@ -8,16 +8,22 @@ export class PetsService {
constructor(private prisma: PrismaService) {}
async create(userId: string, createPetDto: CreatePetDto) {
const { name, type, breed, weight, age, activityLevel, medicalConditions } = createPetDto;
return this.prisma.pet.create({
data: {
name: createPetDto.name,
type: createPetDto.type,
breed: createPetDto.breed || '',
activityLevel: 'متوسط', // Default
age: 1, // Default
weight: createPetDto.weight || 0,
name,
type,
breed: breed || '',
activityLevel: activityLevel || 'متوسط',
age: age || 1,
weight: weight || 0,
userId,
medicalConditions: medicalConditions?.length ? {
create: medicalConditions.map(condition => ({ condition }))
} : undefined,
},
include: { medicalConditions: true, reminders: true, healthLogs: true },
});
}
@@ -31,7 +37,7 @@ export class PetsService {
async findOne(id: string, userId: string) {
const pet = await this.prisma.pet.findFirst({
where: { id, userId },
include: { reminders: true, healthLogs: true },
include: { medicalConditions: true, reminders: true, healthLogs: true },
});
if (!pet) {
throw new NotFoundException('حیوان خانگی یافت نشد');
@@ -41,6 +47,11 @@ export class PetsService {
async update(id: string, userId: string, updatePetDto: UpdatePetDto) {
await this.findOne(id, userId); // Ensure it exists and belongs to user
if (updatePetDto.medicalConditions) {
await this.prisma.petMedicalCondition.deleteMany({ where: { petId: id } });
}
return this.prisma.pet.update({
where: { id },
data: {
@@ -48,7 +59,13 @@ export class PetsService {
type: updatePetDto.type,
breed: updatePetDto.breed,
weight: updatePetDto.weight,
age: updatePetDto.age,
activityLevel: updatePetDto.activityLevel,
medicalConditions: updatePetDto.medicalConditions ? {
create: updatePetDto.medicalConditions.map(condition => ({ condition }))
} : undefined,
},
include: { medicalConditions: true, reminders: true, healthLogs: true },
});
}