|
| 1 | +import type { FirebaseApp } from '@firebase/app-types' |
| 2 | +import type { App as AdminApp } from 'firebase-admin/app' |
| 3 | +import { getAuth as getAdminAuth } from 'firebase-admin/auth' |
| 4 | +import { getAuth, onIdTokenChanged, signInWithCredential, AuthCredential } from 'firebase/auth' |
| 5 | +import { getCurrentUser, VueFireAuth } from 'vuefire' |
| 6 | +import { getCookie } from 'h3' |
| 7 | +import { AUTH_COOKIE_NAME } from '../../auth/session' |
| 8 | +import { defineNuxtPlugin, useRequestEvent } from '#app' |
| 9 | + |
| 10 | +/** |
| 11 | + * Setups VueFireAuth and automatically mints a cookie based auth session. On the server, it reads the cookie to |
| 12 | + * generate the proper auth state. |
| 13 | + */ |
| 14 | +export default defineNuxtPlugin(async (nuxtApp) => { |
| 15 | + const firebaseApp = nuxtApp.$firebaseApp as FirebaseApp |
| 16 | + |
| 17 | + if (process.server) { |
| 18 | + const event = useRequestEvent() |
| 19 | + const token = getCookie(event, AUTH_COOKIE_NAME) |
| 20 | + |
| 21 | + if (token) { |
| 22 | + const firebaseApp = nuxtApp.$firebaseApp as FirebaseApp |
| 23 | + const adminApp = nuxtApp.$adminApp as AdminApp |
| 24 | + const auth = getAdminAuth(adminApp) |
| 25 | + |
| 26 | + const decodedToken = await auth.verifyIdToken(token) |
| 27 | + const user = await auth.getUser(decodedToken.uid) |
| 28 | + |
| 29 | + // signInWithCredential(getAuth(firebaseApp))) |
| 30 | + |
| 31 | + console.log('🔥 setting user', user) |
| 32 | + |
| 33 | + // provide user |
| 34 | + } |
| 35 | + } else { |
| 36 | + VueFireAuth()(firebaseApp, nuxtApp.vueApp) |
| 37 | + const auth = getAuth(firebaseApp) |
| 38 | + // send a post request to the server when auth state changes to mint a cookie |
| 39 | + onIdTokenChanged(auth, async (user) => { |
| 40 | + const jwtToken = await user?.getIdToken() |
| 41 | + // console.log('📚 updating server cookie with', jwtToken) |
| 42 | + // TODO: error handling: should we call showError() in dev only? |
| 43 | + await $fetch('/api/_vuefire/auth', { |
| 44 | + method: 'POST', |
| 45 | + // if the token is undefined, the server will delete the cookie |
| 46 | + body: { token: jwtToken }, |
| 47 | + }) |
| 48 | + }) |
| 49 | + } |
| 50 | +}) |
0 commit comments