Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 2 additions & 19 deletions app/api/auth/github/route.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { buildGitHubAuthorizationUrl } from '../../../../lib/github-oauth.js';

const GITHUB_CLIENT_ID = process.env.GITHUB_CLIENT_ID;

function getBaseUrl(hdrs) {
const host = hdrs.get('x-forwarded-host') || hdrs.get('host') || 'localhost:3000';
const proto = hdrs.get('x-forwarded-proto') || 'http';
return `${proto}://${host}`;
}

export async function GET() {
if (!GITHUB_CLIENT_ID) {
return NextResponse.json(
Expand All @@ -17,16 +11,5 @@ export async function GET() {
);
}

const hdrs = await headers();
const baseUrl = getBaseUrl(hdrs);

const params = new URLSearchParams({
client_id: GITHUB_CLIENT_ID,
scope: 'read:user user:email',
redirect_uri: `${baseUrl}/api/auth/callback`,
});

return NextResponse.redirect(
`https://github.com/login/oauth/authorize?${params.toString()}`
);
return NextResponse.redirect(buildGitHubAuthorizationUrl(GITHUB_CLIENT_ID));
}
6 changes: 6 additions & 0 deletions lib/github-oauth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export function buildGitHubAuthorizationUrl(clientId) {
const url = new URL('https://github.com/login/oauth/authorize');
url.searchParams.set('client_id', clientId);
url.searchParams.set('scope', 'read:user user:email');
return url.toString();
}
13 changes: 13 additions & 0 deletions tests/github-oauth.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { buildGitHubAuthorizationUrl } from '../lib/github-oauth.js';

test('uses the callback registered on the GitHub OAuth application', () => {
const url = new URL(buildGitHubAuthorizationUrl('client-id'));

assert.equal(url.origin, 'https://github.com');
assert.equal(url.pathname, '/login/oauth/authorize');
assert.equal(url.searchParams.get('client_id'), 'client-id');
assert.equal(url.searchParams.get('scope'), 'read:user user:email');
assert.equal(url.searchParams.has('redirect_uri'), false);
});