bc20deac23
Self-edit доступен всем ролям без PUT /admins/:id. Co-authored-by: Cursor <cursoragent@cursor.com>
75 lines
2.4 KiB
TypeScript
75 lines
2.4 KiB
TypeScript
import { create } from 'zustand';
|
|
import { Admin } from '../types/api';
|
|
import { authApi } from '../api/authApi';
|
|
import { ACCESS_TOKEN_KEY, REFRESH_TOKEN_KEY } from '../utils/constants';
|
|
import { useMetricsStore } from './metricsStore';
|
|
|
|
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>;
|
|
setUser: (user: Admin) => 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);
|
|
useMetricsStore.getState().reset();
|
|
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,
|
|
});
|
|
}
|
|
},
|
|
|
|
setUser: (user) => set({ user }),
|
|
})); |