Files
titan3d_react_node_sqllite/src/store/authStore.ts
T
AI Bot cbf44587aa
Build and Deploy / build-and-push (push) Successful in 1m0s
feat: User management, SMTP email activation and password resets
2026-09-17 08:49:11 +05:30

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 }),
}));