|
| 1 | +import type { H3Event, H3Error } from 'h3' |
| 2 | +import { eventHandler, createError, getQuery, getRequestURL, sendRedirect } from 'h3' |
| 3 | +import { withQuery, parseURL, stringifyParsedURL } from 'ufo' |
| 4 | +import { ofetch } from 'ofetch' |
| 5 | +import { defu } from 'defu' |
| 6 | +import { useRuntimeConfig } from '#imports' |
| 7 | + |
| 8 | +export interface OAuthDiscordConfig { |
| 9 | + /** |
| 10 | + * Discord OAuth Client ID |
| 11 | + * @default process.env.NUXT_OAUTH_DISCORD_CLIENT_ID |
| 12 | + */ |
| 13 | + clientId?: string |
| 14 | + /** |
| 15 | + * Discord OAuth Client Secret |
| 16 | + * @default process.env.NUXT_OAUTH_DISCORD_CLIENT_SECRET |
| 17 | + */ |
| 18 | + clientSecret?: string |
| 19 | + /** |
| 20 | + * Discord OAuth Scope |
| 21 | + * @default [] |
| 22 | + * @see https://discord.com/developers/docs/topics/oauth2#shared-resources-oauth2-scopes |
| 23 | + * @example ['identify', 'email'] |
| 24 | + * Without the identify scope the user will not be returned. |
| 25 | + */ |
| 26 | + scope?: string[] |
| 27 | + /** |
| 28 | + * Require email from user, adds the ['email'] scope if not present. |
| 29 | + * @default false |
| 30 | + */ |
| 31 | + emailRequired?: boolean, |
| 32 | + /** |
| 33 | + * Require profile from user, adds the ['identify'] scope if not present. |
| 34 | + * @default true |
| 35 | + */ |
| 36 | + profileRequired?: boolean |
| 37 | + /** |
| 38 | + * Discord OAuth Authorization URL |
| 39 | + * @default 'https://discord.com/oauth2/authorize' |
| 40 | + */ |
| 41 | + authorizationURL?: string |
| 42 | + /** |
| 43 | + * Discord OAuth Token URL |
| 44 | + * @default 'https://discord.com/api/oauth2/token' |
| 45 | + */ |
| 46 | + tokenURL?: string |
| 47 | +} |
| 48 | + |
| 49 | +interface OAuthConfig { |
| 50 | + config?: OAuthDiscordConfig |
| 51 | + onSuccess: (event: H3Event, result: { user: any, tokens: any }) => Promise<void> | void |
| 52 | + onError?: (event: H3Event, error: H3Error) => Promise<void> | void |
| 53 | +} |
| 54 | + |
| 55 | +export function discordEventHandler({ config, onSuccess, onError }: OAuthConfig) { |
| 56 | + return eventHandler(async (event: H3Event) => { |
| 57 | + // @ts-ignore |
| 58 | + config = defu(config, useRuntimeConfig(event).oauth?.discord, { |
| 59 | + authorizationURL: 'https://discord.com/oauth2/authorize', |
| 60 | + tokenURL: 'https://discord.com/api/oauth2/token', |
| 61 | + profileRequired: true |
| 62 | + }) as OAuthDiscordConfig |
| 63 | + const { code } = getQuery(event) |
| 64 | + |
| 65 | + if (!config.clientId || !config.clientSecret) { |
| 66 | + const error = createError({ |
| 67 | + statusCode: 500, |
| 68 | + message: 'Missing NUXT_OAUTH_DISCORD_CLIENT_ID or NUXT_OAUTH_DISCORD_CLIENT_SECRET env variables.' |
| 69 | + }) |
| 70 | + if (!onError) throw error |
| 71 | + return onError(event, error) |
| 72 | + } |
| 73 | + |
| 74 | + const redirectUrl = getRequestURL(event).href |
| 75 | + if (!code) { |
| 76 | + config.scope = config.scope || [] |
| 77 | + if (config.emailRequired && !config.scope.includes('email')) { |
| 78 | + config.scope.push('email') |
| 79 | + } |
| 80 | + if (config.profileRequired && !config.scope.includes('identify')) { |
| 81 | + config.scope.push('identify') |
| 82 | + } |
| 83 | + |
| 84 | + // Redirect to Discord Oauth page |
| 85 | + return sendRedirect( |
| 86 | + event, |
| 87 | + withQuery(config.authorizationURL as string, { |
| 88 | + response_type: 'code', |
| 89 | + client_id: config.clientId, |
| 90 | + redirect_uri: redirectUrl, |
| 91 | + scope: config.scope.join(' ') |
| 92 | + }) |
| 93 | + ) |
| 94 | + } |
| 95 | + |
| 96 | + const parsedRedirectUrl = parseURL(redirectUrl) |
| 97 | + parsedRedirectUrl.search = '' |
| 98 | + const tokens: any = await ofetch( |
| 99 | + config.tokenURL as string, |
| 100 | + { |
| 101 | + method: 'POST', |
| 102 | + headers: { |
| 103 | + 'Content-Type': 'application/x-www-form-urlencoded' |
| 104 | + }, |
| 105 | + body: new URLSearchParams({ |
| 106 | + client_id: config.clientId, |
| 107 | + client_secret: config.clientSecret, |
| 108 | + grant_type: 'authorization_code', |
| 109 | + redirect_uri: stringifyParsedURL(parsedRedirectUrl), |
| 110 | + code: code as string, |
| 111 | + }).toString() |
| 112 | + } |
| 113 | + ).catch(error => { |
| 114 | + return { error } |
| 115 | + }) |
| 116 | + if (tokens.error) { |
| 117 | + console.log(tokens) |
| 118 | + const error = createError({ |
| 119 | + statusCode: 401, |
| 120 | + message: `Discord login failed: ${tokens.error?.data?.error_description || 'Unknown error'}`, |
| 121 | + data: tokens |
| 122 | + }) |
| 123 | + |
| 124 | + if (!onError) throw error |
| 125 | + return onError(event, error) |
| 126 | + } |
| 127 | + |
| 128 | + const accessToken = tokens.access_token |
| 129 | + const user: any = await ofetch('https://discord.com/api/users/@me', { |
| 130 | + headers: { |
| 131 | + 'user-agent': 'Nuxt Auth Utils', |
| 132 | + Authorization: `Bearer ${accessToken}` |
| 133 | + } |
| 134 | + }) |
| 135 | + |
| 136 | + return onSuccess(event, { |
| 137 | + tokens, |
| 138 | + user |
| 139 | + }) |
| 140 | + }) |
| 141 | +} |
0 commit comments