feat: implement authentication state management with Zustand and add request interceptor for JWT injection

This commit is contained in:
Your Name
2026-04-10 18:52:27 +05:30
parent c15a8b481b
commit 07bd221e77
4 changed files with 51 additions and 1 deletions
+10
View File
@@ -1,4 +1,5 @@
import axios, { type AxiosError } from "axios";
import { useAuth } from "../store/useAuth";
const authApiClient = axios.create({
baseURL: `${import.meta.env.VITE_API_URL}/api/auth/`,
@@ -30,4 +31,13 @@ authApiClient.interceptors.response.use(
},
);
// automatically attach access token to request
authApiClient.interceptors.request.use((config) => {
const token = useAuth.getState().accessToken;
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
export default authApiClient;
+36
View File
@@ -0,0 +1,36 @@
import { create } from "zustand";
import authApiClient from "../api/apiClient";
interface AuthState {
accessToken: string | null;
refreshToken: string | null;
isAuthenticated: boolean;
user: any | null;
login: (credentials: any) => Promise<void>;
logout: () => Promise<void>;
}
export const useAuth = create<AuthState>((set) => ({
accessToken: null,
refreshToken: null,
isAuthenticated: false,
user: null,
login: async (credentials: any) => {
const response = await authApiClient.post("login/", credentials);
set({
accessToken: response.data.access,
refreshToken: response.data.refresh,
isAuthenticated: true,
user: response.data.user,
});
},
logout: async () => {
await authApiClient.post("logout/");
set({
accessToken: null,
refreshToken: null,
isAuthenticated: false,
user: null,
});
},
}));