feat: implement auth flow and app initialization

This commit is contained in:
2026-06-15 18:41:27 +05:30
parent 9de65d0ce6
commit 8d4ff49633
29 changed files with 551 additions and 535 deletions

48
src/store/app.store.ts Normal file
View File

@@ -0,0 +1,48 @@
import type { TenantInfo, UserProfile } from '@/types';
import { create } from 'zustand';
export type AppLoadStatus = 'idle' | 'loading' | 'loaded' | 'error';
interface AppState {
user: UserProfile | null;
tenant: TenantInfo | null;
permissions: string[];
loadStatus: AppLoadStatus;
isInitialized: boolean;
setLoading: () => void;
setLoaded: () => void;
setLoadError: () => void;
setUserContext: (payload: {
user: UserProfile;
tenant?: TenantInfo | null;
permissions?: string[];
}) => void;
clear: () => void;
}
export const useAppStore = create<AppState>()((set) => ({
user: null,
tenant: null,
permissions: [],
loadStatus: 'idle',
isInitialized: false,
setLoading: () => set({ loadStatus: 'loading', isInitialized: false }),
setLoaded: () => set({ loadStatus: 'loaded', isInitialized: true }),
setLoadError: () => set({ loadStatus: 'error', isInitialized: true }),
setUserContext: ({ user, tenant = null, permissions = [] }) =>
set({
user,
tenant,
permissions,
loadStatus: 'loaded',
isInitialized: true,
}),
clear: () =>
set({
user: null,
tenant: null,
permissions: [],
loadStatus: 'idle',
isInitialized: false,
}),
}));

View File

@@ -1,40 +1,40 @@
import type { UserProfile } from '@/types';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
const ACCESS_TOKEN_KEY = 'access_token';
const getStoredAccessToken = () => {
if (typeof window === 'undefined') return null;
return localStorage.getItem(ACCESS_TOKEN_KEY);
};
interface AuthState {
user: UserProfile | null;
accessToken: string | null;
refreshToken: string | null;
isAuthenticated: boolean;
setAuth: (user: UserProfile, accessToken?: string | null, refreshToken?: string | null) => void;
setAccessToken: (accessToken: string) => void;
logout: () => void;
}
export const useAuthStore = create<AuthState>()(
persist(
(set) => ({
user: null,
export const useAuthStore = create<AuthState>()((set) => ({
accessToken: getStoredAccessToken(),
isAuthenticated: !!getStoredAccessToken(),
setAccessToken: (accessToken) => {
if (typeof window !== 'undefined') {
localStorage.setItem(ACCESS_TOKEN_KEY, accessToken);
}
set({
accessToken,
isAuthenticated: true,
});
},
logout: () => {
if (typeof window !== 'undefined') {
localStorage.removeItem(ACCESS_TOKEN_KEY);
}
set({
accessToken: null,
refreshToken: null,
isAuthenticated: false,
setAuth: (user, accessToken, refreshToken) =>
set({
user,
accessToken: accessToken ?? null,
refreshToken: refreshToken ?? null,
isAuthenticated: true,
}),
logout: () =>
set({
user: null,
accessToken: null,
refreshToken: null,
isAuthenticated: false,
}),
}),
{
name: 'auth-storage',
},
),
);
});
},
}));