Files
network-app-web/src/stores/auth.ts

73 lines
1.9 KiB
TypeScript

import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import type { User } from '@/types';
import { api } from '@/lib/api';
interface AuthState {
user: User | null;
isLoading: boolean;
isAuthenticated: boolean;
setUser: (user: User | null) => void;
login: (email: string, password: string) => Promise<void>;
logout: () => Promise<void>;
checkSession: () => Promise<void>;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
isLoading: true,
isAuthenticated: false,
setUser: (user) => set({
user,
isAuthenticated: !!user,
isLoading: false,
}),
login: async (email, password) => {
set({ isLoading: true });
try {
await api.login(email, password);
const session = await api.getSession();
if (session?.user) {
set({ user: session.user, isAuthenticated: true, isLoading: false });
} else {
throw new Error('Failed to get session');
}
} catch (error) {
set({ isLoading: false });
throw error;
}
},
logout: async () => {
try {
await api.logout();
} finally {
set({ user: null, isAuthenticated: false });
}
},
checkSession: async () => {
set({ isLoading: true });
try {
const session = await api.getSession();
if (session?.user) {
set({ user: session.user, isAuthenticated: true, isLoading: false });
} else {
set({ user: null, isAuthenticated: false, isLoading: false });
}
} catch {
set({ user: null, isAuthenticated: false, isLoading: false });
}
},
}),
{
name: 'network-auth-storage',
partialize: (state) => ({ user: state.user }),
}
)
);