cg / hackerproducts

64 files · 5,803 lines · 161.0 KB — Next.js 15, React 19, TypeScript, PostgreSQL, Object Storage, plain CSS.

Quick jump: page.tsx / page.tsx / globals.css / schema.sql / package.json

root / src / app / api / auth / github / callback / route.ts

src/app/api/auth/github/callback/route.ts · 110 lines · 3.3 KB← back to folder
1import { cookies } from "next/headers";
2import { NextResponse } from "next/server";
3import { createSession, getSiteUrl, upsertOAuthUser } from "@/lib/auth";
4
5export async function GET(request: Request) {
6 const siteUrl = getSiteUrl();
7 const url = new URL(request.url);
8 const code = url.searchParams.get("code");
9 const state = url.searchParams.get("state");
10
11 const cookieStore = await cookies();
12 const rawStateCookie = cookieStore.get("hp_oauth_state")?.value;
13 cookieStore.delete("hp_oauth_state");
14
15 if (!code || !state || !rawStateCookie) {
16 return NextResponse.redirect(new URL("/login?error=oauth_failed", siteUrl));
17 }
18
19 let parsedState: { state: string; next: string };
20 try {
21 parsedState = JSON.parse(rawStateCookie);
22 } catch {
23 return NextResponse.redirect(new URL("/login?error=oauth_failed", siteUrl));
24 }
25
26 if (parsedState.state !== state) {
27 return NextResponse.redirect(new URL("/login?error=invalid_state", siteUrl));
28 }
29
30 const tokenRes = await fetch("https://github.com/login/oauth/access_token", {
31 method: "POST",
32 headers: {
33 Accept: "application/json",
34 "Content-Type": "application/json",
35 },
36 body: JSON.stringify({
37 client_id: process.env.GITHUB_CLIENT_ID,
38 client_secret: process.env.GITHUB_CLIENT_SECRET,
39 code,
40 redirect_uri: `${siteUrl}/api/auth/github/callback`,
41 }),
42 });
43
44 if (!tokenRes.ok) {
45 return NextResponse.redirect(new URL("/login?error=token_exchange_failed", siteUrl));
46 }
47
48 const tokenJson = (await tokenRes.json()) as { access_token?: string };
49 if (!tokenJson.access_token) {
50 return NextResponse.redirect(new URL("/login?error=token_missing", siteUrl));
51 }
52
53 const userRes = await fetch("https://api.github.com/user", {
54 headers: {
55 Authorization: `Bearer ${tokenJson.access_token}`,
56 Accept: "application/vnd.github+json",
57 "User-Agent": "hackerproducts",
58 },
59 });
60
61 if (!userRes.ok) {
62 return NextResponse.redirect(new URL("/login?error=profile_fetch_failed", siteUrl));
63 }
64
65 const ghUser = (await userRes.json()) as {
66 id: number;
67 login: string;
68 name: string | null;
69 email: string | null;
70 avatar_url: string | null;
71 bio: string | null;
72 blog: string | null;
73 };
74
75 let email = ghUser.email;
76 if (!email) {
77 const emailRes = await fetch("https://api.github.com/user/emails", {
78 headers: {
79 Authorization: `Bearer ${tokenJson.access_token}`,
80 Accept: "application/vnd.github+json",
81 "User-Agent": "hackerproducts",
82 },
83 });
84 if (emailRes.ok) {
85 const emails = (await emailRes.json()) as Array<{
86 email: string;
87 primary: boolean;
88 verified: boolean;
89 }>;
90 const primary = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified);
91 email = primary?.email ?? null;
92 }
93 }
94
95 const user = await upsertOAuthUser({
96 provider: "github",
97 providerAccountId: String(ghUser.id),
98 email,
99 name: ghUser.name,
100 preferredUsername: ghUser.login,
101 avatarUrl: ghUser.avatar_url,
102 bio: ghUser.bio,
103 websiteUrl: ghUser.blog,
104 });
105
106 await createSession(user.id);
107 const safeNext = parsedState.next.startsWith("/") && !parsedState.next.startsWith("//") ? parsedState.next : "/";
108 return NextResponse.redirect(new URL(safeNext, siteUrl));
109}
110
cg / hackerproducts — hacker products