NeahNew/app/api/sync-users/route.ts
2025-05-04 22:14:41 +02:00

84 lines
2.2 KiB
TypeScript

import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
import bcrypt from 'bcryptjs';
const prisma = new PrismaClient();
export async function GET() {
try {
// Fetch users from equipes endpoint
const response = await fetch(process.env.EQUIPES_API_URL || 'https://equipes-api-url/users', {
headers: {
'Authorization': `Bearer ${process.env.EQUIPES_API_TOKEN}`,
},
});
if (!response.ok) {
throw new Error(`API responded with status: ${response.status}`);
}
const equipeUsers = await response.json();
const results = {
total: equipeUsers.length,
created: 0,
updated: 0,
failed: 0,
};
// Process each user from equipes
for (const user of equipeUsers) {
try {
// Check if the keycloak ID exists in our database
const existingUser = await prisma.user.findUnique({
where: { id: user.id },
});
if (existingUser) {
// Update existing user
await prisma.user.update({
where: { id: user.id },
data: {
email: user.email,
// Don't update password as it might be locally changed
updatedAt: new Date(),
},
});
results.updated++;
} else {
// Create new user
// Generate a temporary random password
const tempPassword = await bcrypt.hash(Math.random().toString(36).slice(-10), 10);
await prisma.user.create({
data: {
id: user.id, // Use the keycloak ID as our primary ID
email: user.email,
password: tempPassword,
createdAt: new Date(),
updatedAt: new Date(),
},
});
results.created++;
}
} catch (error: any) {
console.error(`Error processing user ${user.id}:`, error);
results.failed++;
}
}
return NextResponse.json({
success: true,
results,
});
} catch (error: any) {
console.error('Error syncing users:', error);
return NextResponse.json(
{
success: false,
error: error.message
},
{ status: 500 }
);
}
}