fosrl.pangolin/server/db/ensureActions.ts

92 lines
2.6 KiB
TypeScript
Raw Normal View History

2024-10-06 18:12:27 -04:00
import { ActionsEnum } from "@server/auth/actions";
import { db } from "@server/db";
2024-10-10 21:59:30 -04:00
import { actions, roles, roleActions } from "./schema";
import { eq, and, inArray, notInArray } from "drizzle-orm";
2024-10-13 18:41:15 -04:00
import logger from "@server/logger";
2024-10-06 18:12:27 -04:00
export async function ensureActions() {
const actionIds = Object.values(ActionsEnum);
2024-10-10 21:59:30 -04:00
const existingActions = await db.select().from(actions).execute();
const existingActionIds = existingActions.map((action) => action.actionId);
2024-10-06 18:12:27 -04:00
const actionsToAdd = actionIds.filter(
(id) => !existingActionIds.includes(id)
);
const actionsToRemove = existingActionIds.filter(
(id) => !actionIds.includes(id as ActionsEnum)
);
2024-10-10 21:59:30 -04:00
const defaultRoles = await db
2024-10-06 18:12:27 -04:00
.select()
2024-10-10 21:59:30 -04:00
.from(roles)
.where(eq(roles.isAdmin, true))
2024-10-06 18:12:27 -04:00
.execute();
2024-10-10 21:59:30 -04:00
// Add new actions
for (const actionId of actionsToAdd) {
2024-10-26 17:02:11 -04:00
logger.debug(`Adding action: ${actionId}`);
2024-10-21 22:13:53 -04:00
await db.insert(actions).values({ actionId }).execute();
2024-10-10 21:59:30 -04:00
// Add new actions to the Default role
2024-10-26 17:02:11 -04:00
if (defaultRoles.length != 0) {
await db
.insert(roleActions)
.values(
defaultRoles.map((role) => ({
roleId: role.roleId!,
actionId,
orgId: role.orgId!,
}))
)
2024-10-21 22:13:53 -04:00
.execute();
}
2024-10-10 21:59:30 -04:00
}
// Remove deprecated actions
if (actionsToRemove.length > 0) {
logger.debug(`Removing actions: ${actionsToRemove.join(", ")}`);
await db
.delete(actions)
.where(inArray(actions.actionId, actionsToRemove))
.execute();
await db
.delete(roleActions)
.where(inArray(roleActions.actionId, actionsToRemove))
.execute();
2024-10-06 18:12:27 -04:00
}
2024-10-10 21:59:30 -04:00
}
export async function createAdminRole(orgId: string) {
2024-10-10 21:59:30 -04:00
const [insertedRole] = await db
.insert(roles)
.values({
orgId,
isAdmin: true,
name: "Admin",
description: "Admin role with the most permissions",
2024-10-10 21:59:30 -04:00
})
.returning({ roleId: roles.roleId })
.execute();
const roleId = insertedRole.roleId;
2024-10-13 22:45:48 -04:00
const actionIds = await db.select().from(actions).execute();
if (actionIds.length === 0) {
logger.info("No actions to assign to the Admin role");
2024-10-13 22:45:48 -04:00
return;
}
await db
.insert(roleActions)
.values(
actionIds.map((action) => ({
roleId,
actionId: action.actionId,
orgId,
}))
)
2024-10-10 21:59:30 -04:00
.execute();
2024-10-14 19:30:38 -04:00
return roleId;
}