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'
3
5
import { LRUCache } from 'lru-cache'
4
6
import { log } from '../logging'
5
7
import { UserSymbol } from '../constants'
@@ -23,7 +25,7 @@ const appCache = new LRUCache<string, FirebaseApp>({
23
25
/**
24
26
* Initializes the app and provides it to others.
25
27
*/
26
- export default defineNuxtPlugin ( ( nuxtApp ) => {
28
+ export default defineNuxtPlugin ( async ( nuxtApp ) => {
27
29
const appConfig = useAppConfig ( )
28
30
29
31
const user = nuxtApp [
@@ -32,22 +34,36 @@ export default defineNuxtPlugin((nuxtApp) => {
32
34
] as User | undefined | null
33
35
const uid = user ?. uid
34
36
35
- let firebaseApp : FirebaseApp
37
+ let firebaseApp : FirebaseApp | undefined
36
38
37
39
// log('debug', 'initializing app with', appConfig.firebaseConfig)
38
40
if ( uid ) {
39
- if ( ! appCache . has ( uid ) ) {
41
+ firebaseApp = appCache . get ( uid )
42
+ if ( ! firebaseApp ) {
40
43
const randomId = Math . random ( ) . toString ( 36 ) . slice ( 2 )
44
+ // TODO: do we need a randomId?
41
45
const appName = `auth:${ user . uid } :${ randomId } `
42
46
43
- // log('debug ', '✅ creating new app', appName)
47
+ log ( 'log ' , '👤 creating new app' , appName )
44
48
45
49
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)
46
63
}
47
- firebaseApp = appCache . get ( uid ) !
48
64
} else {
49
65
// anonymous session, just create a new app
50
- // log('debug ', 'anonymous session')
66
+ // log('log ', '🥸 anonymous session')
51
67
firebaseApp = initializeApp ( appConfig . firebaseConfig )
52
68
}
53
69
0 commit comments