Skip to content

Commit

Permalink
fetch email when is not public
Browse files Browse the repository at this point in the history
  • Loading branch information
thormengkheang committed Mar 14, 2024
1 parent 64cbe6b commit 10ba4a9
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions src/app/login/github/callback/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export async function GET(request: Request): Promise<Response> {
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) {
Expand All @@ -19,14 +20,25 @@ export async function GET(request: Request): Promise<Response> {
}

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) =>
Expand Down Expand Up @@ -108,5 +120,12 @@ export async function GET(request: Request): Promise<Response> {
interface GitHubUser {
id: string;
login: string;
email: string | null;
}

interface GitHubEmail {
email: string;
primary: boolean;
verified: boolean;
visibility: "public" | "private";
}

0 comments on commit 10ba4a9

Please sign in to comment.