Openstatus www.openstatus.dev

fix: server action (#698)

* fix: server action

* docs: add comment

* fix: ts error

authored by

Maximilian Kaske and committed by
GitHub
4ef733c7 151eaef0

+24 -1
+22
apps/web/src/app/app/[workspaceSlug]/(dashboard)/settings/api-token/_components/actions.ts
··· 1 1 "use server"; 2 2 3 + import { currentUser } from "@clerk/nextjs"; 3 4 import { Unkey } from "@unkey/api"; 4 5 6 + import { db, eq } from "@openstatus/db"; 7 + import { user, usersToWorkspaces, workspace } from "@openstatus/db/src/schema"; 8 + 5 9 import { env } from "@/env"; 6 10 7 11 const unkey = new Unkey({ token: env.UNKEY_TOKEN, cache: "no-cache" }); 12 + 13 + // REMINDER: server actions should have middlewares to do auth checks 8 14 9 15 export async function create(ownerId: number) { 16 + const _user = await currentUser(); 17 + 18 + if (!_user) return; 19 + 20 + const allowedWorkspaces = await db 21 + .select() 22 + .from(usersToWorkspaces) 23 + .innerJoin(user, eq(user.id, usersToWorkspaces.userId)) 24 + .innerJoin(workspace, eq(workspace.id, usersToWorkspaces.workspaceId)) 25 + .where(eq(user.tenantId, _user.id)) 26 + .all(); 27 + 28 + const allowedIds = allowedWorkspaces.map((i) => i.workspace.id); 29 + 30 + if (!allowedIds.includes(ownerId)) return; 31 + 10 32 const key = await unkey.keys.create({ 11 33 apiId: env.UNKEY_API_ID, 12 34 ownerId: String(ownerId),
+2 -1
apps/web/src/app/app/[workspaceSlug]/(dashboard)/settings/api-token/_components/create-form.tsx
··· 35 35 async function onCreate() { 36 36 try { 37 37 const res = await create(ownerId); 38 - if (res.result) { 38 + if (!res) toastAction("error"); 39 + if (res?.result) { 39 40 setRawKey(res.result.key); 40 41 } 41 42 } catch {