diff --git a/src/app/login/github/callback/route.ts b/src/app/login/github/callback/route.ts index 1adc0306..699796cf 100644 --- a/src/app/login/github/callback/route.ts +++ b/src/app/login/github/callback/route.ts @@ -10,6 +10,7 @@ export async function GET(request: Request): Promise { const code = url.searchParams.get("code"); const state = url.searchParams.get("state"); const headerStore = headers(); + const GITHUB_API_URL = "https://api.github.com"; const storedState = cookies().get("github_oauth_state")?.value ?? null; if (!code || !state || !storedState || state !== storedState) { @@ -19,14 +20,25 @@ export async function GET(request: Request): Promise { } try { - const tokens = await github.validateAuthorizationCode(code); - const githubUserResponse = await fetch("https://api.github.com/user", { + const token = await github.validateAuthorizationCode(code); + const githubUserResponse = await fetch(`${GITHUB_API_URL}/user`, { headers: { - Authorization: `Bearer ${tokens.accessToken}`, + Authorization: `Bearer ${token.accessToken}`, }, }); const githubUser: GitHubUser = await githubUserResponse.json(); + if (githubUser.email === null) { + const resp = await fetch(`${GITHUB_API_URL}/user/emails`, { + headers: { + Authorization: `Bearer ${token.accessToken}`, + }, + }); + const githubEmails: GitHubEmail[] = await resp.json(); + githubUser.email = + githubEmails.find((email) => email.primary)?.email || null; + } + // Replace this with your own DB client. const existingUser = await db.query.user_oauth.findFirst({ where: (field, op) => @@ -108,5 +120,12 @@ export async function GET(request: Request): Promise { interface GitHubUser { id: string; login: string; + email: string | null; +} + +interface GitHubEmail { email: string; + primary: boolean; + verified: boolean; + visibility: "public" | "private"; }