manifold/web/hooks/use-redirect-after-signup.ts

46 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-08-23 17:37:02 +00:00
import { User } from 'common/user'
import dayjs from 'dayjs'
import { useEffect } from 'react'
2022-08-26 16:35:32 +00:00
import { getUserAndPrivateUser } from 'web/lib/firebase/users'
import { initLinkTwitchAccount } from 'web/lib/twitch/link-twitch-account'
2022-08-23 17:37:02 +00:00
import { safeLocalStorage } from 'web/lib/util/local'
type page_redirects = 'twitch'
const key = 'redirect-after-signup'
export const useRedirectAfterSignup = (page: page_redirects) => {
useEffect(() => {
safeLocalStorage()?.setItem(key, page)
}, [page])
}
2022-08-26 16:35:32 +00:00
export const handleRedirectAfterSignup = async (user: User | null) => {
2022-08-23 17:37:02 +00:00
const redirect = safeLocalStorage()?.getItem(key)
if (!user || !redirect) return
2022-08-26 16:35:32 +00:00
safeLocalStorage()?.removeItem(key)
2022-08-23 17:37:02 +00:00
const now = dayjs().utc()
const userCreatedTime = dayjs(user.createdTime)
if (now.diff(userCreatedTime, 'minute') > 5) return
if (redirect === 'twitch') {
2022-08-26 16:35:32 +00:00
const { privateUser } = await getUserAndPrivateUser(user.id)
if (!privateUser.apiKey) return // TODO: handle missing API key
try {
const [twitchAuthURL, linkSuccessPromise] = await initLinkTwitchAccount(
privateUser.id,
privateUser.apiKey
)
window.open(twitchAuthURL) // TODO: Handle browser pop-up block
const data = await linkSuccessPromise // TODO: Do something with result?
console.debug(`Successfully linked Twitch account '${data.twitchName}'`)
} catch (e) {
console.error(e)
}
2022-08-23 17:37:02 +00:00
}
}