Neah/app/api/auth/session-cleanup/route.ts
2025-05-02 12:33:43 +02:00

52 lines
1.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { cleanupUserSessions } from '@/lib/redis';
import { closeUserImapConnections } from '@/lib/services/email-service';
/**
* API endpoint to clean up user sessions and invalidate cached data
* Called during logout to ensure proper cleanup of all connections
*/
export async function POST(request: NextRequest) {
try {
// Get the user ID either from the session or request body
const session = await getServerSession(authOptions);
const body = await request.json().catch(() => ({}));
// Get user ID from session or from request body
const userId = session?.user?.id || body.userId;
if (!userId) {
return NextResponse.json({
success: false,
error: 'No user ID provided or user not authenticated'
}, { status: 400 });
}
console.log(`Processing session cleanup for user ${userId}`);
// 1. Close any active IMAP connections using the dedicated function
const closedConnections = await closeUserImapConnections(userId);
// 2. Clean up Redis data
await cleanupUserSessions(userId);
// 3. Return success response with details
return NextResponse.json({
success: true,
message: `Session cleanup completed for user ${userId}`,
details: {
closedConnections,
redisCleanupPerformed: true
}
});
} catch (error) {
console.error('Error in session cleanup:', error);
return NextResponse.json({
success: false,
error: 'Session cleanup failed',
details: error instanceof Error ? error.message : 'Unknown error'
}, { status: 500 });
}
}