|
| 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 OAuthTwitchConfig { |
| 9 | + /** |
| 10 | + * Twitch Client ID |
| 11 | + * @default process.env.NUXT_OAUTH_TWITCH_CLIENT_ID |
| 12 | + */ |
| 13 | + clientId?: string |
| 14 | + |
| 15 | + /** |
| 16 | + * Twitch OAuth Client Secret |
| 17 | + * @default process.env.NUXT_OAUTH_TWITCH_CLIENT_SECRET |
| 18 | + */ |
| 19 | + clientSecret?: string |
| 20 | + |
| 21 | + /** |
| 22 | + * Twitch OAuth Scope |
| 23 | + * @default [] |
| 24 | + * @see https://dev.twitch.tv/docs/authentication/scopes |
| 25 | + * @example ['user:read:email'] |
| 26 | + */ |
| 27 | + scope?: string[] |
| 28 | + |
| 29 | + /** |
| 30 | + * Require email from user, adds the ['user:read:email'] scope if not present |
| 31 | + * @default false |
| 32 | + */ |
| 33 | + emailRequired?: boolean |
| 34 | + |
| 35 | + /** |
| 36 | + * Twitch OAuth Authorization URL |
| 37 | + * @default 'https://id.twitch.tv/oauth2/authorize' |
| 38 | + */ |
| 39 | + authorizationURL?: string |
| 40 | + |
| 41 | + /** |
| 42 | + * Twitch OAuth Token URL |
| 43 | + * @default 'https://id.twitch.tv/oauth2/token' |
| 44 | + */ |
| 45 | + tokenURL?: string |
| 46 | +} |
| 47 | + |
| 48 | +interface OAuthConfig { |
| 49 | + config?: OAuthTwitchConfig |
| 50 | + onSuccess: (event: H3Event, result: { user: any, tokens: any }) => Promise<void> | void |
| 51 | + onError?: (event: H3Event, error: H3Error) => Promise<void> | void |
| 52 | +} |
| 53 | + |
| 54 | +export function twitchEventHandler({ config, onSuccess, onError }: OAuthConfig) { |
| 55 | + return eventHandler(async (event: H3Event) => { |
| 56 | + // @ts-ignore |
| 57 | + config = defu(config, useRuntimeConfig(event).oauth?.twitch, { |
| 58 | + authorizationURL: 'https://id.twitch.tv/oauth2/authorize', |
| 59 | + tokenURL: 'https://id.twitch.tv/oauth2/token' |
| 60 | + }) as OAuthTwitchConfig |
| 61 | + const { code } = getQuery(event) |
| 62 | + |
| 63 | + if (!config.clientId) { |
| 64 | + const error = createError({ |
| 65 | + statusCode: 500, |
| 66 | + message: 'Missing NUXT_OAUTH_TWITCH_CLIENT_ID env variables.' |
| 67 | + }) |
| 68 | + if (!onError) throw error |
| 69 | + return onError(event, error) |
| 70 | + } |
| 71 | + |
| 72 | + const redirectUrl = getRequestURL(event).href |
| 73 | + if (!code) { |
| 74 | + config.scope = config.scope || [] |
| 75 | + if (config.emailRequired && !config.scope.includes('user:read:email')) { |
| 76 | + config.scope.push('user:read:email') |
| 77 | + } |
| 78 | + // Redirect to Twitch Oauth page |
| 79 | + return sendRedirect( |
| 80 | + event, |
| 81 | + withQuery(config.authorizationURL as string, { |
| 82 | + response_type: 'code', |
| 83 | + client_id: config.clientId, |
| 84 | + redirect_uri: redirectUrl, |
| 85 | + scope: config.scope.join('%20') |
| 86 | + }) |
| 87 | + ) |
| 88 | + } |
| 89 | + |
| 90 | + const tokens: any = await ofetch( |
| 91 | + config.tokenURL as string, |
| 92 | + { |
| 93 | + method: 'POST', |
| 94 | + headers: { |
| 95 | + 'Content-Type': 'application/x-www-form-urlencoded' |
| 96 | + }, |
| 97 | + params: { |
| 98 | + grant_type: 'authorization_code', |
| 99 | + redirect_uri: parsePath(redirectUrl).pathname, |
| 100 | + client_id: config.clientId, |
| 101 | + client_secret: config.clientSecret, |
| 102 | + code |
| 103 | + } |
| 104 | + } |
| 105 | + ).catch(error => { |
| 106 | + return { error } |
| 107 | + }) |
| 108 | + if (tokens.error) { |
| 109 | + const error = createError({ |
| 110 | + statusCode: 401, |
| 111 | + message: `Twitch login failed: ${tokens.error?.data?.error_description || 'Unknown error'}`, |
| 112 | + data: tokens |
| 113 | + }) |
| 114 | + if (!onError) throw error |
| 115 | + return onError(event, error) |
| 116 | + } |
| 117 | + |
| 118 | + const accessToken = tokens.access_token |
| 119 | + const users: any = await ofetch('https://api.twitch.tv/helix/users', { |
| 120 | + headers: { |
| 121 | + 'Client-ID': config.clientId, |
| 122 | + Authorization: `Bearer ${accessToken}` |
| 123 | + } |
| 124 | + }) |
| 125 | + |
| 126 | + const user = users.data?.[0] |
| 127 | + |
| 128 | + if (!user) { |
| 129 | + const error = createError({ |
| 130 | + statusCode: 500, |
| 131 | + message: 'Could not get Twitch user', |
| 132 | + data: tokens |
| 133 | + }) |
| 134 | + if (!onError) throw error |
| 135 | + return onError(event, error) |
| 136 | + } |
| 137 | + |
| 138 | + return onSuccess(event, { |
| 139 | + tokens, |
| 140 | + user |
| 141 | + }) |
| 142 | + }) |
| 143 | +} |
0 commit comments