fix(all): auto-create ticket tables, multi-tier otp rate limiting, packaged order status & badges, pet kindness footprint
Deploy Canina / deploy (push) Successful in 1m46s

This commit is contained in:
parsa aghaei committed 2026-08-16 19:19:20 +03:30
1 parent d9254e9b01
commit 884b0486cc
8 files changed
+239 -24

No files matched your search

+55 -1
View File
@@ -1,4 +1,4 @@
import { Injectable, BadRequestException } from '@nestjs/common';
import { Injectable, BadRequestException, HttpException, HttpStatus } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { PrismaService } from '../prisma/prisma.service';
import { RedisService } from '../redis/redis.service';
@@ -25,6 +25,7 @@ export class LoginInput {
export class AdminLoginInput {
email!: string;
password?: string;
username?: string;
}
@Injectable()
@@ -39,8 +40,56 @@ export class AuthService {
async sendOtp(sendOtpDto: SendOtpDto) {
const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber);
// 1. Check 60-second cooldown per phone number
const cooldownKey = `otp:cooldown:${phoneNumber}`;
const inCooldown = await this.redisService.get(cooldownKey);
if (inCooldown) {
const remainingTtl = await this.redisService.ttl(cooldownKey);
throw new HttpException(
{
success: false,
statusCode: HttpStatus.TOO_MANY_REQUESTS,
message: `لطفاً ${Math.max(1, remainingTtl)} ثانیه دیگر مجدداً تلاش کنید.`,
code: 'OTP_COOLDOWN',
remainingSeconds: Math.max(1, remainingTtl),
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
// 2. Hourly rate limit: Max 5 OTP requests per hour per phone
const hourKey = `otp:rate:hour:${phoneNumber}`;
const hourlyRequests = await this.redisService.incr(hourKey, 3600);
if (hourlyRequests > 5) {
throw new HttpException(
{
success: false,
statusCode: HttpStatus.TOO_MANY_REQUESTS,
message: 'تعداد دفعات ارسال پیامک در یک ساعت بیش از حد مجاز است. لطفاً ساعتی دیگر تلاش کنید.',
code: 'HOURLY_RATE_LIMIT_EXCEEDED',
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
// 3. Daily rate limit: Max 10 OTP requests per 24 hours per phone
const dayKey = `otp:rate:day:${phoneNumber}`;
const dailyRequests = await this.redisService.incr(dayKey, 86400);
if (dailyRequests > 10) {
throw new HttpException(
{
success: false,
statusCode: HttpStatus.TOO_MANY_REQUESTS,
message: 'سقف ارسال روزانه پیامک برای این شماره تکمیل شده است. لطفاً فردا مجدداً تلاش کنید.',
code: 'DAILY_RATE_LIMIT_EXCEEDED',
},
HttpStatus.TOO_MANY_REQUESTS,
);
}
const code = crypto.randomInt(10000, 100000).toString();
// Store OTP for 120 seconds
await this.redisService.set(`otp:${phoneNumber}`, code, 120);
// Dispatch OTP via MeliPayamak Pattern SMS
@@ -56,9 +105,14 @@ export class AuthService {
});
}
// Set 60-second cooldown lock
await this.redisService.set(cooldownKey, '1', 60);
return {
success: true,
message: 'کد تایید با موفقیت به شماره شما پیامک شد.',
expiresIn: 120,
cooldown: 60,
};
}
+56
View File
@@ -8,6 +8,62 @@ export class PrismaService
{
async onModuleInit() {
await this.$connect();
await this.ensureTablesExist();
}
private async ensureTablesExist() {
try {
await this.$executeRawUnsafe(`
CREATE TABLE IF NOT EXISTS "tickets" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"ticket_number" VARCHAR(50) NOT NULL UNIQUE,
"user_id" UUID NOT NULL REFERENCES "users"("id") ON DELETE CASCADE,
"pet_id" UUID REFERENCES "pets"("id") ON DELETE SET NULL,
"subject" VARCHAR(255) NOT NULL,
"category" VARCHAR(50) NOT NULL DEFAULT 'VET_CONSULTATION',
"priority" VARCHAR(20) NOT NULL DEFAULT 'MEDIUM',
"status" VARCHAR(30) NOT NULL DEFAULT 'OPEN',
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updated_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS "tickets_user_id_idx" ON "tickets"("user_id");
CREATE INDEX IF NOT EXISTS "tickets_status_idx" ON "tickets"("status");
CREATE INDEX IF NOT EXISTS "tickets_category_idx" ON "tickets"("category");
CREATE INDEX IF NOT EXISTS "tickets_created_at_idx" ON "tickets"("created_at");
CREATE TABLE IF NOT EXISTS "ticket_messages" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"ticket_id" UUID NOT NULL REFERENCES "tickets"("id") ON DELETE CASCADE,
"sender_id" UUID,
"sender_role" VARCHAR(30) NOT NULL DEFAULT 'USER',
"sender_name" VARCHAR(100) NOT NULL,
"message" TEXT NOT NULL,
"attachment" TEXT,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS "ticket_messages_ticket_id_idx" ON "ticket_messages"("ticket_id");
CREATE INDEX IF NOT EXISTS "ticket_messages_created_at_idx" ON "ticket_messages"("created_at");
CREATE TABLE IF NOT EXISTS "sms_logs" (
"id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),
"phone" VARCHAR(20) NOT NULL,
"pattern_id" INTEGER,
"message" TEXT,
"status" VARCHAR(50) NOT NULL,
"bulk_id" VARCHAR(100),
"meta" JSONB,
"created_at" TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS "sms_logs_phone_idx" ON "sms_logs"("phone");
CREATE INDEX IF NOT EXISTS "sms_logs_status_idx" ON "sms_logs"("status");
CREATE INDEX IF NOT EXISTS "sms_logs_created_at_idx" ON "sms_logs"("created_at");
`);
} catch (err) {
console.warn('[PrismaService] Auto table check warning:', err);
}
}
async onModuleDestroy() {
+4
View File
@@ -40,4 +40,8 @@ export class RedisService implements OnModuleInit, OnModuleDestroy {
}
return count;
}
async ttl(key: string): Promise<number> {
return this.client.ttl(key);
}
}