Openstatus www.openstatus.dev
at 20d0eeac16db94063a196dbfa8cb02fb172cac98 76 lines 2.2 kB view raw
1import { Unkey } from "@unkey/api"; 2import { z } from "zod"; 3 4import { Events } from "@openstatus/analytics"; 5import { db, eq } from "@openstatus/db"; 6import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema"; 7 8import { TRPCError } from "@trpc/server"; 9import { env } from "../env"; 10import { createTRPCRouter, protectedProcedure } from "../trpc"; 11 12export const apiKeyRouter = createTRPCRouter({ 13 create: protectedProcedure 14 .meta({ track: Events.CreateAPI }) 15 .input(z.object({ ownerId: z.number() })) 16 .mutation(async ({ input, ctx }) => { 17 const unkey = new Unkey({ token: env.UNKEY_TOKEN, cache: "no-cache" }); 18 19 const allowedWorkspaces = await db 20 .select() 21 .from(usersToWorkspaces) 22 .innerJoin(user, eq(user.id, usersToWorkspaces.userId)) 23 .innerJoin(workspace, eq(workspace.id, usersToWorkspaces.workspaceId)) 24 .where(eq(user.id, ctx.user.id)) 25 .all(); 26 27 const allowedIds = allowedWorkspaces.map((i) => i.workspace.id); 28 29 if (!allowedIds.includes(input.ownerId)) { 30 throw new TRPCError({ 31 code: "UNAUTHORIZED", 32 message: "Unauthorized", 33 }); 34 } 35 36 const key = await unkey.keys.create({ 37 apiId: env.UNKEY_API_ID, 38 ownerId: String(input.ownerId), 39 prefix: "os", 40 }); 41 42 console.log(key); 43 44 return key; 45 }), 46 47 revoke: protectedProcedure 48 .meta({ track: Events.RevokeAPI }) 49 .input(z.object({ keyId: z.string() })) 50 .mutation(async ({ input }) => { 51 const unkey = new Unkey({ token: env.UNKEY_TOKEN, cache: "no-cache" }); 52 53 const res = await unkey.keys.delete({ keyId: input.keyId }); 54 return res; 55 }), 56 57 get: protectedProcedure.query(async ({ ctx }) => { 58 const unkey = new Unkey({ token: env.UNKEY_TOKEN, cache: "no-cache" }); 59 60 const data = await unkey.apis.listKeys({ 61 apiId: env.UNKEY_API_ID, 62 ownerId: String(ctx.workspace.id), 63 }); 64 65 if (data?.error) { 66 throw new TRPCError({ 67 code: "INTERNAL_SERVER_ERROR", 68 message: "Something went wrong. Please contact us.", 69 }); 70 } 71 72 const value = data.result.keys?.[0] || null; 73 74 return value; 75 }), 76});