Skip to content

Commit 634cbb1

Browse files
committed
feat: 重复创建工单保护
1 parent 970aeaf commit 634cbb1

File tree

1 file changed

+8
-7
lines changed

1 file changed

+8
-7
lines changed

next/api/src/router/ticket.ts

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -359,12 +359,13 @@ const ticketRateLimitMiddleware: Middleware = async (ctx: Context, next) => {
359359

360360
if (!isCS && redis) {
361361
console.log(`[Rate Limit] Checking rate limit for non-CS user ${currentUser.id}.`);
362+
let currentCount = 0;
362363
try {
363364
const today = new Date().toISOString().slice(0, 10).replace(/-/g, ''); // YYYYMMDD
364365
const redisKey = `rate_limit:ticket:create:${currentUser.id}:${today}`;
365366
console.log(`[Rate Limit] User: ${currentUser.id}, Date: ${today}, Key: ${redisKey}`);
366367

367-
const currentCount = await redis.incr(redisKey);
368+
currentCount = await redis.incr(redisKey);
368369
console.log(`[Rate Limit] Redis INCR result for key ${redisKey}: ${currentCount}`);
369370

370371
if (currentCount === 1) {
@@ -373,17 +374,17 @@ const ticketRateLimitMiddleware: Middleware = async (ctx: Context, next) => {
373374
await redis.expire(redisKey, 86400); // 86400 seconds = 24 hours
374375
}
375376

376-
if (currentCount > DAILY_TICKET_LIMIT) {
377-
console.warn(`[Rate Limit] Limit exceeded for user ${currentUser.id}. Count: ${currentCount}. Denying request.`);
378-
ctx.throw(429, `Rate limit exceeded. You can create up to ${DAILY_TICKET_LIMIT} tickets per day.`);
379-
return; // Stop processing
380-
}
381377
} catch (error: any) {
382378
console.error(`[Rate Limit] Redis rate limiting check failed for user ${currentUser.id}:`, error);
383379
// Log error to Sentry or other monitoring
384380
// captureException(error, { extra: { component: 'TicketAPIV2', msg: 'Rate limit check failed', userId: currentUser.id } });
385381
// Fail open: If Redis fails, allow the request to proceed.
386382
}
383+
if (currentCount > DAILY_TICKET_LIMIT) {
384+
console.warn(`[Rate Limit] Limit exceeded for user ${currentUser.id}. Count: ${currentCount}. Denying request.`);
385+
ctx.throw(429, `Rate limit exceeded. You can create up to ${DAILY_TICKET_LIMIT} tickets per day.`);
386+
return; // Stop processing
387+
}
387388
} else if (!redis) {
388389
console.warn(`[Rate Limit] Redis client is not available. Skipping rate limiting check for user ${currentUser.id}.`);
389390
} else {
@@ -495,8 +496,8 @@ const ticketDuplicateCheckMiddleware: Middleware = async (ctx: Context, next) =>
495496

496497
router.post('/',
497498
// Apply the new middleware BEFORE the main handler
498-
ticketRateLimitMiddleware,
499499
ticketDuplicateCheckMiddleware,
500+
ticketRateLimitMiddleware,
500501
// Original handler starts here
501502
async (ctx: Context) => {
502503
const currentUser = ctx.state.currentUser as User;

0 commit comments

Comments
 (0)