Разработка админ-панели EventHubFrontAdmin v1.0 #1
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
import { create } from 'zustand';
|
||||
import { Admin } from '../types/api';
|
||||
import { authApi } from '../api/authApi';
|
||||
import { ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY } from '../utils/constants';
|
||||
|
||||
interface AuthState {
|
||||
user: Admin | null;
|
||||
accessToken: string | null;
|
||||
refreshToken: string | null;
|
||||
isAuthenticated: boolean;
|
||||
isInitialized: boolean;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => Promise<void>;
|
||||
checkAuth: () => Promise<void>;
|
||||
}
|
||||
|
||||
export const useAuthStore = create<AuthState>((set) => ({
|
||||
user: null,
|
||||
accessToken: localStorage.getItem(ACCESS_TOKEN_KEY),
|
||||
refreshToken: localStorage.getItem(REFRESH_TOKEN_KEY),
|
||||
isAuthenticated: false,
|
||||
isInitialized: false,
|
||||
|
||||
login: async (email: string, password: string) => {
|
||||
const { token, refresh_token, user } = await authApi.login(email, password);
|
||||
localStorage.setItem(ACCESS_TOKEN_KEY, token);
|
||||
localStorage.setItem(REFRESH_TOKEN_KEY, refresh_token);
|
||||
set({
|
||||
accessToken: token,
|
||||
refreshToken: refresh_token,
|
||||
user,
|
||||
isAuthenticated: true,
|
||||
isInitialized: true,
|
||||
});
|
||||
},
|
||||
|
||||
logout: async () => {
|
||||
localStorage.removeItem(ACCESS_TOKEN_KEY);
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||
set({
|
||||
user: null,
|
||||
accessToken: null,
|
||||
refreshToken: null,
|
||||
isAuthenticated: false,
|
||||
isInitialized: true,
|
||||
});
|
||||
},
|
||||
|
||||
checkAuth: async () => {
|
||||
const token = localStorage.getItem(ACCESS_TOKEN_KEY);
|
||||
if (!token) {
|
||||
set({ isInitialized: true });
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const user = await authApi.getMe();
|
||||
set({ user, isAuthenticated: true, isInitialized: true });
|
||||
} catch {
|
||||
localStorage.removeItem(ACCESS_TOKEN_KEY);
|
||||
localStorage.removeItem(REFRESH_TOKEN_KEY);
|
||||
set({
|
||||
user: null,
|
||||
accessToken: null,
|
||||
refreshToken: null,
|
||||
isAuthenticated: false,
|
||||
isInitialized: true,
|
||||
});
|
||||
}
|
||||
},
|
||||
}));
|
||||
Reference in New Issue
Block a user