manifold/web/lib/twitch/link-twitch-account.ts
mantikoros a2d61a1daa
Twitch integration (#815)
* twitch account linking; profile page twitch panel; twitch landing page

* fix import

* twitch logo

* save twitch credentials cloud function

* use user id instead of bot id, add manifold api endpoint

* properly add function to index

* Added support for new redirect Twitch auth.

* Added clean error handling in case of Twitch link fail.

* remove simulator

* Removed legacy non-redirect Twitch auth code. Added "add bot to channel" button in user profile and relevant data to user type.

* Removed unnecessary imports.

* Fixed line endings.

* Allow users to modify private user twitchInfo firestore object

* Local dev on savetwitchcredentials function

Co-authored-by: Phil <phil.bladen@gmail.com>
Co-authored-by: Marshall Polaris <marshall@pol.rs>
2022-09-14 01:52:31 -07:00

42 lines
1.3 KiB
TypeScript

import { PrivateUser, User } from 'common/user'
import { generateNewApiKey } from '../api/api-key'
const TWITCH_BOT_PUBLIC_URL = 'https://king-prawn-app-5btyw.ondigitalocean.app' // TODO: Add this to env config appropriately
export async function initLinkTwitchAccount(
manifoldUserID: string,
manifoldUserAPIKey: string
): Promise<[string, Promise<{ twitchName: string; controlToken: string }>]> {
const response = await fetch(`${TWITCH_BOT_PUBLIC_URL}/api/linkInit`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
manifoldID: manifoldUserID,
apiKey: manifoldUserAPIKey,
redirectURL: window.location.href,
}),
})
const responseData = await response.json()
if (!response.ok) {
throw new Error(responseData.message)
}
const responseFetch = fetch(
`${TWITCH_BOT_PUBLIC_URL}/api/linkResult?userID=${manifoldUserID}`
)
return [responseData.twitchAuthURL, responseFetch.then((r) => r.json())]
}
export async function linkTwitchAccountRedirect(
user: User,
privateUser: PrivateUser
) {
const apiKey = privateUser.apiKey ?? (await generateNewApiKey(user.id))
if (!apiKey) throw new Error("Couldn't retrieve or create Manifold api key")
const [twitchAuthURL] = await initLinkTwitchAccount(user.id, apiKey)
window.location.href = twitchAuthURL
}