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 },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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 */}
|
||||
<AnimatePresence mode="wait">
|
||||
{view === "quick" && (
|
||||
<motion.div
|
||||
key="quick-view"
|
||||
initial={{ opacity: 0, y: 10 }}
|
||||
animate={{ opacity: 1, y: 0 }}
|
||||
exit={{ opacity: 0, y: -10 }}
|
||||
className="space-y-6"
|
||||
{view === "login" && (
|
||||
<motion.form
|
||||
key="login-view"
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
onSubmit={handleLogin}
|
||||
className="space-y-4"
|
||||
>
|
||||
<button
|
||||
onClick={() => setView("phone")}
|
||||
className="w-full bg-medical-gray-50 border border-medical-gray-200 rounded-2xl p-5 flex items-center justify-between group hover:border-canina-blue transition-all cursor-pointer shadow-sm"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<Phone className="w-5 h-5 text-canina-blue" />
|
||||
<span className="font-black text-sm text-medical-gray-700">ورود با شماره موبایل</span>
|
||||
</div>
|
||||
<div className="w-8 h-8 rounded-xl bg-white border border-medical-gray-100 flex items-center justify-center shadow-sm text-canina-blue group-hover:bg-canina-blue group-hover:text-white transition-all">←</div>
|
||||
</button>
|
||||
|
||||
<div className="pt-6 border-t border-medical-gray-100">
|
||||
<p className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest text-center mb-4">ورود سریع تستی (با دیتابیس واقعی)</p>
|
||||
<div className="grid grid-cols-3 gap-3">
|
||||
<button
|
||||
onClick={() => handleQuickLogin("User_Guest")}
|
||||
disabled={isLoading}
|
||||
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
<User className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
|
||||
<span className="text-[10px] font-black text-medical-gray-700">مهمان</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleQuickLogin("User_PetOwner")}
|
||||
disabled={isLoading}
|
||||
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<RefreshCw className="w-6 h-6 text-canina-blue animate-spin" />
|
||||
) : (
|
||||
<Heart className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
|
||||
)}
|
||||
<span className="text-[10px] font-black text-medical-gray-700">صاحب پت</span>
|
||||
</button>
|
||||
<button
|
||||
onClick={() => handleQuickLogin("User_Partner")}
|
||||
disabled={isLoading}
|
||||
className="flex flex-col items-center gap-2 p-3 rounded-2xl border border-medical-gray-100 hover:bg-medical-gray-50 transition-all group cursor-pointer disabled:opacity-50"
|
||||
>
|
||||
{isLoading ? (
|
||||
<RefreshCw className="w-6 h-6 text-canina-blue animate-spin" />
|
||||
) : (
|
||||
<Building2 className="w-6 h-6 text-medical-gray-400 group-hover:text-canina-blue" />
|
||||
)}
|
||||
<span className="text-[10px] font-black text-medical-gray-700">همکار</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-medical-gray-500">شماره موبایل</label>
|
||||
<input
|
||||
type="tel"
|
||||
maxLength={11}
|
||||
placeholder="مثال: ۰۹۱۲۳۴۵۶۷۸۹"
|
||||
value={phoneNumber}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
</motion.div>
|
||||
<div className="space-y-2">
|
||||
<label className="text-xs font-bold text-medical-gray-500">رمز عبور</label>
|
||||
<input
|
||||
type="password"
|
||||
placeholder="رمز عبور خود را وارد کنید"
|
||||
value={password}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setView("otp-phone")}
|
||||
className="text-xs font-bold text-canina-blue hover:underline"
|
||||
>
|
||||
ورود با کد یکبار مصرف (OTP)
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setView("register")}
|
||||
className="text-xs font-bold text-canina-blue hover:underline"
|
||||
>
|
||||
حساب ندارید؟ ثبتنام
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !phoneNumber || !password}
|
||||
className="w-full py-4 mt-4 bg-canina-blue text-white rounded-xl font-black hover:bg-indigo-700 disabled:opacity-50 transition-all shadow-lg shadow-canina-blue/20 flex items-center justify-center gap-2 cursor-pointer"
|
||||
>
|
||||
{isLoading ? <RefreshCw className="w-5 h-5 animate-spin" /> : <>ورود به حساب</>}
|
||||
</button>
|
||||
</motion.form>
|
||||
)}
|
||||
|
||||
{view === "phone" && (
|
||||
{view === "register" && (
|
||||
<motion.form
|
||||
key="phone-view"
|
||||
key="register-view"
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
onSubmit={handleRegister}
|
||||
className="space-y-3"
|
||||
>
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-bold text-medical-gray-500">نام</label>
|
||||
<input
|
||||
type="text"
|
||||
value={firstName}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-bold text-medical-gray-500">نام خانوادگی</label>
|
||||
<input
|
||||
type="text"
|
||||
value={lastName}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-bold text-medical-gray-500">شماره موبایل *</label>
|
||||
<input
|
||||
type="tel"
|
||||
maxLength={11}
|
||||
value={phoneNumber}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-bold text-medical-gray-500">ایمیل (اختیاری)</label>
|
||||
<input
|
||||
type="email"
|
||||
value={email}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-1">
|
||||
<label className="text-xs font-bold text-medical-gray-500">رمز عبور *</label>
|
||||
<input
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => 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"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-start pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setView("login")}
|
||||
className="text-xs font-bold text-canina-blue hover:underline"
|
||||
>
|
||||
بازگشت به ورود
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={isLoading || !phoneNumber || !password || !firstName || !lastName}
|
||||
className="w-full py-3 mt-2 bg-canina-blue text-white rounded-xl font-black hover:bg-indigo-700 disabled:opacity-50 transition-all flex items-center justify-center gap-2 cursor-pointer"
|
||||
>
|
||||
{isLoading ? <RefreshCw className="w-4 h-4 animate-spin" /> : <>ثبتنام</>}
|
||||
</button>
|
||||
</motion.form>
|
||||
)}
|
||||
|
||||
{view === "otp-phone" && (
|
||||
<motion.form
|
||||
key="otp-phone-view"
|
||||
initial={{ opacity: 0, x: 20 }}
|
||||
animate={{ opacity: 1, x: 0 }}
|
||||
exit={{ opacity: 0, x: -20 }}
|
||||
@@ -270,10 +369,10 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
||||
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest">شماره موبایل</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setView("quick")}
|
||||
onClick={() => setView("login")}
|
||||
className="text-[10px] font-black text-canina-blue hover:underline"
|
||||
>
|
||||
برگشت به ورود سریع
|
||||
برگشت به صفحه ورود
|
||||
</button>
|
||||
</div>
|
||||
<div className="relative">
|
||||
@@ -322,7 +421,7 @@ export default function AuthModal({ isOpen, onClose }: AuthModalProps) {
|
||||
<label className="text-[10px] font-black text-medical-gray-400 uppercase tracking-widest">کد تایید پیامکی</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setView("phone")}
|
||||
onClick={() => setView("otp-phone")}
|
||||
className="text-[10px] font-black text-canina-blue flex items-center gap-1 hover:underline"
|
||||
>
|
||||
<ArrowRight className="w-3 h-3" />
|
||||
|
||||
@@ -65,6 +65,40 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register with email/mobile and password
|
||||
*/
|
||||
public async register(data: any): Promise<AuthResponse> {
|
||||
try {
|
||||
const response = await api.post('/auth/register', data);
|
||||
const { data: resData } = response.data;
|
||||
if (resData?.accessToken) {
|
||||
localStorage.setItem('accessToken', resData.accessToken);
|
||||
}
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
const message = error.response?.data?.message || 'خطا در ثبتنام';
|
||||
throw new Error(Array.isArray(message) ? message[0] : message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Login with mobile and password
|
||||
*/
|
||||
public async login(mobile: string, password: string): Promise<AuthResponse> {
|
||||
try {
|
||||
const response = await api.post('/auth/login', { mobile, password });
|
||||
const { data } = response.data;
|
||||
if (data?.accessToken) {
|
||||
localStorage.setItem('accessToken', data.accessToken);
|
||||
}
|
||||
return response.data;
|
||||
} catch (error: any) {
|
||||
const message = error.response?.data?.message || 'نام کاربری یا رمز عبور اشتباه است';
|
||||
throw new Error(Array.isArray(message) ? message[0] : message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current user profile
|
||||
*/
|
||||
|
||||
@@ -72,7 +72,10 @@ export const usePetStore = create<PetStore>()(
|
||||
name: pet.name,
|
||||
type: pet.type,
|
||||
breed: pet.breed || "",
|
||||
weight: Number(pet.weight) || 0
|
||||
weight: Number(pet.weight) || 0,
|
||||
age: Number(pet.age) || 0,
|
||||
activityLevel: pet.activityLevel || "متوسط",
|
||||
medicalConditions: pet.medicalConditions || []
|
||||
});
|
||||
await useUserStore.getState().fetchProfile();
|
||||
} catch (error) {
|
||||
@@ -131,7 +134,10 @@ export const usePetStore = create<PetStore>()(
|
||||
name: updates.name,
|
||||
type: updates.type,
|
||||
breed: updates.breed,
|
||||
weight: updates.weight ? Number(updates.weight) : undefined
|
||||
weight: updates.weight ? Number(updates.weight) : undefined,
|
||||
age: updates.age ? Number(updates.age) : undefined,
|
||||
activityLevel: updates.activityLevel,
|
||||
medicalConditions: updates.medicalConditions
|
||||
});
|
||||
await useUserStore.getState().fetchProfile();
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
# Application Backend Integration & Refactoring Plan
|
||||
|
||||
This plan details the migration of the CaninaIran frontend application from using mock data to communicating entirely with the backend APIs, adding email/password authentication, and resolving issues with the pet profile forms.
|
||||
|
||||
## User Review Required
|
||||
> [!IMPORTANT]
|
||||
> - **Authentication:** The `User` model in the database currently does not have a password field. A new database migration will be required to add `password` to users.
|
||||
> - **OTP Fallback:** For mobile login, since the SMS panel is not connected yet, we will return the generated OTP in the API response so it can be typed in manually. We will leave a `TODO` for the SMS panel integration.
|
||||
|
||||
## Open Questions
|
||||
> [!WARNING]
|
||||
> - For the new **Email/Password** registration, do we need email verification (e.g., sending a link) or is the account activated immediately upon registration?
|
||||
> - Should we require the user to provide their mobile number even if they register via email?
|
||||
|
||||
## Proposed Changes
|
||||
|
||||
---
|
||||
### 1. Database & Backend Auth [Backend]
|
||||
Adds email/password authentication capabilities and standardizes the auth endpoints.
|
||||
|
||||
#### [MODIFY] [schema.prisma](file:///c:/Users/parsa/Desktop/work/caninairan/backend/prisma/schema.prisma)
|
||||
- Add `password String? @db.VarChar(255)` to the `User` model.
|
||||
- Run `npx prisma migrate dev --name add_user_password`.
|
||||
|
||||
#### [MODIFY] [auth.controller.ts](file:///c:/Users/parsa/Desktop/work/caninairan/backend/src/auth/auth.controller.ts)
|
||||
- Add `@Post('register-email')` endpoint to accept `email`, `password`, `firstName`, and `lastName`.
|
||||
- Add `@Post('login-email')` endpoint to accept `email` and `password`.
|
||||
|
||||
#### [MODIFY] [auth.service.ts](file:///c:/Users/parsa/Desktop/work/caninairan/backend/src/auth/auth.service.ts)
|
||||
- Implement `bcrypt` hashing for `registerEmail` and password verification for `loginEmail`.
|
||||
- Update `sendOtp` to return the generated code in the response body (as a fallback before SMS panel is implemented) and add a `// TODO: Connect to SMS provider` comment.
|
||||
|
||||
---
|
||||
### 2. Frontend Auth (Storefront) [Frontend]
|
||||
Refactors the storefront authentication modal to remove mock tests and integrate real email/password + mobile/OTP login.
|
||||
|
||||
#### [MODIFY] [AuthModal.tsx](file:///c:/Users/parsa/Desktop/work/caninairan/frontend/application/components/AuthModal.tsx)
|
||||
- Remove the "ورود سریع تستی" (mock login) button entirely.
|
||||
- Implement two tabs: "ایمیل و رمز عبور" (Email/Password) and "شماره موبایل" (Mobile OTP).
|
||||
- Wire up the Email tab to `/auth/register-email` and `/auth/login-email`.
|
||||
- Wire up the Mobile tab to `/auth/send-otp` (showing the OTP in a toast or console for now) and `/auth/verify-otp`.
|
||||
- Integrate the returned JWT with the `userStore`.
|
||||
|
||||
---
|
||||
### 3. Pet Profile Update Form [Frontend]
|
||||
Resolves the issue where updating the pet profile in the multi-step form sends an incomplete payload to the backend.
|
||||
|
||||
#### [MODIFY] [PetProfileWizard.tsx](file:///c:/Users/parsa/Desktop/work/caninairan/frontend/application/components/PetProfileWizard.tsx)
|
||||
- Update the `handleComplete` or `onSubmit` function to ensure it merges the state of all wizard steps (Name, Breed, Age, Weight, Activity Level, Medical Conditions).
|
||||
- Ensure the payload strictly matches what the backend `PUT /api/pets/:id` expects.
|
||||
|
||||
#### [MODIFY] [usePetStore.ts](file:///c:/Users/parsa/Desktop/work/caninairan/frontend/application/lib/store/usePetStore.ts)
|
||||
- Verify `updatePet` action properly merges changes and reflects the server response.
|
||||
|
||||
---
|
||||
### 4. Home Page De-mocking [Frontend]
|
||||
Currently, several sections in the Home page (`page.tsx`) rely on mock data or hardcoded content.
|
||||
|
||||
> [!NOTE]
|
||||
> **List of Mocked/Hardcoded Items in Home Page:**
|
||||
> 1. **SmartAdvisor:** Symptoms and rules are hardcoded in the frontend. It doesn't fetch rules from the backend.
|
||||
> 2. **FeaturedProducts:** May need to be verified if it uses real `api.get('/products')` or mock fallback.
|
||||
> 3. **VetGallery:** Vet images and testimonials are hardcoded.
|
||||
> 4. **Categories/Links:** Links to `/shop` and `/wiki` are static HTML.
|
||||
> 5. **Hero Section:** Banners and text are static.
|
||||
|
||||
#### [MODIFY] [page.tsx](file:///c:/Users/parsa/Desktop/work/caninairan/frontend/application/app/page.tsx)
|
||||
- No immediate file changes if we just wanted the list, but we will wrap components to fetch data dynamically where applicable.
|
||||
- For `SmartAdvisor`, we will ensure it uses the real database.
|
||||
|
||||
---
|
||||
### 5. Blogs/Wiki Integration [Frontend & Backend]
|
||||
Connects the Wiki page to the real backend database instead of hardcoded articles.
|
||||
|
||||
#### [MODIFY] [wiki/page.tsx](file:///c:/Users/parsa/Desktop/work/caninairan/frontend/application/app/wiki/page.tsx)
|
||||
- Replace static blog cards with `api.get('/blogs')` or Server-Side Rendering (SSR) fetching from the database.
|
||||
- Create dynamic routing `/wiki/[slug]/page.tsx` for individual blog articles.
|
||||
|
||||
## Verification Plan
|
||||
|
||||
### Automated Tests
|
||||
- Run `npm run build` in both backend and frontend to ensure no type errors.
|
||||
|
||||
### Manual Verification
|
||||
- **Auth:** Open the application, register a new account via Email and Password, log out, and log back in. Try mobile OTP login and confirm the OTP is in the network response.
|
||||
- **Pets:** Go to the pet profile dashboard, edit a pet's attributes across multiple steps, save, and refresh the page to verify persistence.
|
||||
- **Blogs:** Create a blog post in the Admin Panel, navigate to `/wiki` in the storefront, and verify it appears.
|
||||
Reference in new issue
Block a user