stadtwerke/innungsapp/apps/mobile/store/auth.store.ts

59 lines
1.4 KiB
TypeScript

import { create } from 'zustand'
import { authClient } from '@/lib/auth-client'
import AsyncStorage from '@react-native-async-storage/async-storage'
interface Session {
user: {
id: string
email: string
name: string
}
token?: string
}
interface AuthState {
session: Session | null
orgId: string | null
role: 'admin' | 'member' | null
isInitialized: boolean
initialize: () => Promise<void>
setSession: (session: Session | null) => void
signOut: () => Promise<void>
}
export const useAuthStore = create<AuthState>((set) => ({
session: null,
orgId: null,
role: null,
isInitialized: false,
initialize: async () => {
try {
const { data } = await authClient.getSession()
if (data?.session && data?.user) {
set({
session: { user: data.user },
isInitialized: true,
})
// Store token for API requests
if (data.session.token) {
await AsyncStorage.setItem('better-auth-session', data.session.token)
}
} else {
await AsyncStorage.removeItem('better-auth-session')
set({ session: null, orgId: null, role: null, isInitialized: true })
}
} catch {
set({ session: null, isInitialized: true })
}
},
setSession: (session) => set({ session }),
signOut: async () => {
await authClient.signOut()
await AsyncStorage.removeItem('better-auth-session')
set({ session: null, orgId: null, role: null })
},
}))