87 lines
2.5 KiB
TypeScript
87 lines
2.5 KiB
TypeScript
const { PrismaClient } = require('@prisma/client');
|
|
const bcrypt = require('bcryptjs');
|
|
require('dotenv').config();
|
|
|
|
const prisma = new PrismaClient();
|
|
|
|
async function syncUsers() {
|
|
try {
|
|
console.log('Starting user sync process...');
|
|
|
|
// Fetch users from equipes endpoint
|
|
const apiUrl = process.env.EQUIPES_API_URL || 'https://equipes-api-url/users';
|
|
console.log(`Fetching users from: ${apiUrl}`);
|
|
|
|
const response = await fetch(apiUrl, {
|
|
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();
|
|
console.log(`Fetched ${equipeUsers.length} users from equipes API`);
|
|
|
|
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(),
|
|
},
|
|
});
|
|
console.log(`Updated user: ${user.id} (${user.email})`);
|
|
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(),
|
|
},
|
|
});
|
|
console.log(`Created new user: ${user.id} (${user.email})`);
|
|
results.created++;
|
|
}
|
|
} catch (error: any) {
|
|
console.error(`Error processing user ${user.id}:`, error);
|
|
results.failed++;
|
|
}
|
|
}
|
|
|
|
console.log('Sync completed. Results:', results);
|
|
} catch (error: any) {
|
|
console.error('Error syncing users:', error);
|
|
} finally {
|
|
await prisma.$disconnect();
|
|
}
|
|
}
|
|
|
|
// Run the sync function
|
|
syncUsers();
|