diff --git a/src/module.ts b/src/module.ts index bf7c1ead..74638abd 100644 --- a/src/module.ts +++ b/src/module.ts @@ -1,5 +1,5 @@ import { writeFile, readFile } from 'node:fs/promises' -import { defineNuxtModule, addPlugin, createResolver, addImportsDir, addServerHandler } from '@nuxt/kit' +import { defineNuxtModule, addPlugin, createResolver, addImportsDir, addServerHandler, addServerPlugin } from '@nuxt/kit' import { join } from 'pathe' import { defu } from 'defu' import { randomUUID } from 'uncrypto' @@ -45,6 +45,7 @@ export default defineNuxtModule({ ], }) } + addServerPlugin(resolver.resolve('./runtime/server/plugins/oauth')) // Waiting for https://github.com/nuxt/nuxt/pull/24000/files // addServerImportsDir(resolver.resolve('./runtime/server/utils')) addServerHandler({ diff --git a/src/runtime/server/lib/oauth/facebook.ts b/src/runtime/server/lib/oauth/facebook.ts index 6329d7a7..9dbf72fe 100644 --- a/src/runtime/server/lib/oauth/facebook.ts +++ b/src/runtime/server/lib/oauth/facebook.ts @@ -31,6 +31,14 @@ export interface OAuthFacebookConfig { */ scope?: string[] + /** + * Facebook OAuth User Fields + * @default [ 'id', 'name'], + * @see https://developers.facebook.com/docs/graph-api/guides/field-expansion + * @example [ 'id', 'name', 'email' ], + */ + fields?: string[] + /** * Facebook OAuth Authorization URL * @default 'https://www.facebook.com/v19.0/dialog/oauth' @@ -121,9 +129,12 @@ export function facebookEventHandler({ const accessToken = tokens.access_token // TODO: improve typing - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const user: any = await ofetch( - `https://graph.facebook.com/v19.0/me?fields=id,name&access_token=${accessToken}`, + + config.fields = config.fields || ['id', 'name'] + const fields = config.fields.join(',') + + const user = await ofetch( + `https://graph.facebook.com/v19.0/me?fields=${fields}&access_token=${accessToken}`, ) if (!user) { diff --git a/src/runtime/server/plugins/oauth.ts b/src/runtime/server/plugins/oauth.ts new file mode 100644 index 00000000..3f6cedf5 --- /dev/null +++ b/src/runtime/server/plugins/oauth.ts @@ -0,0 +1,23 @@ +import type { NitroApp } from 'nitropack' +import { defineNitroPlugin } from 'nitropack/runtime' + +export default defineNitroPlugin((nitroApp: NitroApp) => { + if (process.env.NUXT_OAUTH_FACEBOOK_CLIENT_ID && process.env.NUXT_OAUTH_FACEBOOK_CLIENT_SECRET) { + // In facebook login, the url is redirected to /#_=_ which is not a valid route + // so we remove it from the url, we are loading this long before the app is loaded + // by using render:html hook + // this is a hack, but it works + // https://stackoverflow.com/questions/7131909/facebook-callback-appends-to-return-url + nitroApp.hooks.hook('render:html', (html) => { + html.head.unshift(` + + `) + }) + } +})