dodanie logowania #2

Merged
s153592 merged 1 commits from login into master 2024-10-28 23:26:53 +01:00
12 changed files with 665 additions and 256 deletions

View File

@ -12,6 +12,7 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.2",
"jwt-decode": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.1",
@ -12539,6 +12540,14 @@
"node": ">=4.0"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"engines": {
"node": ">=18"
}
},
"node_modules/keyv": {
"version": "4.5.4",
"resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz",

View File

@ -7,6 +7,7 @@
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.7.2",
"jwt-decode": "^4.0.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.23.1",

View File

@ -1,36 +1,70 @@
import 'tailwindcss/tailwind.css';
import React from 'react';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import React, { useState, useEffect } from 'react';
import { BrowserRouter as Router, Route, Routes, Navigate } from 'react-router-dom';
import PanelAdministratora from './components/PanelAdministratora';
import ZarzadzanieProduktami from './components/ZarzadzanieProduktami';
import Transakcje from './components/Transakcje';
import NavBar from './components/NavBar'
import NavBar from './components/NavBar';
import Sidebar from './components/Sidebar';
import Wydatki from './components/Wydatki';
import Raporty from './components/Raporty';
import Login from './components/Login';
import Harmonogram from './components/Harmonogram';
import { jwtDecode } from 'jwt-decode';
const App = () => {
const [token, setToken] = useState(localStorage.getItem('token'));
const [userRole, setUserRole] = useState(null);
useEffect(() => {
if (token) {
try {
const decodedToken = jwtDecode(token);
console.log(decodedToken);
setUserRole(decodedToken['http://schemas.microsoft.com/ws/2008/06/identity/claims/role']);
} catch (error) {
console.error('Failed to decode token:', error);
setUserRole(null);
}
} else {
setUserRole(null);
}
}, [token]);
return (
<Router>
<div className="">
<NavBar />
{token && <NavBar setToken={setToken} />}
<div className="flex w-screen">
{token && (
<div className="w-17/100 bg-gray-200">
<Sidebar />
<Sidebar userRole={userRole} />
</div>
)}
<div className="w-3/4">
<Routes>
<Route path="/transakcje" element={<Transakcje />} />
<Route path="/panel" element={<PanelAdministratora />} />
<Route path="/produkty" element={<ZarzadzanieProduktami />} />
<Route path="/wydatki" element={<Wydatki />} />
<Route path="/raporty" element={<Raporty />} />
{/* Przekierowanie na stronę logowania, jeśli token jest pusty */}
<Route path="/" element={token ? <Navigate to="/transakcje" /> : <Navigate to="/login" />} />
{/* Strona logowania */}
<Route path="/login" element={token ? <Navigate to="/transakcje" /> : <Login setToken={setToken} />} />
{/* Chronione ścieżki */}
<Route path="/transakcje" element={token ? <Transakcje /> : <Navigate to="/login" />} />
<Route path="/panel" element={token ? <PanelAdministratora /> : <Navigate to="/login" />} />
<Route path="/produkty" element={token ? <ZarzadzanieProduktami /> : <Navigate to="/login" />} />
<Route path="/wydatki" element={token ? <Wydatki /> : <Navigate to="/login" />} />
<Route path="/raporty" element={token ? <Raporty /> : <Navigate to="/login" />} />
<Route path="/harmonogram" element={token ? <Harmonogram /> : <Navigate to="/login" />} />
{/* Przekierowanie dla nieznanych ścieżek */}
<Route path="*" element={<Navigate to="/login" />} />
</Routes>
</div>
</div>
</div>
</Router>
);
}
};
export default App;

View File

@ -0,0 +1,11 @@
import React from 'react';
const Harmonogram = () => {
return (
<div>
<h1>Harmonogram</h1>
</div>
);
};
export default Harmonogram;

View File

@ -0,0 +1,58 @@
import React, { useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
const Login = ({ setToken }) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const navigate = useNavigate();
const handleLogin = async (e) => {
e.preventDefault();
try {
const response = await axios.post('https://localhost:7039/api/user/login', { email, password });
const token = response.data;
setToken(token);
localStorage.setItem('token', token);
navigate('/');
} catch (error) {
setError('Nieprawidłowy email lub hasło');
}
};
return (
<div className="flex justify-center items-center h-screen">
<form onSubmit={handleLogin} className="p-4 bg-white shadow-md rounded">
<h2 className="text-2xl mb-4 text-center">Logowanie</h2>
{error && <p className="text-red-500">{error}</p>}
<div className="mb-4">
<label className="block mb-2">Email:</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="border rounded w-full p-2"
required
/>
</div>
<div className="mb-4">
<label className="block mb-2">Hasło:</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="border rounded w-full p-2"
required
/>
</div>
<button type="submit" className="w-full bg-blue-500 text-white p-2 rounded">
Zaloguj się
</button>
</form>
</div>
);
};
export default Login;

View File

