From b6a9715d6878696881355b8dfade120f81d818e9 Mon Sep 17 00:00:00 2001 From: Sylvain Marroufin Date: Fri, 2 Feb 2024 17:26:09 +0100 Subject: [PATCH] chore(auth): dynamic provider server route --- _nuxthub/server/api/auth/[...provider].get.ts | 22 +++++++++++++++++++ _nuxthub/server/utils/config.ts | 2 +- server/api/auth/github.get.ts | 6 ----- 3 files changed, 23 insertions(+), 7 deletions(-) create mode 100644 _nuxthub/server/api/auth/[...provider].get.ts delete mode 100644 server/api/auth/github.get.ts diff --git a/_nuxthub/server/api/auth/[...provider].get.ts b/_nuxthub/server/api/auth/[...provider].get.ts new file mode 100644 index 00000000..ebb97d78 --- /dev/null +++ b/_nuxthub/server/api/auth/[...provider].get.ts @@ -0,0 +1,22 @@ +type OAuthHandler = keyof typeof oauth + +export default eventHandler(async event => { + const { provider } = await getValidatedRouterParams(event, z.object({ + provider: z.string().min(1) + }).parse) + + const config = getConfig() + const oauthConfig = config.oauth?.[provider] + const handlerName = `${provider}EventHandler` + if (!Object.hasOwn(oauth, handlerName)) { + throw createError({ statusCode: 400, message: 'Could not resolve this provider.' }) + } + + return oauth[handlerName as OAuthHandler]({ + config: oauthConfig as any, + async onSuccess(event, { user }) { + await setUserSession(event, { user }) + return sendRedirect(event, '/todos') + } + })(event) +}) diff --git a/_nuxthub/server/utils/config.ts b/_nuxthub/server/utils/config.ts index 1fadc64c..a17e9fa6 100644 --- a/_nuxthub/server/utils/config.ts +++ b/_nuxthub/server/utils/config.ts @@ -24,7 +24,7 @@ export async function _fetchConfig() { return _config } -export function useConfig() { +export function getConfig() { if (!_config) { throw createError('Please run _fetchConfig() in order to use useConfig()') } diff --git a/server/api/auth/github.get.ts b/server/api/auth/github.get.ts deleted file mode 100644 index 44595f82..00000000 --- a/server/api/auth/github.get.ts +++ /dev/null @@ -1,6 +0,0 @@ -export default oauth.githubEventHandler({ - async onSuccess(event, { user }) { - await setUserSession(event, { user }) - return sendRedirect(event, '/todos') - } -})