Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: auth multi tenancy support #1521

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,9 +54,9 @@
"lint": "prettier -c --parser typescript \"{src,__tests__,e2e}/**/*.[jt]s?(x)\"",
"lint:fix": "pnpm run lint --write",
"test:types": "tsc --build tsconfig.json",
"test:unit": "vitest --coverage",
"test:unit": "cross-env GOOGLE_CLOUD_PROJECT='vue-fire-store' vitest --coverage",
"firebase:emulators": "firebase emulators:start",
"test:dev": "vitest",
"test:dev": "cross-env GOOGLE_CLOUD_PROJECT='vue-fire-store' vitest",
"test": "pnpm run lint && pnpm run test:types && pnpm run build && pnpm run -C packages/nuxt build && pnpm run test:unit run",
"prepare": "simple-git-hooks"
},
Expand All @@ -71,6 +71,7 @@
],
"license": "MIT",
"dependencies": {
"jwt-decode": "^4.0.0",
"vue-demi": "latest"
},
"peerDependencies": {
Expand All @@ -96,6 +97,7 @@
"chalk": "^5.3.0",
"consola": "^3.2.3",
"conventional-changelog-cli": "^2.0.34",
"cross-env": "^7.0.3",
"enquirer": "^2.4.1",
"execa": "^8.0.1",
"firebase": "^10.8.0",
Expand Down
5 changes: 3 additions & 2 deletions packages/nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
"build": "nuxt-module-build build",
"lint": "eslint src",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path . -l nuxt-vuefire -r 1",
"test": "vitest",
"dev": "nuxi dev playground",
"test": "cross-env GOOGLE_CLOUD_PROJECT='vue-fire-store' vitest",
"dev": "cross-env GOOGLE_CLOUD_PROJECT='vue-fire-store' nuxi dev playground",
"dev:build": "nuxi build playground",
"dev:prepare": "nuxt-module-build --stub"
},
Expand Down Expand Up @@ -71,6 +71,7 @@
"firebase-admin": "^12.0.0",
"firebase-functions": "^4.7.0",
"nuxt": "^3.10.3",
"playwright-core": "^1.43.1",
"vuefire": "workspace:*"
}
}
16 changes: 16 additions & 0 deletions packages/nuxt/playground/components/ServerOnlyPre.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<script setup lang="ts">
type Props = {
data: MaybeRef<unknown>,
testid: string
}
const props = defineProps<Props>()

const serverState = useState();
if (import.meta.server) {
serverState.value = JSON.parse(JSON.stringify(toValue(props.data)));
}
</script>

