Get email with github token (#505)

* Get email with github token

* Changeset added
pull/506/head
Carlos Sanjines Aldazosa 2024-05-06 16:38:37 -04:00 committed by GitHub
parent 9495f5ddab
commit 42e75f07dc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 26 additions and 19 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/oauth-providers': minor
---
Requesting github for user email with token

View File

@ -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() { async getUserData() {
if (!this.token?.token) { if (!this.token?.token) {
await this.getTokenFromCode() await this.getTokenFromCode()
@ -112,25 +132,7 @@ export class AuthFlow {
throw new HTTPException(400, { message: response.message }) throw new HTTPException(400, { message: response.message })
} }
if (!this.oauthApp) { response.email = await this.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
}
response.email = email as string
}
if ('id' in response) { if ('id' in response) {
this.user = response this.user = response