This commit is contained in:
keyhan
2026-04-05 15:22:01 +03:30
commit 33be1649c4
82 changed files with 23956 additions and 0 deletions
+55
View File
@@ -0,0 +1,55 @@
'use client';
import { create } from 'zustand';
import api from '@/lib/api';
import type { User, AuthResponse } from '@/types';
interface AuthState {
user: User | null;
isLoading: boolean;
isAuthenticated: boolean;
login: (email: string, password: string) => Promise<void>;
register: (data: { email: string; password: string; firstName: string; lastName: string }) => Promise<void>;
logout: () => void;
loadUser: () => Promise<void>;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
isLoading: true,
isAuthenticated: false,
login: async (email, password) => {
const { data } = await api.post<AuthResponse>('/auth/login', { email, password });
localStorage.setItem('accessToken', data.accessToken);
localStorage.setItem('refreshToken', data.refreshToken);
set({ user: data.user, isAuthenticated: true });
},
register: async (registerData) => {
const { data } = await api.post<AuthResponse>('/auth/register', registerData);
localStorage.setItem('accessToken', data.accessToken);
localStorage.setItem('refreshToken', data.refreshToken);
set({ user: data.user, isAuthenticated: true });
},
logout: () => {
localStorage.removeItem('accessToken');
localStorage.removeItem('refreshToken');
set({ user: null, isAuthenticated: false });
},
loadUser: async () => {
try {
const token = localStorage.getItem('accessToken');
if (!token) {
set({ isLoading: false });
return;
}
const { data } = await api.get<User>('/users/me');
set({ user: data, isAuthenticated: true, isLoading: false });
} catch {
set({ user: null, isAuthenticated: false, isLoading: false });
}
},
}));