generateNewApiKey

This commit is contained in:
mantikoros 2022-08-26 11:54:13 -05:00
parent 050c80609b
commit 6b05561517
3 changed files with 19 additions and 12 deletions

View File

@ -1,6 +1,7 @@
import { User } from 'common/user'
import dayjs from 'dayjs'
import { useEffect } from 'react'
import { generateNewApiKey } from 'web/lib/api/api-key'
import { getUserAndPrivateUser } from 'web/lib/firebase/users'
import { initLinkTwitchAccount } from 'web/lib/twitch/link-twitch-account'
@ -29,11 +30,14 @@ export const handleRedirectAfterSignup = async (user: User | null) => {
if (redirect === 'twitch') {
const { privateUser } = await getUserAndPrivateUser(user.id)
if (!privateUser.apiKey) return // TODO: handle missing API key
const apiKey = privateUser.apiKey ?? (await generateNewApiKey(user.id))
if (!apiKey) return
try {
const [twitchAuthURL, linkSuccessPromise] = await initLinkTwitchAccount(
privateUser.id,
privateUser.apiKey
apiKey
)
window.open(twitchAuthURL) // TODO: Handle browser pop-up block
const data = await linkSuccessPromise // TODO: Do something with result?

9
web/lib/api/api-key.ts Normal file
View File

@ -0,0 +1,9 @@
import { updatePrivateUser } from '../firebase/users'
export const generateNewApiKey = async (userId: string) => {
const newApiKey = crypto.randomUUID()
return await updatePrivateUser(userId, { apiKey: newApiKey })
.then(() => newApiKey)
.catch(() => undefined)
}

View File

@ -12,16 +12,13 @@ import { uploadImage } from 'web/lib/firebase/storage'
import { Col } from 'web/components/layout/col'
import { Row } from 'web/components/layout/row'
import { User, PrivateUser } from 'common/user'
import {
getUserAndPrivateUser,
updateUser,
updatePrivateUser,
} from 'web/lib/firebase/users'
import { getUserAndPrivateUser, updateUser } from 'web/lib/firebase/users'
import { defaultBannerUrl } from 'web/components/user-page'
import { SiteLink } from 'web/components/site-link'
import Textarea from 'react-expanding-textarea'
import { redirectIfLoggedOut } from 'web/lib/firebase/server-auth'
import { TwitchPanel } from 'web/components/twitch-panel'
import { generateNewApiKey } from 'web/lib/api/api-key'
export const getServerSideProps = redirectIfLoggedOut('/', async (_, creds) => {
return { props: { auth: await getUserAndPrivateUser(creds.user.uid) } }
@ -97,11 +94,8 @@ export default function ProfilePage(props: {
}
const updateApiKey = async (e: React.MouseEvent) => {
const newApiKey = crypto.randomUUID()
setApiKey(newApiKey)
await updatePrivateUser(user.id, { apiKey: newApiKey }).catch(() => {
setApiKey(privateUser.apiKey || '')
})
const newApiKey = await generateNewApiKey(user.id)
setApiKey(newApiKey ?? '')
e.preventDefault()
}