mirror of
https://github.com/ramvignesh-b/pi-ku.git
synced 2026-05-04 08:56:52 +00:00
feat: implement auth state management with RouteGuards
This commit is contained in:
@@ -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 }),
|
||||
}));
|
||||
|
||||
Reference in New Issue
Block a user