@ -1,12 +1,20 @@
import React from 'react';
import { Link } from 'react-router-dom';
import { Link, useNavigate } from 'react-router-dom';
import lupaIcon from "../icons/lupa.jpg";
import domIcon from "../icons/dom.png";
import profilIcon from "../icons/profil.png";
import settingsIcon from "../icons/settings.png";
import znakIcon from "../icons/znak.png";
const Navbar = () => {
const Navbar = ({ setToken }) => {
const navigate = useNavigate();
const handleLogout = () => {
setToken(null);
localStorage.removeItem('token');
navigate('/login');
};
return (
<div className="flex items-center justify-between bg-gray-300 p-7 h-16">
<div className="flex items-center flex-shrink-0 text-black mr-6">
@ -22,7 +30,12 @@ const Navbar = () => {
<Link to="/"><img src={domIcon} alt="" className="w-8 h-8 mr-2" /></Link>
<Link to="/"><img src={znakIcon} alt="" className="w-8 h-8 mr-2" /></Link>
<Link to="/"><img src={settingsIcon} alt="" className="w-8 h-8 mr-2" /></Link>
<Link to="/"><img src={profilIcon} alt="" className="w-8 h-8 mr-2" /></Link>
<img
src={profilIcon}
alt="Profil"
className="w-8 h-8 mr-2 cursor-pointer"
onClick={handleLogout}
/>
</div>
</div>
);

View File

@ -11,13 +11,23 @@ const Raporty = () => {
const [deleteReportId, setDeleteReportId] = useState(null);
const fetchReports = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Report');
const response = await axios.get('https://localhost:7039/api/Report', {
headers: {
Authorization: `Bearer ${token}`
}
});
setReports(response.data);
} catch (error) {
console.error('Błąd podczas pobierania raportów:', error);
}
};
const openDeleteConfirmation = (transactionId) => {
setDeleteReportId(transactionId);
};
@ -35,30 +45,49 @@ const Raporty = () => {
setError('Proszę uzupełnić wszystkie pola.');
return;
}
const token = localStorage.getItem('token');
try {
console.log('Wysyłane dane:', fromDate, toDate);
const response = await axios.post('https://localhost:7039/api/Report', {
fromDate,
toDate
}, {
headers: {
Authorization: `Bearer ${token}`
}
});
const newReport = response.data;
setReports([...reports, newReport]);
} catch (error) {
console.error('Błąd podczas generowania raportu:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
const handleDeleteReport = async (reportId) => {
const token = localStorage.getItem('token');
try {
await axios.delete(`https://localhost:7039/api/Report/${reportId}`);
await axios.delete(`https://localhost:7039/api/Report/${reportId}`, {
headers: {
Authorization: `Bearer ${token}`
}
});
fetchReports();
setDeleteReportId(null);
} catch (error) {
console.error('Błąd podczas usuwania raportu:', error);
if (error.response && error.response.data) {
setError(error.response.data);
} else {
setError('Wystąpił nieoczekiwany błąd. Spróbuj ponownie później.');
}
}
};
const formatDate = (dateString) => {
const options = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' };
const date = new Date(dateString);
@ -77,7 +106,7 @@ const Raporty = () => {
<input type="datetime-local" id="fromDate" value={fromDate} onChange={(e) => setFromDate(e.target.value)} className="mr-5" />
<label htmlFor="toDate" className="mr-3">Do:</label>
<input type="datetime-local" id="toDate" value={toDate} onChange={(e) => setToDate(e.target.value)} className="mr-5" />
<button onClick={() =>{handleGenerateReport(); console.log()}} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Generuj</button>
<button onClick={handleGenerateReport} className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">Generuj</button>
</div>
<div className="mt-5">
<h2 className="text-2xl font-bold mb-4">Raporty</h2>
@ -127,7 +156,8 @@ const Raporty = () => {
message="Czy na pewno chcesz usunąć ten raport?"
onCancel={closeDeleteConfirmation}
onConfirm={() => handleDeleteReport(deleteReportId)}
/>)}
/>
)}
</div>
);
};

View File

@ -7,15 +7,19 @@ import harmonogramIcon from "../icons/harmonogram.png";
import wydatkiIcon from "../icons/wydatki.png";
import raportyIcon from "../icons/raport.png";
const Sidebar = () => {
const Sidebar = ({ userRole }) => {
return (
<div className="bg-gray-200 h-screen flex justify-center marign-0 w-max">
<ul className="">
{userRole !== 'User' && (
<>
<Link to="/panel" className="text-black px-10 py-2 block font-customFont text-center w-max">
<li className='flex items-center'>
<img src={adminIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Panel Administratora
</li></Link>
</>
)}
<Link to="/produkty" className="text-black px-10 py-2 block font-customFont text-center w-max">
<li className='flex items-center'>
<img src={produktIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
@ -31,6 +35,8 @@ const Sidebar = () => {
<img src={harmonogramIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Harmonogram
</li></Link>
{userRole !== 'User' && (
<>
<Link to="/wydatki" className="text-black px-10 py-2 block font-customFont text-center w-max flex-item-center">
<li className='flex items-center'>
<img src={wydatkiIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
@ -41,9 +47,10 @@ const Sidebar = () => {
<img src={raportyIcon} alt="Obrazek 1" className="w-7 h-7 mr-2" />
Raporty
</li></Link>
</>
)}
</ul>
</div>
);
}
export default Sidebar;

View File

@ -34,16 +34,34 @@ const Transakcje = () => {
});
const fetchTransactions = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Transaction');
const response = await axios.get('https://localhost:7039/api/Transaction', {
headers: {
Authorization: `Bearer ${token}`
}
});
setTransactions(response.data);
} catch (error) {
console.error('Błąd podczas dodawania transakcji:', error);
}
};
const fetchProducts = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Products');
const response = await axios.get('https://localhost:7039/api/Products', {
headers: {
Authorization: `Bearer ${token}`
}
});
setProducts(response.data.map(product => ({ value: product.id, label: product.name })));
} catch (error) {
console.error('Błąd podczas pobierania produktów:', error);

View File

@ -16,8 +16,17 @@ const Wydatki = () => {
});
const fetchExpenses = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Expenses');
const response = await axios.get('https://localhost:7039/api/Expenses', {
headers: {
Authorization: `Bearer ${token}`
}
});
setExpenses(response.data);
} catch (error) {
console.error('Błąd podczas pobierania wydatków:', error);
@ -33,8 +42,13 @@ const Wydatki = () => {
setError('Proszę uzupełnić wszystkie pola.');
return;
}
const token = localStorage.getItem('token');
try {
const response = await axios.post('https://localhost:7039/api/Expenses', newExpense);
const response = await axios.post('https://localhost:7039/api/Expenses', newExpense, {
headers: {
Authorization: `Bearer ${token}`
}
});
const addedExpense = response.data;
setExpenses([...expenses, addedExpense]);
setNewExpense({
@ -45,12 +59,18 @@ const Wydatki = () => {
setShowModal(false);
} catch (error) {
console.error('Błąd podczas dodawania wydatku:', error);
setError('Wystąpił błąd podczas dodawania wydatku.');
}
};
const handleDeleteExpense = async (expenseId) => {
const token = localStorage.getItem('token');
try {
await axios.delete(`https://localhost:7039/api/Expenses/${expenseId}`);
await axios.delete(`https://localhost:7039/api/Expenses/${expenseId}`, {
headers: {
Authorization: `Bearer ${token}`
}
});
fetchExpenses();
setDeleteExpenseId(null);
} catch (error) {
@ -62,8 +82,9 @@ const Wydatki = () => {
}
}
};
const openDeleteConfirmation = (transactionId) => {
setDeleteExpenseId(transactionId);
const openDeleteConfirmation = (expenseId) => {
setDeleteExpenseId(expenseId);
};
const closeDeleteConfirmation = () => {
@ -78,7 +99,6 @@ const Wydatki = () => {
return (
<div className="p-10 ml-11">
<div className="mt-5">
<div className='flex items-center justify-between'>
<div className='h-20 text-5xl ml-1'>
@ -107,7 +127,8 @@ const Wydatki = () => {
<td className="border border-gray-300 p-2">{expense.description}</td>
<td className="border border-gray-300 p-2">
<button onClick={() => openDeleteConfirmation(expense.id)} className="mr-2 bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded flex">
<img src={koszIcon} alt="" className="w-8 h-8 mr-2" />Usuń</button>
<img src={koszIcon} alt="" className="w-8 h-8 mr-2" />Usuń
</button>
</td>
</tr>
))}
@ -144,7 +165,7 @@ const Wydatki = () => {
</div>
</div>
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<button onClick={() => {handleAddExpense();setShowModal(false);}} type="button" className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-green transition ease-in-out duration-150 sm:text-sm sm:leading-5">
<button onClick={() => { handleAddExpense(); }} type="button" className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-green-600 text-base font-medium text-white hover:bg-green-500 focus:outline-none focus:border-green-700 focus:shadow-outline-green transition ease-in-out duration-150 sm:text-sm sm:leading-5">
Dodaj
</button>
<button onClick={() => setShowModal(false)} type="button" className="mt-3 sm:mt-0 mr-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue transition ease-in-out duration-150 sm:text-sm sm:leading-5">
@ -170,11 +191,11 @@ const Wydatki = () => {
<ConfirmationModal
message="Czy na pewno chcesz usunąć ten raport?"
onCancel={closeDeleteConfirmation}
onConfirm={() => {handleDeleteExpense(deleteExpenseId); setDeleteExpenseId(false);}}
/>)}
onConfirm={() => { handleDeleteExpense(deleteExpenseId); }}
/>
)}
</div>
);
};
export default Wydatki;

View File

@ -21,8 +21,18 @@ const ZarzadzanieProduktami = () => {
const [editProduct, setEditProduct] = useState(null);
const fetchProducts = async () => {
const token = localStorage.getItem('token');
if (!token) {
console.error('Brak tokena. Użytkownik musi być zalogowany.');
return;
}
try {
const response = await axios.get('https://localhost:7039/api/Products');
const response = await axios.get('https://localhost:7039/api/products', {
headers: {
Authorization: `Bearer ${token}`
}
});
setProducts(response.data);
} catch (error) {
console.error('Błąd podczas pobierania produktów:', error);

File diff suppressed because it is too large Load Diff