<template>
<pre :data-testid="props.testid">{{ serverState }}</pre>
</template>
45 changes: 29 additions & 16 deletions packages/nuxt/playground/pages/authentication.vue
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@ watch(user, (user) => {
// new user
const email = ref('')
const password = ref('')
function signUp() {
const tenant = ref<string | null>(null)

async function signUp() {
// link to an existing anonymous account
if (user.value?.isAnonymous) {
credential = EmailAuthProvider.credential(email.value, password.value)
Expand All @@ -59,7 +61,7 @@ function signUp() {
return createUserWithEmailAndPassword(auth, email.value, password.value)
}

function signinPopup() {
async function signinPopup() {
return signInWithPopup(auth, googleAuthProvider).then((result) => {
const googleCredential = GoogleAuthProvider.credentialFromResult(result)
credential = googleCredential
Expand Down Expand Up @@ -96,37 +98,42 @@ onMounted(() => {
<template>
<main>
<h1>Auth playground</h1>
<button @click="signOut(auth)">SignOut</button>
<button @click="signInAnonymously(auth)">Anonymous signIn</button>
<button @click="signinPopup()">Signin Google (popup)</button>
<button @click="signinRedirect()">Signin Google (redirect)</button>
<button @click="changeUserImage">Change User picture</button>
<button data-testid="sign-out" @click="auth.tenantId = null; signOut(auth)">SignOut</button>
<button data-testid="anonymous-sign-in" @click="auth.tenantId = null; signInAnonymously(auth)">Anonymous signIn</button>
<button data-testid="google-popup-sign-in" @click="auth.tenantId = null; signinPopup()">Signin Google (popup)</button>
<button data-testid="google-redirect-sign-in" @click="auth.tenantId = null; signinRedirect()">Signin Google (redirect)</button>
<button data-testid="change-user-picture" @click="changeUserImage">Change User picture</button>

<p>
Tenant: <input v-model="tenant" data-testid="tenant" type="text" placeholder="leave empty for default tenant"/>
</p>

<form @submit.prevent="signUp()">

<form @submit.prevent="auth.tenantId = tenant || null; signUp()">
<fieldset>
<legend>New User</legend>

<label> Email: <input v-model="email" type="email" required /> </label>
<label> Email: <input v-model="email" data-testid="email-signup" type="email" required /> </label>

<label>
Password: <input v-model="password" type="password" required />
Password: <input v-model="password" data-testid="password-signup" type="password" required />
</label>

<button>Create</button>
<button data-testid="submit-signup">Create</button>
</fieldset>
</form>

<form @submit.prevent="signInWithEmailAndPassword(auth, email, password)">
<form @submit.prevent="auth.tenantId = tenant || null; signInWithEmailAndPassword(auth, email, password)">
<fieldset>
<legend>Sign in</legend>

<label> Email: <input v-model="email" type="email" required /> </label>
<label> Email: <input v-model="email" data-testid="email-signin" type="email" required /> </label>

<label>
Password: <input v-model="password" type="password" required />
Password: <input v-model="password" data-testid="password-signin" type="password" required />
</label>

<button>Signin</button>
<button data-testid="submit-signin">Signin</button>
</fieldset>
</form>

Expand All @@ -144,7 +151,13 @@ onMounted(() => {
<!-- this is for debug purposes only, displaying it on the server would create a hydration mismatch -->
<ClientOnly>
<p>Current User:</p>
<pre>{{ user }}</pre>
<pre data-testid="user-data-client">{{ user }}</pre>
</ClientOnly>

<ServerOnlyPre
v-if="user"
:data="user"
testid="user-data-server"
/>
</main>
</template>
8 changes: 7 additions & 1 deletion packages/nuxt/src/runtime/auth/api.session-verification.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
import { ensureAdminApp } from 'vuefire/server'
import { logger } from '../logging'
import { useRuntimeConfig } from '#imports'
import { parseTenantFromFirebaseJwt } from 'vuefire'

/**
* Setups an API endpoint to be used by the client to mint a cookie based auth session.
Expand All @@ -27,7 +28,12 @@ export default defineEventHandler(async (event) => {
},
'session-verification'
)
const adminAuth = getAdminAuth(adminApp)

const tenant = parseTenantFromFirebaseJwt(token)

const adminAuth = tenant
? getAdminAuth(adminApp).tenantManager().authForTenant(tenant)
: getAdminAuth(adminApp)

logger.debug(token ? 'Verifying the token' : 'Deleting the session cookie')
const verifiedIdToken = token ? await adminAuth.verifyIdToken(token) : null
Expand Down
12 changes: 10 additions & 2 deletions packages/nuxt/src/runtime/auth/plugin-authenticate-user.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ export default defineNuxtPlugin(async (nuxtApp) => {
const event = useRequestEvent()
const firebaseApp = nuxtApp.$firebaseApp as FirebaseApp
const firebaseAdminApp = nuxtApp.$firebaseAdminApp as AdminApp
const adminAuth = getAdminAuth(firebaseAdminApp)
const auth = nuxtApp.$firebaseAuth as Auth

const decodedToken = nuxtApp[
Expand All @@ -27,10 +26,17 @@ export default defineNuxtPlugin(async (nuxtApp) => {

const uid = decodedToken?.uid

const tenant = decodedToken?.firebase?.tenant

const adminAuth = tenant
? getAdminAuth(firebaseAdminApp).tenantManager().authForTenant(tenant)
: getAdminAuth(firebaseAdminApp)

// this is also undefined if the user hasn't enabled the session cookie option
if (uid) {
// reauthenticate if the user is not the same (e.g. invalidated)
if (auth.currentUser?.uid !== uid) {
// OR multi tenancy is used, otherwise tenantId won't be present in SSR accessToken
if (auth.currentUser?.uid !== uid || tenant) {
const customToken = await adminAuth
.createCustomToken(uid)
.catch((err) => {
Expand All @@ -40,6 +46,8 @@ export default defineNuxtPlugin(async (nuxtApp) => {
// console.timeLog('token', `got token for ${user.uid}`)
if (customToken) {
logger.debug('Signing in with custom token')
// Update firebase/auth tenantId to ensure it is set during SSR
auth.tenantId = tenant ?? null
// TODO: allow user to handle error?
await signInWithCustomToken(auth, customToken)
// console.timeLog('token', `signed in with token for ${user.uid}`)
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/runtime/auth/plugin-user-token.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export default defineNuxtPlugin(async (nuxtApp) => {
const adminApp = nuxtApp.$firebaseAdminApp as AdminApp

const decodedToken = await decodeSessionCookie(
getCookie(event, AUTH_COOKIE_NAME),
event && getCookie(event, AUTH_COOKIE_NAME),
adminApp
)

Expand Down
138 changes: 138 additions & 0 deletions packages/nuxt/tests/auth.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import { describe, expect, it } from 'vitest'
import { createPage, setup } from '@nuxt/test-utils/e2e'
import { createResolver } from '@nuxt/kit'

const { resolve } = createResolver(import.meta.url)

await setup({
rootDir: resolve('../playground'),
build: false,
server: true,
browser: true,
dev: true,

browserOptions: {
type: 'chromium',
launch: {
headless: true,
},
},
})

describe('auth/multi-tenancy', async () => {
it('should create a default tenant token if no tenant is specified', async () => {
const page = await createPage('/authentication')

// 1. Sign out, clear tenant to start clean
await page.getByTestId('sign-out').click()
await page.getByTestId('tenant').clear()

// 2. Ensure test account exists
const signupResponse = page.waitForResponse((r) =>
r.url().includes('accounts:signUp')
)
await page.getByTestId('email-signup').fill('[email protected]')
await page.getByTestId('password-signup').fill('testtest')
await page.getByTestId('submit-signup').click()
await signupResponse

// 3. Log in with test account, check tenant
// Call to sign in is 'accounts:signInWithPassword', but we need __session call to get user info
const signinResponse = page.waitForResponse((r) =>
r.url().includes('/api/__session')
)
await page.getByTestId('email-signin').fill('[email protected]')
await page.getByTestId('password-signin').fill('testtest')
await page.getByTestId('submit-signin').click()
await signinResponse

// 4. Assert user does in fact not have a tenant id
const userData = await page.getByTestId('user-data-client').textContent()

expect(userData).toBeTruthy()
if (!userData) return

const user = JSON.parse(userData)
expect(user.tenantId).toBeUndefined()
})

it('should create token with tenantId if tenant name is specified', async () => {
const page = await createPage('/authentication')
const tenantName = 'tenant A'

// 1. Sign out, clear tenant to start clean
await page.getByTestId('sign-out').click()
await page.getByTestId('tenant').clear()
await page.getByTestId('tenant').fill(tenantName)

// 2. Ensure test account exists
const signupResponse = page.waitForResponse((r) =>
r.url().includes('accounts:signUp')
)
await page.getByTestId('email-signup').fill('[email protected]')
await page.getByTestId('password-signup').fill('testtest')
await page.getByTestId('submit-signup').click()
await signupResponse

// 3. Log in with test account, check tenant
// Call to sign in is 'accounts:signInWithPassword', but we need __session call to get user info
const signinResponse = page.waitForResponse((r) =>
r.url().includes('/api/__session')
)
await page.getByTestId('email-signin').fill('[email protected]')
await page.getByTestId('password-signin').fill('testtest')
await page.getByTestId('submit-signin').click()
await signinResponse

// 4. Assert user does in fact not have a tenant id
const userData = await page.getByTestId('user-data-client').textContent()

expect(userData).toBeTruthy()
if (!userData) return

const user = JSON.parse(userData)
expect(user.tenantId).toEqual(tenantName)
})

it('should return tenantId in server render', async () => {
const page = await createPage('/authentication')
const tenantName = 'tenant A'

// 1. Sign out, clear tenant to start clean
await page.getByTestId('sign-out').click()
await page.getByTestId('tenant').clear()
await page.getByTestId('tenant').fill(tenantName)

// 2. Ensure test account exists
const signupResponse = page.waitForResponse((r) =>
r.url().includes('accounts:signUp')
)
await page.getByTestId('email-signup').fill('[email protected]')
await page.getByTestId('password-signup').fill('testtest')
await page.getByTestId('submit-signup').click()
await signupResponse

// 3. Log in with test account, check tenant
// Call to sign in is 'accounts:signInWithPassword', but we need __session call to get user info
const signinResponse = page.waitForResponse((r) =>
r.url().includes('/api/__session')
)
await page.getByTestId('email-signin').fill('[email protected]')
await page.getByTestId('password-signin').fill('testtest')
await page.getByTestId('submit-signin').click()
await signinResponse

// 4. Reload the page to trigger server render
await page.reload({ waitUntil: 'domcontentloaded' })

const serverUserData = await page
.getByTestId('user-data-server')
.textContent()

expect(serverUserData).toBeTruthy()
if (!serverUserData) return

const serverUser = JSON.parse(serverUserData)
expect(serverUser.tenantId).toEqual(tenantName)
})
})
Loading