Neah/app/api/courrier/session/route.ts
2025-04-27 16:05:04 +02:00

112 lines
3.6 KiB
TypeScript

import { NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
import { getUserEmailCredentials } from '@/lib/services/email-service';
import { prefetchUserEmailData } from '@/lib/services/prefetch-service';
import { getCachedEmailCredentials, getRedisStatus, warmupRedisCache, getCachedImapSession, cacheImapSession } from '@/lib/redis';
// Keep track of last prefetch time for each user
const lastPrefetchMap = new Map<string, number>();
const PREFETCH_COOLDOWN_MS = 30000; // 30 seconds cooldown between prefetches
/**
* This endpoint is called when the app initializes to check if the user has email credentials
* and to start prefetching email data in the background if they do
*/
export async function GET() {
try {
// Warm up Redis connection
await warmupRedisCache();
// Get Redis status to include in response
const redisStatus = await getRedisStatus();
// Get server session to verify authentication
const session = await getServerSession(authOptions);
// Check if user is authenticated
if (!session?.user?.id) {
return NextResponse.json({
authenticated: false,
redisStatus,
message: "Not authenticated"
});
}
const userId = session.user.id;
// Check when we last prefetched for this user
const lastPrefetchTime = lastPrefetchMap.get(userId) || 0;
const now = Date.now();
const shouldPrefetch = now - lastPrefetchTime > PREFETCH_COOLDOWN_MS;
// Check if we have a cached session
const cachedSession = await getCachedImapSession(userId);
// First, check Redis cache for credentials
let credentials = await getCachedEmailCredentials(userId);
let credentialsSource = 'cache';
// If not in cache, check database
if (!credentials) {
credentials = await getUserEmailCredentials(userId);
credentialsSource = 'database';
}
// If no credentials found
if (!credentials) {
return NextResponse.json({
authenticated: true,
hasEmailCredentials: false,
redisStatus,
message: "No email credentials found"
});
}
let prefetchStarted = false;
// Only prefetch if the cooldown period has elapsed
if (shouldPrefetch) {
// Update the last prefetch time
lastPrefetchMap.set(userId, now);
// Start prefetching email data in the background
// We don't await this to avoid blocking the response
prefetchUserEmailData(userId).catch(err => {
console.error('Background prefetch error:', err);
});
prefetchStarted = true;
} else {
console.log(`Skipping prefetch for ${userId}, last prefetch was ${Math.round((now - lastPrefetchTime)/1000)}s ago`);
}
// Store last visit time in session data
if (cachedSession) {
await cacheImapSession(userId, {
...cachedSession,
lastVisit: now
});
} else {
await cacheImapSession(userId, { lastVisit: now });
}
// Return session info without sensitive data
return NextResponse.json({
authenticated: true,
hasEmailCredentials: true,
email: credentials.email,
redisStatus,
prefetchStarted,
credentialsSource,
lastVisit: cachedSession?.lastVisit,
mailboxes: cachedSession?.mailboxes || []
});
} catch (error) {
console.error("Error checking session:", error);
return NextResponse.json({
authenticated: false,
error: "Internal Server Error"
}, { status: 500 });
}
}