|
| 1 | +import type { H3Event, H3Error } from 'h3' |
| 2 | +import { eventHandler, createError, getQuery, getRequestURL, sendRedirect } from 'h3' |
| 3 | +import { withQuery, parsePath } from 'ufo' |
| 4 | +import { ofetch } from 'ofetch' |
| 5 | +import { defu } from 'defu' |
| 6 | +import { useRuntimeConfig } from '#imports' |
| 7 | + |
| 8 | +export interface OAuthAuth0Config { |
| 9 | + /** |
| 10 | + * Auth0 OAuth Client ID |
| 11 | + * @default process.env.NUXT_OAUTH_AUTH0_CLIENT_ID |
| 12 | + */ |
| 13 | + clientId?: string |
| 14 | + /** |
| 15 | + * Auth0 OAuth Client Secret |
| 16 | + * @default process.env.NUXT_OAUTH_AUTH0_CLIENT_SECRET |
| 17 | + */ |
| 18 | + clientSecret?: string |
| 19 | + /** |
| 20 | + * Auth0 OAuth Issuer |
| 21 | + * @default process.env.NUXT_OAUTH_AUTH0_DOMAIN |
| 22 | + */ |
| 23 | + domain?: string |
| 24 | + /** |
| 25 | + * Auth0 OAuth Audience |
| 26 | + * @default process.env.NUXT_OAUTH_AUTH0_AUDIENCE |
| 27 | + */ |
| 28 | + audience?: string |
| 29 | + /** |
| 30 | + * Auth0 OAuth Scope |
| 31 | + * @default [] |
| 32 | + * @see https://auth0.com/docs/get-started/apis/scopes/openid-connect-scopes |
| 33 | + * @example ['openid'] |
| 34 | + */ |
| 35 | + scope?: string[] |
| 36 | + /** |
| 37 | + * Require email from user, adds the ['email'] scope if not present |
| 38 | + * @default false |
| 39 | + */ |
| 40 | + emailRequired?: boolean |
| 41 | +} |
| 42 | + |
| 43 | +interface OAuthConfig { |
| 44 | + config?: OAuthAuth0Config |
| 45 | + onSuccess: (event: H3Event, result: { user: any, tokens: any }) => Promise<void> | void |
| 46 | + onError?: (event: H3Event, error: H3Error) => Promise<void> | void |
| 47 | +} |
| 48 | + |
| 49 | +export function auth0EventHandler({ config, onSuccess, onError }: OAuthConfig) { |
| 50 | + return eventHandler(async (event: H3Event) => { |
| 51 | + // @ts-ignore |
| 52 | + config = defu(config, useRuntimeConfig(event).oauth?.auth0) as OAuthAuth0Config |
| 53 | + const { code } = getQuery(event) |
| 54 | + |
| 55 | + if (!config.clientId || !config.clientSecret || !config.domain) { |
| 56 | + const error = createError({ |
| 57 | + statusCode: 500, |
| 58 | + message: 'Missing NUXT_OAUTH_AUTH0_CLIENT_ID or NUXT_OAUTH_AUTH0_CLIENT_SECRET or NUXT_OAUTH_AUTH0_DOMAIN env variables.' |
| 59 | + }) |
| 60 | + if (!onError) throw error |
| 61 | + return onError(event, error) |
| 62 | + } |
| 63 | + const authorizationURL = `https://${config.domain}/authorize` |
| 64 | + const tokenURL = `https://${config.domain}/oauth/token` |
| 65 | + |
| 66 | + const redirectUrl = getRequestURL(event).href |
| 67 | + if (!code) { |
| 68 | + config.scope = config.scope || ['openid', 'offline_access'] |
| 69 | + if (config.emailRequired && !config.scope.includes('email')) { |
| 70 | + config.scope.push('email') |
| 71 | + } |
| 72 | + // Redirect to Auth0 Oauth page |
| 73 | + return sendRedirect( |
| 74 | + event, |
| 75 | + withQuery(authorizationURL as string, { |
| 76 | + response_type: 'code', |
| 77 | + client_id: config.clientId, |
| 78 | + redirect_uri: redirectUrl, |
| 79 | + scope: config.scope.join(' '), |
| 80 | + audience: config.audience || '', |
| 81 | + }) |
| 82 | + ) |
| 83 | + } |
| 84 | + |
| 85 | + const tokens: any = await ofetch( |
| 86 | + tokenURL as string, |
| 87 | + { |
| 88 | + method: 'POST', |
| 89 | + headers: { |
| 90 | + 'Content-Type': 'application/json' |
| 91 | + }, |
| 92 | + body: { |
| 93 | + grant_type: 'authorization_code', |
| 94 | + client_id: config.clientId, |
| 95 | + client_secret: config.clientSecret, |
| 96 | + redirect_uri: parsePath(redirectUrl).pathname, |
| 97 | + code, |
| 98 | + } |
| 99 | + } |
| 100 | + ).catch(error => { |
| 101 | + return { error } |
| 102 | + }) |
| 103 | + if (tokens.error) { |
| 104 | + const error = createError({ |
| 105 | + statusCode: 401, |
| 106 | + message: `Auth0 login failed: ${tokens.error?.data?.error_description || 'Unknown error'}`, |
| 107 | + data: tokens |
| 108 | + }) |
| 109 | + if (!onError) throw error |
| 110 | + return onError(event, error) |
| 111 | + } |
| 112 | + |
| 113 | + const tokenType = tokens.token_type |
| 114 | + const accessToken = tokens.access_token |
| 115 | + const user: any = await ofetch(`https://${config.domain}/userinfo`, { |
| 116 | + headers: { |
| 117 | + Authorization: `${tokenType} ${accessToken}` |
| 118 | + } |
| 119 | + }) |
| 120 | + |
| 121 | + return onSuccess(event, { |
| 122 | + tokens, |
| 123 | + user |
| 124 | + }) |
| 125 | + }) |
| 126 | +} |
0 commit comments