diff --git a/apps/dokploy/pages/api/providers/github/setup.ts b/apps/dokploy/pages/api/providers/github/setup.ts index 663939c5e..fc8869938 100644 --- a/apps/dokploy/pages/api/providers/github/setup.ts +++ b/apps/dokploy/pages/api/providers/github/setup.ts @@ -1,5 +1,6 @@ -import { createGithub } from "@dokploy/server"; +import { createGithub, validateRequest } from "@dokploy/server"; import { db } from "@dokploy/server/db"; +import { hasPermission } from "@dokploy/server/services/permission"; import { eq } from "drizzle-orm"; import type { NextApiRequest, NextApiResponse } from "next"; import { Octokit } from "octokit"; @@ -21,18 +22,22 @@ export default async function handler( if (!code) { return res.status(400).json({ error: "Missing code parameter" }); } - const [action, ...rest] = state?.split(":"); - // For gh_init: rest[0] = organizationId, rest[1] = userId - // For gh_setup: rest[0] = githubProviderId + + const { user, session } = await validateRequest(req); + if (!user || !session?.activeOrganizationId) { + return res.status(401).json({ error: "Unauthorized" }); + } + const ctx = { + user: { id: user.id }, + session: { activeOrganizationId: session.activeOrganizationId }, + }; + + const [action] = state?.split(":") ?? []; + if (!(await hasPermission(ctx, { gitProviders: ["create"] }))) { + return res.status(403).json({ error: "Forbidden" }); + } if (action === "gh_init") { - const organizationId = rest[0]; - const userId = rest[1] || (req.query.userId as string); - - if (!userId) { - return res.status(400).json({ error: "Missing userId parameter" }); - } - const octokit = new Octokit({}); const { data } = await octokit.request( "POST /app-manifests/{code}/conversions", @@ -51,16 +56,32 @@ export default async function handler( githubWebhookSecret: data.webhook_secret, githubPrivateKey: data.pem, }, - organizationId as string, - userId, + session.activeOrganizationId, + user.id, ); } else if (action === "gh_setup") { + const githubId = state?.split(":")[1]; + if (!githubId) { + return res.status(400).json({ error: "Missing github provider id" }); + } + + const provider = await db.query.github.findFirst({ + where: eq(github.githubId, githubId), + with: { gitProvider: true }, + }); + if ( + !provider || + provider.gitProvider.organizationId !== session.activeOrganizationId + ) { + return res.status(404).json({ error: "Github provider not found" }); + } + await db .update(github) .set({ githubInstallationId: installation_id, }) - .where(eq(github.githubId, rest[0] as string)) + .where(eq(github.githubId, githubId)) .returning(); }