feat(fullstack): Add organization scoping for application form

This commit is contained in:
2025-05-03 18:06:18 +02:00
parent 2771c71253
commit f748e14c81
12 changed files with 112 additions and 23 deletions

View File

@@ -11,6 +11,22 @@ interface RuntimeAuthConfig {
redirectGuestTo: RouteLocationRaw | string
}
const session = ref<InferSessionFromClient<ClientOptions> | null>(null)
const user = ref<InferUserFromClient<ClientOptions> | null>(null)
const sessionFetching = import.meta.server ? ref(false) : ref(false)
const jwt = ref<string | null>(null)
const organizations = ref<
{ id: string; name: string; createdAt: Date; slug: string; metadata?: any; logo?: string | null }[]
>([])
const selectedOrganization = ref<{
id: string
name: string
createdAt: Date
slug: string
metadata?: any
logo?: string | null
} | null>(null)
export function useAuth() {
const url = useRequestURL()
const headers = import.meta.server ? useRequestHeaders() : undefined
@@ -27,10 +43,6 @@ export function useAuth() {
redirectUserTo: '/',
redirectGuestTo: '/login'
})
const session = useState<InferSessionFromClient<ClientOptions> | null>('auth:session', () => null)
const user = useState<InferUserFromClient<ClientOptions> | null>('auth:user', () => null)
const sessionFetching = import.meta.server ? ref(false) : useState('auth:sessionFetching', () => false)
const jwt = useState<string | null>('auth:jwt', () => null)
async function fetchSession() {
if (sessionFetching.value) {
@@ -43,13 +55,33 @@ export function useAuth() {
headers
}
})
jwt.value = (await client.token()).data?.token ?? null
session.value = data?.session || null
user.value = data?.user || null
sessionFetching.value = false
// Fetch JWT - workaround for not working extraction of JWT out of session (https://github.com/better-auth/better-auth/issues/1835)
jwt.value = (await client.token()).data?.token ?? null
// Fetch organization
organizations.value = (await client.organization.list()).data ?? []
if (!selectedOrganization.value && organizations.value.length > 0) {
selectedOrganization.value = organizations.value[0]
}
return data
}
watch(
() => selectedOrganization.value,
async (newValue) => {
if (newValue) {
await client.organization.setActive({
organizationId: newValue?.id
})
}
}
)
if (import.meta.client) {
client.$store.listen('$sessionSignal', async (signal) => {
if (!signal) return
@@ -79,6 +111,8 @@ export function useAuth() {
signUp: client.signUp,
signOut,
organization: client.organization,
organizations,
selectedOrganization,
options,
fetchSession,
client,