From 42e75f07dc4eef9a1cd3d88062fc90edd6677aeb Mon Sep 17 00:00:00 2001 From: Carlos Sanjines Aldazosa Date: Mon, 6 May 2024 16:38:37 -0400 Subject: [PATCH] Get email with github token (#505) * Get email with github token * Changeset added --- .changeset/lazy-files-appear.md | 5 +++ .../src/providers/github/authFlow.ts | 40 ++++++++++--------- 2 files changed, 26 insertions(+), 19 deletions(-) create mode 100644 .changeset/lazy-files-appear.md diff --git a/.changeset/lazy-files-appear.md b/.changeset/lazy-files-appear.md new file mode 100644 index 000000000..587835624 --- /dev/null +++ b/.changeset/lazy-files-appear.md @@ -0,0 +1,5 @@ +--- +'@hono/oauth-providers': minor +--- + +Requesting github for user email with token diff --git a/packages/oauth-providers/src/providers/github/authFlow.ts b/packages/oauth-providers/src/providers/github/authFlow.ts index 1b15b495a..4344e1150 100644 --- a/packages/oauth-providers/src/providers/github/authFlow.ts +++ b/packages/oauth-providers/src/providers/github/authFlow.ts @@ -94,6 +94,26 @@ export class AuthFlow { } } + private async getEmail() { + const emails = (await fetch('https://api.github.com/user/emails', { + headers: { + Authorization: `Bearer ${this.token?.token}`, + 'User-Agent': userAgent, + }, + }).then((res) => res.json())) as GitHubEmailResponse[] | GitHubErrorResponse + + if ('message' in emails) { + throw new HTTPException(400, { message: emails.message }) + } + + let email = emails.find((emails) => emails.primary === true)?.email + if (email === undefined) { + email = emails.find((emails) => !emails.email.includes('@users.noreply.github.com'))?.email + } + + return email as string + } + async getUserData() { if (!this.token?.token) { await this.getTokenFromCode() @@ -112,25 +132,7 @@ export class AuthFlow { throw new HTTPException(400, { message: response.message }) } - if (!this.oauthApp) { - const emails = (await fetch('https://api.github.com/user/emails', { - headers: { - Authorization: `Bearer ${this.token?.token}`, - 'User-Agent': userAgent, - }, - }).then((res) => res.json())) as GitHubEmailResponse[] | GitHubErrorResponse - - if ('message' in emails) { - throw new HTTPException(400, { message: emails.message }) - } - - let email = emails.find((emails) => emails.primary === true)?.email - if (email === undefined) { - email = emails.find((emails) => !emails.email.includes('@users.noreply.github.com'))?.email - } - - response.email = email as string - } + response.email = await this.getEmail() if ('id' in response) { this.user = response