fosrl.pangolin/server/setup/ensureActions.ts

59 lines
2 KiB
TypeScript
Raw Permalink Normal View History

2024-10-06 18:12:27 -04:00
import { ActionsEnum } from "@server/auth/actions";
import { db } from "@server/db";
2025-06-04 12:02:07 -04:00
import { actions, roles, roleActions } from "@server/db";
2024-12-22 12:33:49 -05:00
import { eq, inArray } 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
2025-06-04 12:02:07 -04:00
await db.transaction(async (trx) => {
// Add new actions
for (const actionId of actionsToAdd) {
logger.debug(`Adding action: ${actionId}`);
await trx.insert(actions).values({ actionId }).execute();
// Add new actions to the Default role
if (defaultRoles.length != 0) {
await trx
.insert(roleActions)
.values(
defaultRoles.map((role) => ({
roleId: role.roleId!,
actionId,
orgId: role.orgId!
}))
)
.execute();
}
}
2024-12-24 16:00:02 -05:00
2025-06-04 12:02:07 -04:00
// Remove deprecated actions
if (actionsToRemove.length > 0) {
logger.debug(`Removing actions: ${actionsToRemove.join(", ")}`);
2024-12-24 16:00:02 -05:00
await trx
2025-06-04 12:02:07 -04:00
.delete(actions)
.where(inArray(actions.actionId, actionsToRemove))
.execute();
await trx
.delete(roleActions)
.where(inArray(roleActions.actionId, actionsToRemove))
2024-10-21 22:13:53 -04:00
.execute();
}
2024-12-24 16:00:02 -05:00
});
}