feat: implement auth state management with RouteGuards

This commit is contained in:
Your Name
2026-04-11 17:56:40 +05:30
parent dfd33f1dad
commit 96f867f139
13 changed files with 434 additions and 190 deletions
+10 -51
View File
@@ -1,6 +1,4 @@
import { create } from "zustand";
import { postAuthApiClient, preAuthApiClient } from "../api/apiClient";
import { endpoints } from "../config/endpoints";
interface UserProfile {
public_id: string;
@@ -10,59 +8,20 @@ interface UserProfile {
interface AuthState {
accessToken: string | null;
isAuthenticated: boolean;
user: UserProfile | null;
isInitializing: boolean; // refresh in transit
login: (credentials: any) => Promise<void>;
logout: () => Promise<void>;
checkAuth: () => Promise<void>;
isInitializing: boolean;
setAuth: (accessToken: string, user: UserProfile) => void;
clearAuth: () => void;
setInitializing: (v: boolean) => void;
}
export const useAuth = create<AuthState>((set, get) => ({
export const useAuthStore = create<AuthState>((set) => ({
accessToken: null,
isAuthenticated: false,
user: null,
isInitializing: true,
login: async (credentials: any) => {
const response = await preAuthApiClient.post(endpoints.LOGIN, credentials);
set({
accessToken: response.data.access,
isAuthenticated: true,
user: response.data.user,
});
},
logout: async () => {
try {
const token = get().accessToken;
if (token) {
await preAuthApiClient.post(endpoints.LOGOUT);
}
} finally {
set({
accessToken: null,
isAuthenticated: false,
user: null,
});
}
},
checkAuth: async () => {
try {
const response = await postAuthApiClient.get(endpoints.ME);
set({
user: response.data,
isAuthenticated: true,
});
} catch (err) {
console.error("Check auth error:", err);
set({
user: null,
isAuthenticated: false,
});
} finally {
set({ isInitializing: false });
}
},
setAuth: (accessToken, user) =>
set({ accessToken, user, isInitializing: false }),
clearAuth: () =>
set({ accessToken: null, user: null, isInitializing: false }),
setInitializing: (isInitializing) => set({ isInitializing }),
}));