69 lines
2.2 KiB
TypeScript
69 lines
2.2 KiB
TypeScript
import "dotenv/config";
|
|
import { PrismaClient } from "@prisma/client";
|
|
import { seedRbac } from "../prisma/rbac-seed";
|
|
const db = new PrismaClient();
|
|
async function main() {
|
|
await seedRbac(db);
|
|
await db.$transaction(async (tx) => {
|
|
await tx.$queryRaw`SELECT pg_advisory_xact_lock(822100)::text`;
|
|
const done = await tx.auditEvent.findFirst({
|
|
where: { action: "migration.rbac" },
|
|
});
|
|
if (done) return;
|
|
const users = await tx.user.findMany();
|
|
const emails = users.map((u) => u.email.trim().toLowerCase());
|
|
if (new Set(emails).size !== emails.length)
|
|
throw new Error(
|
|
"Doppelte normalisierte E-Mail-Adressen vor Migration auflösen",
|
|
);
|
|
for (const user of users) {
|
|
await tx.user.update({
|
|
where: { id: user.id },
|
|
data: {
|
|
email: user.email.trim().toLowerCase(),
|
|
sessionVersion: { increment: 1 },
|
|
},
|
|
});
|
|
await tx.userGroup.upsert({
|
|
where: { userId_groupId: { userId: user.id, groupId: "legacy" } },
|
|
create: { userId: user.id, groupId: "legacy" },
|
|
update: {},
|
|
});
|
|
const roleId = {
|
|
ADMIN: "system-admin",
|
|
VORGESETZTER: "leader",
|
|
PFLEGER: "coordinator",
|
|
BEARBEITER: "worker",
|
|
}[user.role];
|
|
const scope = user.role === "BEARBEITER" ? "ASSIGNED" : "GLOBAL";
|
|
const key = {
|
|
userId: user.id,
|
|
roleId,
|
|
scope: scope as "ASSIGNED" | "GLOBAL",
|
|
targetGroupId: "",
|
|
};
|
|
await tx.userRole.upsert({
|
|
where: { userId_roleId_scope_targetGroupId: key },
|
|
create: key,
|
|
update: {},
|
|
});
|
|
if (user.role === "PFLEGER") {
|
|
const assigned = { userId: user.id, roleId: "worker", scope: "ASSIGNED" as const, targetGroupId: "" };
|
|
await tx.userRole.upsert({ where: { userId_roleId_scope_targetGroupId: assigned }, create: assigned, update: {} });
|
|
}
|
|
}
|
|
await tx.auditEvent.create({
|
|
data: {
|
|
actorId: "migration",
|
|
action: "migration.rbac",
|
|
targetId: "system",
|
|
data: { users: users.length },
|
|
},
|
|
});
|
|
}, { timeout: 120000 });
|
|
console.log(
|
|
"RBAC-Datenmigration abgeschlossen. Globale Altzuweisungen in der Verwaltung prüfen.",
|
|
);
|
|
}
|
|
main().finally(() => db.$disconnect());
|