ensureActions.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import { ActionsEnum } from "@server/auth/actions";
  2. import { db } from "@server/db";
  3. import { actions, roles, roleActions } from "./schema";
  4. import { eq, and, inArray, notInArray } from "drizzle-orm";
  5. import logger from "@server/logger";
  6. export async function ensureActions() {
  7. const actionIds = Object.values(ActionsEnum);
  8. const existingActions = await db.select().from(actions).execute();
  9. const existingActionIds = existingActions.map(action => action.actionId);
  10. const actionsToAdd = actionIds.filter(id => !existingActionIds.includes(id));
  11. const actionsToRemove = existingActionIds.filter(id => !actionIds.includes(id as ActionsEnum));
  12. const defaultRoles = await db
  13. .select()
  14. .from(roles)
  15. .where(eq(roles.isSuperuserRole, true))
  16. .execute();
  17. if (defaultRoles.length === 0) {
  18. logger.info('No default roles to assign');
  19. return;
  20. }
  21. // Add new actions
  22. for (const actionId of actionsToAdd) {
  23. await db.insert(actions).values({ actionId }).execute();
  24. // Add new actions to the Default role
  25. await db.insert(roleActions)
  26. .values(defaultRoles.map(role => ({ roleId: role.roleId!, actionId, orgId: role.orgId! })))
  27. .execute();
  28. }
  29. // Remove deprecated actions
  30. if (actionsToRemove.length > 0) {
  31. await db.delete(actions).where(inArray(actions.actionId, actionsToRemove)).execute();
  32. await db.delete(roleActions).where(inArray(roleActions.actionId, actionsToRemove)).execute();
  33. }
  34. }
  35. export async function createSuperuserRole(orgId: number) {
  36. // Create the Default role if it doesn't exist
  37. const [insertedRole] = await db
  38. .insert(roles)
  39. .values({
  40. orgId,
  41. isSuperuserRole: true,
  42. name: 'Superuser',
  43. description: 'Superuser role with all actions'
  44. })
  45. .returning({ roleId: roles.roleId })
  46. .execute();
  47. const roleId = insertedRole.roleId;
  48. // Add all current actions to the new Default role
  49. const actionIds = Object.values(ActionsEnum);
  50. await db.insert(roleActions)
  51. .values(actionIds.map(actionId => ({
  52. roleId,
  53. actionId: actionId,
  54. orgId
  55. })))
  56. .execute();
  57. }