diff --git a/backend/package-lock.json b/backend/package-lock.json index 29f0eb2f..18562ca8 100644 --- a/backend/package-lock.json +++ b/backend/package-lock.json @@ -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", diff --git a/backend/package.json b/backend/package.json index 243637ad..97164d63 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index 969fd182..8ce349ab 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -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) diff --git a/backend/src/auth/auth.controller.ts b/backend/src/auth/auth.controller.ts index 7e529b55..fc5323fc 100644 --- a/backend/src/auth/auth.controller.ts +++ b/backend/src/auth/auth.controller.ts @@ -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: 'ورود ادمین به پنل مدیریت' }) diff --git a/backend/src/auth/auth.service.ts b/backend/src/auth/auth.service.ts index 9122066e..d4f45196 100644 --- a/backend/src/auth/auth.service.ts +++ b/backend/src/auth/auth.service.ts @@ -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' }; diff --git a/backend/src/auth/dto/login.dto.ts b/backend/src/auth/dto/login.dto.ts new file mode 100644 index 00000000..8a61407c --- /dev/null +++ b/backend/src/auth/dto/login.dto.ts @@ -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; +} diff --git a/backend/src/auth/dto/register.dto.ts b/backend/src/auth/dto/register.dto.ts new file mode 100644 index 00000000..6a666b79 --- /dev/null +++ b/backend/src/auth/dto/register.dto.ts @@ -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; +} diff --git a/backend/src/pets/dto/create-pet.dto.ts b/backend/src/pets/dto/create-pet.dto.ts index 90de4691..87c03990 100644 --- a/backend/src/pets/dto/create-pet.dto.ts +++ b/backend/src/pets/dto/create-pet.dto.ts @@ -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[]; } diff --git a/backend/src/pets/pets.service.ts b/backend/src/pets/pets.service.ts index 249f05f1..f0d9b323 100644 --- a/backend/src/pets/pets.service.ts +++ b/backend/src/pets/pets.service.ts @@ -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 }, }); } diff --git a/frontend/application/components/AuthModal.tsx b/frontend/application/components/AuthModal.tsx index 10b5df5d..ec20cc42 100644 --- a/frontend/application/components/AuthModal.tsx +++ b/frontend/application/components/AuthModal.tsx @@ -14,8 +14,12 @@ interface AuthModalProps { export default function AuthModal({ isOpen, onClose }: AuthModalProps) { const { setRole, setLoggedIn, fetchProfile } = useUserStore(); - const [view, setView] = useState<"quick" | "phone" | "otp">("quick"); + const [view, setView] = useState<"login" | "register" | "otp-phone" | "otp">("login"); const [phoneNumber, setPhoneNumber] = useState(""); + const [password, setPassword] = useState(""); + const [email, setEmail] = useState(""); + const [firstName, setFirstName] = useState(""); + const [lastName, setLastName] = useState(""); const [otpCode, setOtpCode] = useState(""); const [isLoading, setIsLoading] = useState(false); const [countdown, setCountdown] = useState(0); @@ -33,8 +37,12 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { // Reset modal state on open/close useEffect(() => { if (!isOpen) { - setView("quick"); + setView("login"); setPhoneNumber(""); + setPassword(""); + setEmail(""); + setFirstName(""); + setLastName(""); setOtpCode(""); setIsLoading(false); setCountdown(0); @@ -49,37 +57,41 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { } }, [countdown]); - const handleQuickLogin = async (targetRole: UserRole) => { - if (targetRole === "User_Guest") { - setRole("User_Guest"); - setLoggedIn(false); - toast.success("به عنوان کاربر مهمان وارد شدید."); - onClose(); - return; - } - + const handleLogin = async (e: React.FormEvent) => { + e.preventDefault(); + if (!phoneNumber || !password) return toast.error("شماره موبایل و رمز عبور الزامی است"); + setIsLoading(true); - const testPhone = targetRole === "User_PetOwner" ? "09121111111" : "09122222222"; - try { - // Step 1: Send OTP to test phone - const sendRes = await authService.sendOtp(testPhone); - const code = (sendRes as any).code; - if (!code) { - throw new Error("کد تایید تستی تولید نشد"); - } - - // Step 2: Verify OTP - const verifyRes = await authService.verifyOtp(testPhone, code); - if (verifyRes.success) { - // Force state sync and fetch profile - setRole(targetRole); + const res = await authService.login(phoneNumber, password); + if (res.success) { await fetchProfile(); - toast.success(`ورود سریع موفق! در نقش ${targetRole === "User_Partner" ? 'همکار' : 'صاحب پت'} وارد شدید.`); + toast.success("با موفقیت وارد شدید"); onClose(); } } catch (err: any) { - toast.error(`خطا در ورود سریع: ${err.message}`); + toast.error(err.message || "خطا در ورود"); + } finally { + setIsLoading(false); + } + }; + + const handleRegister = async (e: React.FormEvent) => { + e.preventDefault(); + if (!firstName || !lastName || !phoneNumber || !password) { + return toast.error("لطفاً فیلدهای الزامی را پر کنید"); + } + + setIsLoading(true); + try { + const res = await authService.register({ firstName, lastName, mobile: phoneNumber, email, password }); + if (res.success) { + await fetchProfile(); + toast.success("ثبت‌نام با موفقیت انجام شد"); + onClose(); + } + } catch (err: any) { + toast.error(err.message || "خطا در ثبت‌نام"); } finally { setIsLoading(false); } @@ -197,68 +209,155 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) { {/* Content Panel */} - {view === "quick" && ( - - - -
-

ورود سریع تستی (با دیتابیس واقعی)

-
- - - -
+
+ + setPhoneNumber(e.target.value.replace(/[^0-9]/g, ''))} + disabled={isLoading} + className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-3 px-4 focus:ring-2 focus:ring-canina-blue/20 outline-none font-bold text-left tracking-widest" + />
- +
+ + setPassword(e.target.value)} + disabled={isLoading} + className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-3 px-4 focus:ring-2 focus:ring-canina-blue/20 outline-none text-left" + /> +
+ +
+ + +
+ + + )} - {view === "phone" && ( + {view === "register" && ( +
+
+ + setFirstName(e.target.value)} + disabled={isLoading} + className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2 px-3 focus:ring-2 focus:ring-canina-blue/20 outline-none text-sm" + /> +
+
+ + setLastName(e.target.value)} + disabled={isLoading} + className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2 px-3 focus:ring-2 focus:ring-canina-blue/20 outline-none text-sm" + /> +
+
+ +
+ + setPhoneNumber(e.target.value.replace(/[^0-9]/g, ''))} + disabled={isLoading} + className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2 px-3 focus:ring-2 focus:ring-canina-blue/20 outline-none text-left tracking-widest text-sm" + /> +
+ +
+ + setEmail(e.target.value)} + disabled={isLoading} + className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2 px-3 focus:ring-2 focus:ring-canina-blue/20 outline-none text-left text-sm" + /> +
+ +
+ + setPassword(e.target.value)} + disabled={isLoading} + className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-xl py-2 px-3 focus:ring-2 focus:ring-canina-blue/20 outline-none text-left text-sm" + /> +
+ +
+ +
+ + +
+ )} + + {view === "otp-phone" && ( + شماره موبایل
@@ -322,7 +421,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {