Skip to content

Commit

Permalink
Merge pull request #25 from diggerhq/feat/gh-app-callback
Browse files Browse the repository at this point in the history
Add github callback route to proxy backend
  • Loading branch information
ZIJ authored Aug 20, 2024
2 parents 5ef1504 + 6118667 commit 83fa1e8
Show file tree
Hide file tree
Showing 6 changed files with 111 additions and 22 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"@unkey/nextjs": "^0.15.0",
"@vercel/analytics": "^1.0.1",
"ai": "^3.1.12",
"async-retry": "^1.3.3",
"autoprefixer": "^10.4.13",
"axios": "^1.2.1",
"checkbox": "^0.0.1",
Expand Down
16 changes: 16 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import Link from "next/link";

export default function GithubAppError() {
const appSlug = process.env.NEXT_PUBLIC_GITHUB_APP_SLUG;
return (
<>
<h1>Something went wrong</h1>
<p>GitHub App installation failed. Maybe <Link href={`https://github.com/apps/${appSlug}/installations/new/`}>try re-install it?</Link></p>
</>
)
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import Link from "next/link";

export default function GithubAppError() {
return (
<>
<h1>Success</h1>
<p>GitHub App installed successfully. You can now close this tab or <Link href="/">go to dashboard</Link></p>
</>
)
}
22 changes: 0 additions & 22 deletions src/app/(dynamic-pages)/(login-pages)/auth/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,28 +22,6 @@ export async function GET(request: Request) {
}
}

// HACK_ALERT!!!
// cookie is probably set on 'next.digger.dev' we have to change it to `.digger.dev`
const cookieKey = `sb-${process.env.SUPABASE_PROJECT_REF}-auth-token`;
const cookieStore = cookies();
const currentCookieValue = cookieStore.get(cookieKey)?.value;
// get domain of current reques
const domain = new URL(request.url).hostname;
if (
domain.includes('next.digger.dev') &&
currentCookieValue &&
!isDevelopment
) {
// set cookie to .digger.dev
cookieStore.set(cookieKey, currentCookieValue, {
domain: '.digger.dev',
secure: true,
path: '/',
sameSite: 'lax',
httpOnly: true,
});
}

let redirectTo = new URL('/dashboard', requestUrl.origin);

if (next) {
Expand Down
73 changes: 73 additions & 0 deletions src/app/api/github-callback/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { createSupabaseUserRouteHandlerClient } from '@/supabase-clients/user/createSupabaseUserRouteHandlerClient';
import { toSiteURL } from '@/utils/helpers';
import { NextRequest, NextResponse } from 'next/server';

// Use the environment variable for the callback URL
const AUTH_SERVICE_URL = process.env.GITHUB_CALLBACK_URL;
const DIGGER_WEBHOOK_SECRET = process.env.DIGGER_WEBHOOK_SECRET;

if (!AUTH_SERVICE_URL) {
throw new Error('GITHUB_CALLBACK_URL environment variable is not set');
}

export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const installationId = searchParams.get('installation_id');

if (!installationId) {
return NextResponse.json(
{ error: 'Missing installation_id' },
{ status: 400 },
);
}

try {
console.log(
'Trying to get org id for the following installation ID:',
installationId,
);
const organizationId = await getOrganizationId();
const response = await fetch(
`${AUTH_SERVICE_URL}?${searchParams.toString()}`,
{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-Digger-Org-ID': organizationId,
Authorization: `Bearer ${DIGGER_WEBHOOK_SECRET}`,
},
},
);

if (!response.ok) {
throw new Error(`Auth service responded with status: ${response.status}`);
}
return NextResponse.redirect(toSiteURL('/github_app/success'));
} catch (error) {
console.error('Error handling GitHub App installation callback:', error);
return NextResponse.redirect(toSiteURL('/github_app/error'));
}
}

async function getOrganizationId(): Promise<string> {
const supabase = createSupabaseUserRouteHandlerClient();
const {
data: { user },
error,
} = await supabase.auth.getUser();
if (error || !user?.id) {
console.error('Failed to get current user', error);
throw error;
}
const { data: orgs, error: errOrg } = await supabase
.from('organization_members')
.select('*')
.eq('member_id', user.id);

if (errOrg || !orgs[0]) {
console.error('Failed to get org');
throw error;
}

return orgs[0].organization_id;
}

0 comments on commit 83fa1e8

Please sign in to comment.