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