diff --git a/src/App.jsx b/src/App.jsx index b0345dd..a176ae1 100755 --- a/src/App.jsx +++ b/src/App.jsx @@ -1,37 +1,108 @@ -import React, { useState, useMemo } from "react"; -import { ThemeProvider, CssBaseline, Switch, Box } from "@mui/material"; +import React, { useState, useMemo, useEffect } from "react"; +import { ThemeProvider, CssBaseline, Switch, Box, CircularProgress } from "@mui/material"; import Dashboard from "./Components/Layout/Dashboard"; import LoginModal from "./Components/UI/LoginModal"; import { lightTheme, darkTheme } from "./Style/theme"; -import Logo from './assets/images/logo.svg?react'; // Импорт как компонента +import Logo from './assets/images/logo.svg?react'; +import { checkAuth } from "./Components/UI/auth"; // Убедитесь, что путь правильный function App() { - const [isAuthenticated, setIsAuthenticated] = useState(false); - const [showLoginModal, setShowLoginModal] = useState(true); + const [authState, setAuthState] = useState({ + isAuthenticated: false, + isLoading: true, + user: null + }); + const [showLoginModal, setShowLoginModal] = useState(false); const [isDarkMode, setIsDarkMode] = useState( window.matchMedia("(prefers-color-scheme: dark)").matches ); const theme = useMemo(() => (isDarkMode ? darkTheme : lightTheme), [isDarkMode]); - const handleLogin = () => { - setIsAuthenticated(true); + useEffect(() => { + const verifyAuth = async () => { + try { + const authStatus = await checkAuth(); + + setAuthState({ + isAuthenticated: authStatus.isAuthenticated, + isLoading: false, + user: authStatus.user || null + }); + + setShowLoginModal(!authStatus.isAuthenticated); + } catch (error) { + console.error('Auth verification error:', error); + setAuthState({ + isAuthenticated: false, + isLoading: false, + user: null + }); + setShowLoginModal(true); + } + }; + + verifyAuth(); + }, []); + + const handleLogin = (userData) => { + setAuthState({ + isAuthenticated: true, + isLoading: false, + user: userData + }); setShowLoginModal(false); }; + const handleLogout = async () => { + try { + await fetch('http://192.168.2.39:3000/api/auth/logout', { + method: 'POST', + credentials: 'include' + }); + localStorage.removeItem('access_token'); + setAuthState({ + isAuthenticated: false, + isLoading: false, + user: null + }); + setShowLoginModal(true); + } catch (error) { + console.error('Logout failed:', error); + } + }; + + if (authState.isLoading) { + return ( + + + + +

Проверка авторизации...

+
+
+ ); + } + return ( - {!isAuthenticated && showLoginModal ? ( + {!authState.isAuthenticated && showLoginModal ? ( <> - {/* Логотип */} - + - setIsDarkMode((prev) => !prev)} /> + setIsDarkMode((prev) => !prev)} + /> )} diff --git a/src/Components/UI/LoginModal.jsx b/src/Components/UI/LoginModal.jsx index 3e29de2..5a3bfc8 100755 --- a/src/Components/UI/LoginModal.jsx +++ b/src/Components/UI/LoginModal.jsx @@ -16,9 +16,9 @@ const LoginModal = ({ onLogin, onClose }) => { e.preventDefault(); try { - // Отправляем данные на бэкенд - const response = await fetch(`${import.meta.env.VITE_BACK_URL}/api/auth/login`, { + const response = await fetch('http://192.168.2.39:3000/api/auth/login', { method: 'POST', + credentials: 'include', headers: { 'Content-Type': 'application/json', }, @@ -28,8 +28,9 @@ const LoginModal = ({ onLogin, onClose }) => { const data = await response.json(); if (data.success) { - onLogin(); // Успешная авторизация - onClose(); // Закрыть модальное окно + localStorage.setItem('access_token', data.access_token); + onLogin(data.user); // Передаем данные пользователя + onClose(); } else { setError(data.message || "Неверный логин или пароль"); } diff --git a/src/Components/UI/auth.jsx b/src/Components/UI/auth.jsx new file mode 100644 index 0000000..9c8e0a9 --- /dev/null +++ b/src/Components/UI/auth.jsx @@ -0,0 +1,20 @@ +export const checkAuth = async () => { + try { + const response = await fetch('http://192.168.2.39:3000/api/auth/check', { + method: 'GET', + credentials: 'include', // Важно для отправки cookies + headers: { + 'Authorization': `Bearer ${localStorage.getItem('access_token') || ''}`, + }, + }); + + if (!response.ok) { + throw new Error('Not authenticated'); + } + + return await response.json(); + } catch (err) { + console.error('Auth check failed:', err); + return { isAuthenticated: false }; + } +}; \ No newline at end of file