init
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
import { create } from "zustand";
|
||||
import { persist } from "zustand/middleware";
|
||||
import axios from "axios";
|
||||
import * as api from "../api/auth";
|
||||
|
||||
export const useAuthStore = create(
|
||||
persist(
|
||||
(set, get) => {
|
||||
// Axios interceptor for handling 401/403
|
||||
axios.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
if (error.response && (error.response.status === 401 || error.response.status === 403)) {
|
||||
set({ user_id: null, token: null, isLoading: false });
|
||||
delete axios.defaults.headers.common["Authorization"];
|
||||
// Redirect to login using window.location for global interceptor
|
||||
if (window.location.pathname !== '/login') {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
user_id: null,
|
||||
token: null,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
|
||||
signIn: async (email, password) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const response = await api.login({ email, password });
|
||||
set({ user_id: response.user_id, token: response.token, isLoading: false });
|
||||
} catch (error) {
|
||||
set({
|
||||
error: error.response?.data?.message || error.message,
|
||||
isLoading: false,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
signUp: async (userData) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const response = await api.register(userData);
|
||||
set({ user_id: response.user_id, token: response.token, isLoading: false });
|
||||
} catch (error) {
|
||||
set({
|
||||
error: error.response?.data?.message || error.message,
|
||||
isLoading: false,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
signInWithGoogle: async (googleToken) => {
|
||||
set({ isLoading: true, error: null });
|
||||
try {
|
||||
const response = await api.googleLogin(googleToken);
|
||||
set({ user_id: response.user_id, token: response.token, isLoading: false });
|
||||
} catch (error) {
|
||||
set({
|
||||
error: error.response?.data?.message || error.message,
|
||||
isLoading: false,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
signOut: async () => {
|
||||
const { token } = get();
|
||||
try {
|
||||
await api.logout(token);
|
||||
} catch (error) {
|
||||
console.error("Logout error:", error);
|
||||
} finally {
|
||||
set({ user_id: null, token: null });
|
||||
window.location.href = '/login';
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
{
|
||||
name: "auth-storage",
|
||||
}
|
||||
)
|
||||
);
|
||||
Reference in New Issue
Block a user