25 lines1,226 bytesCodeBlame
1import { redirect } from "react-router";
2
3import type { Route } from "./+types/github-install";
4import { INSTALL_COOKIE, cookie, installCookieValue, newState } from "../lib/github";
5import { githubApp } from "../lib/github.server";
6import { requireUser, roleIn } from "../lib/session.server";
7
8/**
9 * Sends a workspace owner to GitHub to install g1t's GitHub App on an
10 * account or organization. GitHub returns to /integrations/github/setup
11 * with the state, which must match the cookie set here.
12 */
13export async function loader({ request, context }: Route.LoaderArgs) {
14 const user = requireUser(context, request);
15 const workspace = (new URL(request.url).searchParams.get("workspace") ?? "").toLowerCase();
16 if (roleIn(user, workspace) !== "owner") throw redirect(`/new/github?workspace=${encodeURIComponent(workspace)}`);
17 const status = await githubApp.status(user, workspace);
18 if (!status.ok || !status.value.installUrl) throw redirect("/new");
19 const state = newState();
20 const target = new URL(status.value.installUrl);
21 target.searchParams.set("state", state);
22 throw redirect(target.toString(), {
23 headers: { "set-cookie": cookie(INSTALL_COOKIE, installCookieValue(state, workspace), 1800) },
24 });
25}