133 lines
4.8 KiB
TypeScript
133 lines
4.8 KiB
TypeScript
import { NextResponse } from 'next/server';
|
|
import { getServerSession } from 'next-auth';
|
|
import { authOptions } from '@/app/api/auth/[...nextauth]/route';
|
|
import { prisma } from '@/lib/prisma';
|
|
import { getRedisClient } from '@/lib/redis';
|
|
|
|
// This is an admin-only route to restore email credentials from Redis to the database
|
|
export async function GET(request: Request) {
|
|
try {
|
|
// Authenticate user
|
|
const session = await getServerSession(authOptions);
|
|
if (!session?.user?.id) {
|
|
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
|
|
}
|
|
|
|
// Only allow authorized users
|
|
if (!session.user.role.includes('admin')) {
|
|
return NextResponse.json({ error: 'Admin access required' }, { status: 403 });
|
|
}
|
|
|
|
const redis = getRedisClient();
|
|
|
|
// Get all email credential keys
|
|
const keys = await redis.keys('email:credentials:*');
|
|
console.log(`Found ${keys.length} credential records in Redis`);
|
|
|
|
const results = {
|
|
total: keys.length,
|
|
processed: 0,
|
|
success: 0,
|
|
errors: [] as string[]
|
|
};
|
|
|
|
// Process each key
|
|
for (const key of keys) {
|
|
results.processed++;
|
|
|
|
try {
|
|
// Extract user ID from key
|
|
const userId = key.split(':')[2];
|
|
if (!userId) {
|
|
results.errors.push(`Invalid key format: ${key}`);
|
|
continue;
|
|
}
|
|
|
|
// Get credentials from Redis
|
|
const credStr = await redis.get(key);
|
|
if (!credStr) {
|
|
results.errors.push(`No data found for key: ${key}`);
|
|
continue;
|
|
}
|
|
|
|
// Parse credentials
|
|
const creds = JSON.parse(credStr);
|
|
console.log(`Processing credentials for user ${userId}`, {
|
|
email: creds.email,
|
|
host: creds.host
|
|
});
|
|
|
|
// Check if user exists
|
|
const userExists = await prisma.user.findUnique({
|
|
where: { id: userId },
|
|
select: { id: true }
|
|
});
|
|
|
|
if (!userExists) {
|
|
// Create dummy user if needed (this is optional and might not be appropriate in all cases)
|
|
// Remove or modify this section if you don't want to create placeholder users
|
|
console.log(`User ${userId} not found, creating placeholder`);
|
|
await prisma.user.create({
|
|
data: {
|
|
id: userId,
|
|
email: creds.email || 'placeholder@example.com',
|
|
password: 'PLACEHOLDER_HASH_CHANGE_THIS', // You should set a proper password
|
|
// Add any other required fields
|
|
}
|
|
});
|
|
console.log(`Created placeholder user ${userId}`);
|
|
}
|
|
|
|
// Upsert credentials in database
|
|
await prisma.mailCredentials.upsert({
|
|
where: { userId },
|
|
update: {
|
|
email: creds.email,
|
|
password: creds.encryptedPassword || 'encrypted_placeholder',
|
|
host: creds.host,
|
|
port: creds.port,
|
|
// Optional fields
|
|
...(creds.secure !== undefined && { secure: creds.secure }),
|
|
...(creds.smtp_host && { smtp_host: creds.smtp_host }),
|
|
...(creds.smtp_port && { smtp_port: creds.smtp_port }),
|
|
...(creds.smtp_secure !== undefined && { smtp_secure: creds.smtp_secure }),
|
|
...(creds.display_name && { display_name: creds.display_name }),
|
|
...(creds.color && { color: creds.color })
|
|
},
|
|
create: {
|
|
userId,
|
|
email: creds.email,
|
|
password: creds.encryptedPassword || 'encrypted_placeholder',
|
|
host: creds.host,
|
|
port: creds.port,
|
|
// Optional fields
|
|
...(creds.secure !== undefined && { secure: creds.secure }),
|
|
...(creds.smtp_host && { smtp_host: creds.smtp_host }),
|
|
...(creds.smtp_port && { smtp_port: creds.smtp_port }),
|
|
...(creds.smtp_secure !== undefined && { smtp_secure: creds.smtp_secure }),
|
|
...(creds.display_name && { display_name: creds.display_name }),
|
|
...(creds.color && { color: creds.color })
|
|
}
|
|
});
|
|
|
|
results.success++;
|
|
console.log(`Successfully restored credentials for user ${userId}`);
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
results.errors.push(`Error processing ${key}: ${message}`);
|
|
console.error(`Error processing ${key}:`, error);
|
|
}
|
|
}
|
|
|
|
return NextResponse.json({
|
|
message: 'Credential restoration process completed',
|
|
results
|
|
});
|
|
} catch (error) {
|
|
console.error('Error in restore credentials route:', error);
|
|
return NextResponse.json(
|
|
{ error: 'Failed to restore credentials', details: error instanceof Error ? error.message : String(error) },
|
|
{ status: 500 }
|
|
);
|
|
}
|
|
}
|