|
| 1 | +import { getEnvVariable } from "@stackframe/stack-shared/dist/utils/env"; |
| 2 | +import { OAuthUserInfo, validateUserInfo } from "../utils"; |
| 3 | +import { OAuthBaseProvider, TokenSet } from "./base"; |
| 4 | + |
| 5 | +export class TwitchProvider extends OAuthBaseProvider { |
| 6 | + private constructor( |
| 7 | + ...args: ConstructorParameters<typeof OAuthBaseProvider> |
| 8 | + ) { |
| 9 | + super(...args); |
| 10 | + } |
| 11 | + |
| 12 | + static async create(options: { |
| 13 | + clientId: string, |
| 14 | + clientSecret: string, |
| 15 | + }) { |
| 16 | + return new TwitchProvider(...await OAuthBaseProvider.createConstructorArgs({ |
| 17 | + issuer: "https://id.twitch.tv", |
| 18 | + authorizationEndpoint: "https://id.twitch.tv/oauth2/authorize", |
| 19 | + tokenEndpoint: "https://id.twitch.tv/oauth2/token", |
| 20 | + tokenEndpointAuthMethod: "client_secret_post", |
| 21 | + redirectUri: getEnvVariable("NEXT_PUBLIC_STACK_API_URL") + "/api/v1/auth/oauth/callback/twitch", |
| 22 | + baseScope: "user:read:email", |
| 23 | + ...options, |
| 24 | + })); |
| 25 | + } |
| 26 | + |
| 27 | + async postProcessUserInfo(tokenSet: TokenSet): Promise<OAuthUserInfo> { |
| 28 | + const info = await fetch("https://api.twitch.tv/helix/users", { |
| 29 | + headers: { |
| 30 | + Authorization: `Bearer ${tokenSet.accessToken}`, |
| 31 | + "Client-Id": this.oauthClient.client_id as string, |
| 32 | + }, |
| 33 | + }).then((res) => res.json()); |
| 34 | + |
| 35 | + |
| 36 | + const userInfo = info.data?.[0]; |
| 37 | + |
| 38 | + return validateUserInfo({ |
| 39 | + accountId: userInfo.id, |
| 40 | + displayName: userInfo.display_name, |
| 41 | + email: userInfo.email, |
| 42 | + profileImageUrl: userInfo.profile_image_url, |
| 43 | + emailVerified: true, |
| 44 | + }); |
| 45 | + } |
| 46 | + |
| 47 | + async checkAccessTokenValidity(accessToken: string): Promise<boolean> { |
| 48 | + const info = await fetch("https://api.twitch.tv/helix/users", { |
| 49 | + headers: { |
| 50 | + Authorization: `Bearer ${accessToken}`, |
| 51 | + "Client-Id": this.oauthClient.client_id as string, |
| 52 | + }, |
| 53 | + }).then((res) => res.json()); |
| 54 | + return info.data?.[0] !== undefined; |
| 55 | + } |
| 56 | +} |
0 commit comments