Backfill api keys
This commit is contained in:
@@ -3,6 +3,7 @@ import { z } from "zod";
|
||||
|
||||
import { createTRPCRouter, protectedProcedure } from "~/server/api/trpc";
|
||||
import { prisma } from "~/server/db";
|
||||
import { generateApiKey } from "~/server/utils/generateApiKey";
|
||||
import { requireCanModifyOrganization, requireNothing } from "~/utils/accessControl";
|
||||
|
||||
export const organizationsRouter = createTRPCRouter({
|
||||
@@ -41,6 +42,13 @@ export const organizationsRouter = createTRPCRouter({
|
||||
role: "ADMIN",
|
||||
},
|
||||
}),
|
||||
prisma.apiKey.create({
|
||||
data: {
|
||||
name: "Default API Key",
|
||||
organizationId: newOrgId,
|
||||
apiKey: generateApiKey(),
|
||||
},
|
||||
}),
|
||||
]);
|
||||
organizations.push(newOrg);
|
||||
}
|
||||
@@ -53,6 +61,9 @@ export const organizationsRouter = createTRPCRouter({
|
||||
where: {
|
||||
id: input.id,
|
||||
},
|
||||
include: {
|
||||
apiKeys: true,
|
||||
}
|
||||
});
|
||||
}),
|
||||
update: protectedProcedure
|
||||
|
||||
33
app/src/server/scripts/backfillApiKeys.ts
Normal file
33
app/src/server/scripts/backfillApiKeys.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
import { type Prisma } from "@prisma/client";
|
||||
import { prisma } from "~/server/db";
|
||||
import { generateApiKey } from "~/server/utils/generateApiKey";
|
||||
|
||||
console.log("backfilling api keys");
|
||||
|
||||
const organizations = await prisma.organization.findMany({
|
||||
include: {
|
||||
apiKeys: true,
|
||||
},
|
||||
});
|
||||
|
||||
console.log(`found ${organizations.length} organizations`);
|
||||
|
||||
const apiKeysToCreate: Prisma.ApiKeyCreateManyInput[] = [];
|
||||
|
||||
for (const org of organizations) {
|
||||
if (!org.apiKeys.length) {
|
||||
apiKeysToCreate.push({
|
||||
name: "Default API Key",
|
||||
organizationId: org.id,
|
||||
apiKey: generateApiKey(),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`creating ${apiKeysToCreate.length} api keys`);
|
||||
|
||||
await prisma.apiKey.createMany({
|
||||
data: apiKeysToCreate,
|
||||
});
|
||||
|
||||
console.log("done");
|
||||
11
app/src/server/utils/generateApiKey.ts
Normal file
11
app/src/server/utils/generateApiKey.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
const KEY_LENGTH = 42;
|
||||
|
||||
export const generateApiKey = () => {
|
||||
const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
|
||||
let randomChars = "";
|
||||
for (let i = 0; i < KEY_LENGTH; i++) {
|
||||
randomChars += chars.charAt(Math.floor(Math.random() * chars.length));
|
||||
}
|
||||
|
||||
return `opc_${randomChars}`;
|
||||
};
|
||||
Reference in New Issue
Block a user