76 lines
2.3 KiB
TypeScript
76 lines
2.3 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 } from '@/lib/redis';
|
|
|
|
/**
|
|
* 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;
|
|
|
|
// 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"
|
|
});
|
|
}
|
|
|
|
// 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);
|
|
});
|
|
|
|
// Return session info without sensitive data
|
|
return NextResponse.json({
|
|
authenticated: true,
|
|
hasEmailCredentials: true,
|
|
email: credentials.email,
|
|
redisStatus,
|
|
prefetchStarted: true,
|
|
credentialsSource
|
|
});
|
|
} catch (error) {
|
|
console.error("Error checking session:", error);
|
|
return NextResponse.json({
|
|
authenticated: false,
|
|
error: "Internal Server Error"
|
|
}, { status: 500 });
|
|
}
|
|
}
|