feat: implement backend auth and fix pet profile payload
This commit is contained in:
1 parent
82ab454647
commit
6027e635db
13 files changed
+493
-114
No files matched your search
Generated
+18
@@ -18,6 +18,7 @@
|
||||
"@nestjs/throttler": "^6.5.0",
|
||||
"@prisma/client": "^5.22.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"helmet": "^8.2.0",
|
||||
@@ -35,6 +36,7 @@
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@types/bcrypt": "^6.0.0",
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/multer": "^2.1.0",
|
||||
@@ -2833,6 +2835,13 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/bcryptjs": {
|
||||
"version": "2.4.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/bcryptjs/-/bcryptjs-2.4.6.tgz",
|
||||
"integrity": "sha512-9xlo6R2qDs5uixm0bcIqCeMCE6HiQsIyel9KQySStiyqNl2tnj2mP3DX1Nf56MD6KMenNNlBBsy3LJ7gUEQPXQ==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/body-parser": {
|
||||
"version": "1.19.6",
|
||||
"resolved": "https://registry.npmjs.org/@types/body-parser/-/body-parser-1.19.6.tgz",
|
||||
@@ -4351,6 +4360,15 @@
|
||||
"node": ">= 18"
|
||||
}
|
||||
},
|
||||
"node_modules/bcryptjs": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz",
|
||||
"integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==",
|
||||
"license": "BSD-3-Clause",
|
||||
"bin": {
|
||||
"bcrypt": "bin/bcrypt"
|
||||
}
|
||||
},
|
||||
"node_modules/bl": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz",
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"@nestjs/throttler": "^6.5.0",
|
||||
"@prisma/client": "^5.22.0",
|
||||
"bcrypt": "^6.0.0",
|
||||
"bcryptjs": "^3.0.3",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"helmet": "^8.2.0",
|
||||
@@ -46,6 +47,7 @@
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@types/bcrypt": "^6.0.0",
|
||||
"@types/bcryptjs": "^2.4.6",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/multer": "^2.1.0",
|
||||
|
||||
@@ -11,8 +11,9 @@ model User {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
firstName String @map("first_name") @db.VarChar(100)
|
||||
lastName String @map("last_name") @db.VarChar(100)
|
||||
email String @unique @db.VarChar(150)
|
||||
mobile String? @unique @db.VarChar(15)
|
||||
email String? @unique @db.VarChar(150)
|
||||
mobile String @unique @db.VarChar(15)
|
||||
password String? @db.VarChar(255)
|
||||
role String @default("User_PetOwner") @db.VarChar(30)
|
||||
walletBalance Decimal @default(0.00) @map("wallet_balance") @db.Decimal(15, 2)
|
||||
charityDonationTotal Decimal @default(0.00) @map("charity_donation_total") @db.Decimal(15, 2)
|
||||
|
||||
@@ -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: 'ورود ادمین به پنل مدیریت' })
|
||||
|
||||
@@ -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' };
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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[];
|
||||
}
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user