1- import { deleteApp , FirebaseApp , initializeApp } from 'firebase/app'
2- import type { User } from 'firebase/auth'
1+ import { deleteApp , type FirebaseApp , initializeApp } from 'firebase/app'
2+ import { getAuth , signInWithCustomToken , type User } from 'firebase/auth'
3+ import { type App as AdminApp } from 'firebase-admin/app'
4+ import { getAuth as getAdminAuth } from 'firebase-admin/auth'
35import { LRUCache } from 'lru-cache'
46import { log } from '../logging'
57import { UserSymbol } from '../constants'
@@ -23,7 +25,7 @@ const appCache = new LRUCache<string, FirebaseApp>({
2325/**
2426 * Initializes the app and provides it to others.
2527 */
26- export default defineNuxtPlugin ( ( nuxtApp ) => {
28+ export default defineNuxtPlugin ( async ( nuxtApp ) => {
2729 const appConfig = useAppConfig ( )
2830
2931 const user = nuxtApp [
@@ -32,22 +34,36 @@ export default defineNuxtPlugin((nuxtApp) => {
3234 ] as User | undefined | null
3335 const uid = user ?. uid
3436
35- let firebaseApp : FirebaseApp
37+ let firebaseApp : FirebaseApp | undefined
3638
3739 // log('debug', 'initializing app with', appConfig.firebaseConfig)
3840 if ( uid ) {
39- if ( ! appCache . has ( uid ) ) {
41+ firebaseApp = appCache . get ( uid )
42+ if ( ! firebaseApp ) {
4043 const randomId = Math . random ( ) . toString ( 36 ) . slice ( 2 )
44+ // TODO: do we need a randomId?
4145 const appName = `auth:${ user . uid } :${ randomId } `
4246
43- // log('debug ', '✅ creating new app', appName)
47+ log ( 'log ' , '👤 creating new app' , appName )
4448
4549 appCache . set ( uid , initializeApp ( appConfig . firebaseConfig , appName ) )
50+ firebaseApp = appCache . get ( uid ) !
51+ const firebaseAdminApp = nuxtApp . $firebaseAdminApp as AdminApp
52+ const adminAuth = getAdminAuth ( firebaseAdminApp )
53+ // console.time('token')
54+ const customToken = await adminAuth . createCustomToken ( user . uid )
55+ // console.timeLog('token', `got token for ${user.uid}`)
56+ const credentials = await signInWithCustomToken (
57+ getAuth ( firebaseApp ) ,
58+ customToken
59+ )
60+ // console.timeLog('token', `signed in with token for ${user.uid}`)
61+ // console.timeEnd('token')
62+ // TODO: token expiration (1h)
4663 }
47- firebaseApp = appCache . get ( uid ) !
4864 } else {
4965 // anonymous session, just create a new app
50- // log('debug ', 'anonymous session')
66+ // log('log ', '🥸 anonymous session')
5167 firebaseApp = initializeApp ( appConfig . firebaseConfig )
5268 }
5369
0 commit comments