chore: initial commit for phase05

This commit is contained in:
hibna
2026-02-21 16:59:21 +03:00
parent 218452706c
commit 0941a9ba46
43 changed files with 4431 additions and 17 deletions
+69
View File
@@ -0,0 +1,69 @@
import { create } from 'zustand';
import { api, ApiError } from '@/lib/api';
interface User {
id: string;
email: string;
username: string;
isSuperAdmin: boolean;
avatarUrl: string | null;
}
interface AuthState {
user: User | null;
isLoading: boolean;
isAuthenticated: boolean;
login: (email: string, password: string) => Promise<void>;
register: (email: string, username: string, password: string) => Promise<void>;
logout: () => Promise<void>;
fetchUser: () => Promise<void>;
}
export const useAuthStore = create<AuthState>((set) => ({
user: null,
isLoading: true,
isAuthenticated: false,
login: async (email, password) => {
const data = await api.post<{ accessToken: string; user: User }>('/auth/login', {
email,
password,
});
localStorage.setItem('access_token', data.accessToken);
set({ user: data.user, isAuthenticated: true });
},
register: async (email, username, password) => {
const data = await api.post<{ accessToken: string; user: User }>('/auth/register', {
email,
username,
password,
});
localStorage.setItem('access_token', data.accessToken);
set({ user: data.user, isAuthenticated: true });
},
logout: async () => {
try {
await api.post('/auth/logout');
} catch {
// ignore
}
localStorage.removeItem('access_token');
set({ user: null, isAuthenticated: false });
},
fetchUser: async () => {
try {
const user = await api.get<User>('/auth/me');
set({ user, isAuthenticated: true, isLoading: false });
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
set({ user: null, isAuthenticated: false, isLoading: false });
} else {
set({ isLoading: false });
}
}
},
}));