74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
import { create } from 'zustand';
|
|
import { api } from '../lib/api';
|
|
|
|
interface UserProfile {
|
|
id: string;
|
|
email: string;
|
|
role: string;
|
|
api_credits: number;
|
|
storage_limit_mb: number;
|
|
}
|
|
|
|
interface AuthState {
|
|
user: { id: string, email: string } | null;
|
|
profile: UserProfile | null;
|
|
isLoading: boolean;
|
|
initialize: () => Promise<void>;
|
|
setSession: (token: string, profile: UserProfile) => void;
|
|
signOut: () => void;
|
|
setProfile: (profile: UserProfile) => void;
|
|
isAuthModalOpen: boolean;
|
|
openAuthModal: (mode?: 'login' | 'register' | 'forgot-password') => void;
|
|
closeAuthModal: () => void;
|
|
authMode: 'login' | 'register' | 'forgot-password';
|
|
}
|
|
|
|
export const useAuthStore = create<AuthState>((set) => ({
|
|
user: null,
|
|
profile: null,
|
|
isLoading: true,
|
|
isAuthModalOpen: false,
|
|
authMode: 'login',
|
|
|
|
openAuthModal: (mode = 'login') => set({ isAuthModalOpen: true, authMode: mode }),
|
|
closeAuthModal: () => set({ isAuthModalOpen: false }),
|
|
|
|
initialize: async () => {
|
|
try {
|
|
const token = localStorage.getItem('auth_token');
|
|
if (!token) {
|
|
set({ user: null, profile: null, isLoading: false });
|
|
return;
|
|
}
|
|
|
|
const { profile } = await api.getMe();
|
|
if (profile) {
|
|
set({
|
|
user: { id: profile.id, email: profile.email },
|
|
profile,
|
|
isLoading: false
|
|
});
|
|
} else {
|
|
localStorage.removeItem('auth_token');
|
|
set({ user: null, profile: null, isLoading: false });
|
|
}
|
|
} catch (error) {
|
|
console.error('Failed to initialize session:', error);
|
|
localStorage.removeItem('auth_token');
|
|
set({ user: null, profile: null, isLoading: false });
|
|
}
|
|
},
|
|
|
|
setSession: (token, profile) => {
|
|
localStorage.setItem('auth_token', token);
|
|
set({ user: { id: profile.id, email: profile.email }, profile });
|
|
},
|
|
|
|
signOut: () => {
|
|
localStorage.removeItem('auth_token');
|
|
set({ user: null, profile: null });
|
|
},
|
|
|
|
setProfile: (profile) => set({ profile }),
|
|
}));
|