mirror of
https://github.com/donpat1to/Schichtenplaner.git
synced 2025-11-30 22:45:46 +01:00
added roll depending users
This commit is contained in:
@@ -2,17 +2,16 @@
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
const app = express();
|
||||
const PORT = 3002;
|
||||
|
||||
// IN-MEMORY STORE für Mitarbeiter (mit gehashten Passwörtern)
|
||||
// IN-MEMORY STORE für Mitarbeiter
|
||||
let employees = [
|
||||
{
|
||||
id: '1',
|
||||
email: 'admin@schichtplan.de',
|
||||
password: '$2a$10$8K1p/a0dRTlB0ZQ1.5Q.2e5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q', // admin123
|
||||
password: 'admin123', // Klartext für Test
|
||||
name: 'Admin User',
|
||||
role: 'admin',
|
||||
isActive: true,
|
||||
@@ -24,7 +23,7 @@ let employees = [
|
||||
{
|
||||
id: '2',
|
||||
email: 'instandhalter@schichtplan.de',
|
||||
password: '$2a$10$8K1p/a0dRTlB0ZQ1.5Q.2e5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q5Q', // instandhalter123
|
||||
password: 'instandhalter123',
|
||||
name: 'Max Instandhalter',
|
||||
role: 'instandhalter',
|
||||
isActive: true,
|
||||
@@ -32,6 +31,30 @@ let employees = [
|
||||
department: 'Produktion',
|
||||
createdAt: new Date().toISOString(),
|
||||
lastLogin: new Date().toISOString()
|
||||
},
|
||||
{
|
||||
id: '3',
|
||||
email: 'mitarbeiter1@schichtplan.de',
|
||||
password: 'user123',
|
||||
name: 'Anna Müller',
|
||||
role: 'user',
|
||||
isActive: true,
|
||||
phone: '+49 123 456791',
|
||||
department: 'Logistik',
|
||||
createdAt: new Date().toISOString(),
|
||||
lastLogin: new Date().toISOString()
|
||||
},
|
||||
{
|
||||
id: '4',
|
||||
email: 'mitarbeiter2@schichtplan.de',
|
||||
password: 'user123',
|
||||
name: 'Tom Schmidt',
|
||||
role: 'user',
|
||||
isActive: true,
|
||||
phone: '+49 123 456792',
|
||||
department: 'Produktion',
|
||||
createdAt: new Date().toISOString(),
|
||||
lastLogin: new Date().toISOString()
|
||||
}
|
||||
];
|
||||
|
||||
@@ -51,18 +74,19 @@ app.get('/api/health', (req: any, res: any) => {
|
||||
});
|
||||
});
|
||||
|
||||
// Login Route für ALLE Benutzer
|
||||
app.post('/api/auth/login', async (req: any, res: any) => {
|
||||
try {
|
||||
const { email, password } = req.body;
|
||||
|
||||
console.log('🔐 Login attempt for:', email);
|
||||
console.log('📧 Email:', email);
|
||||
console.log('🔑 Password length:', password?.length);
|
||||
|
||||
if (!email || !password) {
|
||||
return res.status(400).json({ error: 'Email and password are required' });
|
||||
}
|
||||
|
||||
// Benutzer in der employees Liste suchen
|
||||
// Benutzer suchen
|
||||
const user = employees.find(emp => emp.email === email && emp.isActive);
|
||||
|
||||
if (!user) {
|
||||
@@ -70,20 +94,15 @@ app.post('/api/auth/login', async (req: any, res: any) => {
|
||||
return res.status(401).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
// Passwort vergleichen
|
||||
// Für Test: Wenn Passwort nicht gehasht ist (neue Benutzer), direkt vergleichen
|
||||
let isPasswordValid = false;
|
||||
console.log('🔍 User found:', user.email);
|
||||
console.log('💾 Stored password:', user.password);
|
||||
console.log('↔️ Password match:', password === user.password);
|
||||
|
||||
if (user.password.startsWith('$2a$')) {
|
||||
// Gehashtes Passwort (bcrypt)
|
||||
isPasswordValid = await bcrypt.compare(password, user.password);
|
||||
} else {
|
||||
// Klartext-Passwort (für Test)
|
||||
isPasswordValid = password === user.password;
|
||||
}
|
||||
// Passwort-Überprüfung
|
||||
const isPasswordValid = password === user.password;
|
||||
|
||||
if (!isPasswordValid) {
|
||||
console.log('❌ Invalid password for:', email);
|
||||
console.log('❌ Password invalid for:', email);
|
||||
return res.status(401).json({ error: 'Invalid credentials' });
|
||||
}
|
||||
|
||||
@@ -107,7 +126,7 @@ app.post('/api/auth/login', async (req: any, res: any) => {
|
||||
}
|
||||
});
|
||||
|
||||
// EMPLOYEE ROUTES mit In-Memory Store
|
||||
// EMPLOYEE ROUTES
|
||||
app.get('/api/employees', async (req: any, res: any) => {
|
||||
try {
|
||||
console.log('📋 Fetching employees - Total:', employees.length);
|
||||
@@ -139,19 +158,22 @@ app.post('/api/employees', async (req: any, res: any) => {
|
||||
return res.status(400).json({ error: 'Password must be at least 6 characters long' });
|
||||
}
|
||||
|
||||
// Rollen-Validierung
|
||||
const validRoles = ['admin', 'instandhalter', 'user'];
|
||||
if (!validRoles.includes(role)) {
|
||||
return res.status(400).json({ error: 'Ungültige Rolle' });
|
||||
}
|
||||
|
||||
// Check if email already exists
|
||||
if (employees.find(emp => emp.email === email)) {
|
||||
return res.status(409).json({ error: 'Email already exists' });
|
||||
}
|
||||
|
||||
// Passwort hashen für neue Benutzer
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
|
||||
// Neuen Mitarbeiter erstellen
|
||||
// NEUEN Benutzer erstellen
|
||||
const newEmployee = {
|
||||
id: uuidv4(),
|
||||
email,
|
||||
password: hashedPassword, // Gehashtes Passwort speichern
|
||||
password: password, // Klartext speichern für einfachen Test
|
||||
name,
|
||||
role,
|
||||
isActive: true,
|
||||
@@ -161,10 +183,14 @@ app.post('/api/employees', async (req: any, res: any) => {
|
||||
lastLogin: ''
|
||||
};
|
||||
|
||||
// Zum Store hinzufügen
|
||||
employees.push(newEmployee);
|
||||
|
||||
console.log('✅ Employee created. Total employees:', employees.length);
|
||||
console.log('✅ Employee created:', {
|
||||
email: newEmployee.email,
|
||||
name: newEmployee.name,
|
||||
role: newEmployee.role
|
||||
});
|
||||
console.log('📊 Total employees:', employees.length);
|
||||
|
||||
// Response ohne Passwort
|
||||
const { password: _, ...employeeWithoutPassword } = newEmployee;
|
||||
@@ -189,7 +215,7 @@ app.put('/api/employees/:id', async (req: any, res: any) => {
|
||||
return res.status(404).json({ error: 'Employee not found' });
|
||||
}
|
||||
|
||||
// Mitarbeiter aktualisieren (Passwort bleibt unverändert)
|
||||
// Mitarbeiter aktualisieren
|
||||
employees[employeeIndex] = {
|
||||
...employees[employeeIndex],
|
||||
name: name || employees[employeeIndex].name,
|
||||
@@ -221,7 +247,7 @@ app.delete('/api/employees/:id', async (req: any, res: any) => {
|
||||
return res.status(404).json({ error: 'Employee not found' });
|
||||
}
|
||||
|
||||
// Soft delete - set isActive to false
|
||||
// Soft delete
|
||||
employees[employeeIndex].isActive = false;
|
||||
|
||||
console.log('✅ Employee deactivated:', employees[employeeIndex].name);
|
||||
@@ -232,38 +258,7 @@ app.delete('/api/employees/:id', async (req: any, res: any) => {
|
||||
}
|
||||
});
|
||||
|
||||
// Get current user profile
|
||||
app.get('/api/auth/me', async (req: any, res: any) => {
|
||||
try {
|
||||
// Einfache Mock-Implementation
|
||||
// In einer echten App würde man den Token verifizieren
|
||||
const token = req.headers.authorization?.replace('Bearer ', '');
|
||||
|
||||
if (!token) {
|
||||
return res.status(401).json({ error: 'No token provided' });
|
||||
}
|
||||
|
||||
// Einfache Token-"Validierung" für Demo
|
||||
const tokenParts = token.split('-');
|
||||
const userId = tokenParts[tokenParts.length - 1];
|
||||
|
||||
const user = employees.find(emp => emp.id === userId && emp.isActive);
|
||||
|
||||
if (!user) {
|
||||
return res.status(401).json({ error: 'Invalid token' });
|
||||
}
|
||||
|
||||
// User ohne Passwort zurückgeben
|
||||
const { password, ...userWithoutPassword } = user;
|
||||
res.json(userWithoutPassword);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Error getting user profile:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
});
|
||||
|
||||
// Availability Routes (Mock)
|
||||
// Availability Routes
|
||||
app.get('/api/employees/:employeeId/availabilities', async (req: any, res: any) => {
|
||||
try {
|
||||
const { employeeId } = req.params;
|
||||
@@ -284,7 +279,7 @@ app.get('/api/employees/:employeeId/availabilities', async (req: any, res: any)
|
||||
dayOfWeek: day,
|
||||
startTime: slot.start,
|
||||
endTime: slot.end,
|
||||
isAvailable: day >= 1 && day <= 5 // Nur Mo-Fr verfügbar
|
||||
isAvailable: day >= 1 && day <= 5
|
||||
}))
|
||||
);
|
||||
|
||||
@@ -301,7 +296,6 @@ app.put('/api/employees/:employeeId/availabilities', async (req: any, res: any)
|
||||
const availabilities = req.body;
|
||||
|
||||
console.log('💾 Saving availabilities for:', employeeId);
|
||||
console.log('Data:', availabilities);
|
||||
|
||||
// Mock erfolgreiches Speichern
|
||||
res.json(availabilities);
|
||||
@@ -316,6 +310,13 @@ app.listen(PORT, () => {
|
||||
console.log('🎉 BACKEND STARTED SUCCESSFULLY!');
|
||||
console.log(`📍 Port: ${PORT}`);
|
||||
console.log(`📍 Health: http://localhost:${PORT}/api/health`);
|
||||
console.log('🔐 Login system READY for ALL users!');
|
||||
console.log('👥 Employee management READY with proper authentication!');
|
||||
console.log('');
|
||||
console.log('🔐 SIMPLE LOGIN READY - Plain text passwords for testing!');
|
||||
console.log('');
|
||||
console.log('📋 TEST ACCOUNTS:');
|
||||
console.log(' 👑 Admin: admin@schichtplan.de / admin123');
|
||||
console.log(' 🔧 Instandhalter: instandhalter@schichtplan.de / instandhalter123');
|
||||
console.log(' 👤 User1: mitarbeiter1@schichtplan.de / user123');
|
||||
console.log(' 👤 User2: mitarbeiter2@schichtplan.de / user123');
|
||||
console.log(' 👤 Patrick: patrick@patrick.de / 12345678');
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
// frontend/src/App.tsx
|
||||
// frontend/src/App.tsx - KORRIGIERT
|
||||
import React from 'react';
|
||||
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||
@@ -18,76 +18,109 @@ const ProtectedRoute: React.FC<{ children: React.ReactNode; roles?: string[] }>
|
||||
}) => {
|
||||
const { user, loading, hasRole } = useAuth();
|
||||
|
||||
console.log('🔒 ProtectedRoute - User:', user?.email, 'Loading:', loading);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{ textAlign: 'center', padding: '40px' }}>
|
||||
<div>⏳ Lade Anwendung...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user) {
|
||||
console.log('❌ No user, redirecting to login');
|
||||
return <Login />;
|
||||
}
|
||||
|
||||
if (!hasRole(roles)) {
|
||||
console.log('❌ Insufficient permissions for:', user.email);
|
||||
return (
|
||||
<Layout>
|
||||
<div style={{ textAlign: 'center', padding: '40px' }}>
|
||||
<div>⏳ Lade Anwendung...</div>
|
||||
<h2>Zugriff verweigert</h2>
|
||||
<p>Sie haben keine Berechtigung für diese Seite.</p>
|
||||
</div>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
||||
if (!user || !hasRole(roles)) {
|
||||
return <Login />;
|
||||
}
|
||||
|
||||
console.log('✅ Access granted for:', user.email);
|
||||
return <Layout>{children}</Layout>;
|
||||
};
|
||||
|
||||
function App() {
|
||||
const { user, loading } = useAuth();
|
||||
|
||||
console.log('🏠 App Component - User:', user?.email, 'Loading:', loading);
|
||||
|
||||
// Während des Ladens zeigen wir einen Loading Screen
|
||||
if (loading) {
|
||||
return (
|
||||
<div style={{
|
||||
textAlign: 'center',
|
||||
padding: '100px 20px',
|
||||
fontSize: '18px'
|
||||
}}>
|
||||
<div>⏳ SchichtPlaner wird geladen...</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Router>
|
||||
<Routes>
|
||||
{/* Public Route */}
|
||||
<Route path="/login" element={<Login />} />
|
||||
|
||||
{/* Protected Routes with Layout */}
|
||||
<Route path="/" element={
|
||||
<ProtectedRoute>
|
||||
<Dashboard />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/shift-plans" element={
|
||||
<ProtectedRoute>
|
||||
<ShiftPlanList />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/shift-plans/new" element={
|
||||
<ProtectedRoute roles={['admin', 'instandhalter']}>
|
||||
<ShiftPlanCreate />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/employees" element={
|
||||
<ProtectedRoute roles={['admin', 'instandhalter']}>
|
||||
<EmployeeManagement />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/settings" element={
|
||||
<ProtectedRoute roles={['admin']}>
|
||||
<Settings />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/help" element={
|
||||
<ProtectedRoute>
|
||||
<Help />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
</Routes>
|
||||
</Router>
|
||||
);
|
||||
}
|
||||
|
||||
// Hauptkomponente mit AuthProvider
|
||||
function AppWrapper() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<Router>
|
||||
<Routes>
|
||||
{/* Public Route */}
|
||||
<Route path="/login" element={<Login />} />
|
||||
|
||||
{/* Protected Routes with Layout */}
|
||||
<Route path="/" element={
|
||||
<ProtectedRoute>
|
||||
<Dashboard />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/shift-plans" element={
|
||||
<ProtectedRoute>
|
||||
<ShiftPlanList />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/shift-plans/new" element={
|
||||
<ProtectedRoute roles={['admin', 'instandhalter']}>
|
||||
<ShiftPlanCreate />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/employees" element={
|
||||
<ProtectedRoute roles={['admin', 'instandhalter']}>
|
||||
<EmployeeManagement />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/settings" element={
|
||||
<ProtectedRoute roles={['admin']}>
|
||||
<Settings />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
<Route path="/help" element={
|
||||
<ProtectedRoute>
|
||||
<Help />
|
||||
</ProtectedRoute>
|
||||
} />
|
||||
|
||||
{/* Legal Pages (ohne Layout für einfacheren Zugang) */}
|
||||
<Route path="/impressum" element={<div>Impressum Seite</div>} />
|
||||
<Route path="/datenschutz" element={<div>Datenschutz Seite</div>} />
|
||||
<Route path="/agb" element={<div>AGB Seite</div>} />
|
||||
</Routes>
|
||||
</Router>
|
||||
<App />
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
||||
export default AppWrapper;
|
||||
@@ -1,4 +1,4 @@
|
||||
// frontend/src/contexts/AuthContext.tsx
|
||||
// frontend/src/contexts/AuthContext.tsx - KORRIGIERT
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import { authService, User, LoginRequest } from '../services/authService';
|
||||
|
||||
@@ -8,6 +8,7 @@ interface AuthContextType {
|
||||
logout: () => void;
|
||||
hasRole: (roles: string[]) => boolean;
|
||||
loading: boolean;
|
||||
refreshUser: () => void; // NEU: Force refresh
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
@@ -15,22 +16,44 @@ const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
|
||||
const [user, setUser] = useState<User | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [refreshTrigger, setRefreshTrigger] = useState(0); // NEU: Refresh trigger
|
||||
|
||||
// User beim Start laden
|
||||
useEffect(() => {
|
||||
// User aus localStorage laden beim Start
|
||||
const savedUser = authService.getCurrentUser();
|
||||
if (savedUser) {
|
||||
setUser(savedUser);
|
||||
console.log('✅ User from localStorage:', savedUser.email);
|
||||
}
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
// NEU: User vom Server laden wenn nötig
|
||||
useEffect(() => {
|
||||
if (refreshTrigger > 0) {
|
||||
const loadUserFromServer = async () => {
|
||||
const serverUser = await authService.fetchCurrentUser();
|
||||
if (serverUser) {
|
||||
setUser(serverUser);
|
||||
console.log('✅ User from server:', serverUser.email);
|
||||
}
|
||||
};
|
||||
loadUserFromServer();
|
||||
}
|
||||
}, [refreshTrigger]);
|
||||
|
||||
const login = async (credentials: LoginRequest) => {
|
||||
try {
|
||||
console.log('🔄 Attempting login...');
|
||||
const response = await authService.login(credentials);
|
||||
setUser(response.user);
|
||||
console.log('✅ Login successful, user set:', response.user.email);
|
||||
|
||||
// Force refresh der App
|
||||
setRefreshTrigger(prev => prev + 1);
|
||||
|
||||
} catch (error) {
|
||||
console.error('AuthContext: Login fehlgeschlagen', error);
|
||||
console.error('❌ Login failed:', error);
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
@@ -38,6 +61,11 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
||||
const logout = () => {
|
||||
authService.logout();
|
||||
setUser(null);
|
||||
console.log('✅ Logout completed');
|
||||
};
|
||||
|
||||
const refreshUser = () => {
|
||||
setRefreshTrigger(prev => prev + 1);
|
||||
};
|
||||
|
||||
const hasRole = (roles: string[]) => {
|
||||
@@ -49,7 +77,8 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children
|
||||
login,
|
||||
logout,
|
||||
hasRole,
|
||||
loading
|
||||
loading,
|
||||
refreshUser // NEU
|
||||
};
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
// frontend/src/pages/Auth/Login.tsx
|
||||
// frontend/src/pages/Auth/Login.tsx - KORRIGIERT
|
||||
import React, { useState } from 'react';
|
||||
import { useAuth } from '../../contexts/AuthContext';
|
||||
|
||||
const Login: React.FC = () => {
|
||||
const [email, setEmail] = useState('admin@schichtplan.de');
|
||||
const [password, setPassword] = useState('admin123');
|
||||
const [email, setEmail] = useState('');
|
||||
const [password, setPassword] = useState('');
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const { login } = useAuth();
|
||||
const { login, user } = useAuth(); // user hinzugefügt für Debugging
|
||||
|
||||
console.log('Login Komponente - State:', { email, password, error, loading });
|
||||
console.log('🔍 Login Component - Current user:', user);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -18,13 +18,14 @@ const Login: React.FC = () => {
|
||||
setLoading(true);
|
||||
|
||||
try {
|
||||
console.log('Login startet mit:', { email });
|
||||
console.log('🚀 Starting login process...');
|
||||
await login({ email, password });
|
||||
console.log('Login erfolgreich abgeschlossen');
|
||||
// Force refresh als Fallback
|
||||
window.location.reload();
|
||||
console.log('✅ Login process completed');
|
||||
|
||||
// Navigation passiert automatisch durch AuthContext
|
||||
|
||||
} catch (err: any) {
|
||||
console.error('Login Fehler:', err);
|
||||
console.error('❌ Login error:', err);
|
||||
setError(err.message || 'Login fehlgeschlagen');
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -37,10 +38,9 @@ const Login: React.FC = () => {
|
||||
margin: '100px auto',
|
||||
padding: '20px',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '8px',
|
||||
backgroundColor: '#f9f9f9'
|
||||
borderRadius: '8px'
|
||||
}}>
|
||||
<h2 style={{ textAlign: 'center', marginBottom: '20px' }}>Anmelden</h2>
|
||||
<h2>Anmelden</h2>
|
||||
|
||||
{error && (
|
||||
<div style={{
|
||||
@@ -48,8 +48,7 @@ const Login: React.FC = () => {
|
||||
backgroundColor: '#ffe6e6',
|
||||
padding: '10px',
|
||||
borderRadius: '4px',
|
||||
marginBottom: '15px',
|
||||
border: '1px solid #ffcccc'
|
||||
marginBottom: '15px'
|
||||
}}>
|
||||
<strong>Fehler:</strong> {error}
|
||||
</div>
|
||||
@@ -57,7 +56,7 @@ const Login: React.FC = () => {
|
||||
|
||||
<form onSubmit={handleSubmit}>
|
||||
<div style={{ marginBottom: '15px' }}>
|
||||
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
|
||||
<label style={{ display: 'block', marginBottom: '5px' }}>
|
||||
E-Mail:
|
||||
</label>
|
||||
<input
|
||||
@@ -65,18 +64,12 @@ const Login: React.FC = () => {
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px',
|
||||
border: '1px solid #ccc',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
style={{ width: '100%', padding: '8px', border: '1px solid #ccc', borderRadius: '4px' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div style={{ marginBottom: '20px' }}>
|
||||
<label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>
|
||||
<div style={{ marginBottom: '15px' }}>
|
||||
<label style={{ display: 'block', marginBottom: '5px' }}>
|
||||
Passwort:
|
||||
</label>
|
||||
<input
|
||||
@@ -84,13 +77,7 @@ const Login: React.FC = () => {
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px',
|
||||
border: '1px solid #ccc',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px'
|
||||
}}
|
||||
style={{ width: '100%', padding: '8px', border: '1px solid #ccc', borderRadius: '4px' }}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -99,31 +86,23 @@ const Login: React.FC = () => {
|
||||
disabled={loading}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '12px',
|
||||
backgroundColor: loading ? '#6c757d' : '#007bff',
|
||||
padding: '10px',
|
||||
backgroundColor: loading ? '#ccc' : '#007bff',
|
||||
color: 'white',
|
||||
border: 'none',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px',
|
||||
fontWeight: 'bold',
|
||||
cursor: loading ? 'not-allowed' : 'pointer',
|
||||
transition: 'background-color 0.2s'
|
||||
cursor: loading ? 'not-allowed' : 'pointer'
|
||||
}}
|
||||
>
|
||||
{loading ? '⏳ Anmeldung...' : 'Anmelden'}
|
||||
{loading ? 'Anmeldung...' : 'Anmelden'}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div style={{
|
||||
marginTop: '20px',
|
||||
padding: '15px',
|
||||
backgroundColor: '#e7f3ff',
|
||||
borderRadius: '4px',
|
||||
border: '1px solid #b3d9ff'
|
||||
}}>
|
||||
<h4 style={{ margin: '0 0 10px 0' }}>Test Account:</h4>
|
||||
<p style={{ margin: '5px 0' }}><strong>Email:</strong> admin@schichtplan.de</p>
|
||||
<p style={{ margin: '5px 0' }}><strong>Passwort:</strong> admin123</p>
|
||||
<div style={{ marginTop: '15px', textAlign: 'center' }}>
|
||||
<p><strong>Test Accounts:</strong></p>
|
||||
<p>admin@schichtplan.de / admin123</p>
|
||||
<p>instandhalter@schichtplan.de / instandhalter123</p>
|
||||
<p>user@schichtplan.de / user123</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Employee, CreateEmployeeRequest, UpdateEmployeeRequest } from '../../../types/employee';
|
||||
import { employeeService } from '../../../services/employeeService';
|
||||
import { useAuth } from '../../../contexts/AuthContext';
|
||||
|
||||
interface EmployeeFormProps {
|
||||
mode: 'create' | 'edit';
|
||||
@@ -10,6 +11,13 @@ interface EmployeeFormProps {
|
||||
onCancel: () => void;
|
||||
}
|
||||
|
||||
// Rollen Definition
|
||||
const ROLE_OPTIONS = [
|
||||
{ value: 'user', label: 'Mitarbeiter', description: 'Kann eigene Schichten einsehen' },
|
||||
{ value: 'instandhalter', label: 'Instandhalter', description: 'Kann Schichtpläne erstellen und Mitarbeiter verwalten' },
|
||||
{ value: 'admin', label: 'Administrator', description: 'Voller Zugriff auf alle Funktionen' }
|
||||
] as const;
|
||||
|
||||
const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
mode,
|
||||
employee,
|
||||
@@ -27,6 +35,7 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const { hasRole } = useAuth();
|
||||
|
||||
useEffect(() => {
|
||||
if (mode === 'edit' && employee) {
|
||||
@@ -50,6 +59,14 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
}));
|
||||
};
|
||||
|
||||
// NEU: Checkbox für Rollen
|
||||
const handleRoleChange = (roleValue: 'admin' | 'instandhalter' | 'user') => {
|
||||
setFormData(prev => ({
|
||||
...prev,
|
||||
role: roleValue
|
||||
}));
|
||||
};
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
@@ -94,6 +111,19 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
return formData.name.trim() && formData.email.trim();
|
||||
};
|
||||
|
||||
// Bestimme welche Rollen der aktuelle Benutzer vergeben darf
|
||||
const getAvailableRoles = () => {
|
||||
if (hasRole(['admin'])) {
|
||||
return ROLE_OPTIONS; // Admins können alle Rollen vergeben
|
||||
}
|
||||
if (hasRole(['instandhalter'])) {
|
||||
return ROLE_OPTIONS.filter(role => role.value !== 'admin'); // Instandhalter können keine Admins erstellen
|
||||
}
|
||||
return ROLE_OPTIONS.filter(role => role.value === 'user'); // Normale User können gar nichts (sollte nicht vorkommen)
|
||||
};
|
||||
|
||||
const availableRoles = getAvailableRoles();
|
||||
|
||||
return (
|
||||
<div style={{
|
||||
maxWidth: '600px',
|
||||
@@ -146,7 +176,7 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
padding: '10px',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px'
|
||||
@@ -173,7 +203,7 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
padding: '10px',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px'
|
||||
@@ -202,7 +232,7 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
minLength={6}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
padding: '10px',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px'
|
||||
@@ -215,40 +245,7 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Rolle */}
|
||||
<div>
|
||||
<label style={{
|
||||
display: 'block',
|
||||
marginBottom: '8px',
|
||||
fontWeight: 'bold',
|
||||
color: '#2c3e50'
|
||||
}}>
|
||||
Rolle *
|
||||
</label>
|
||||
<select
|
||||
name="role"
|
||||
value={formData.role}
|
||||
onChange={handleChange}
|
||||
required
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px',
|
||||
backgroundColor: 'white'
|
||||
}}
|
||||
>
|
||||
<option value="user">Mitarbeiter (User)</option>
|
||||
<option value="instandhalter">Instandhalter</option>
|
||||
<option value="admin">Administrator</option>
|
||||
</select>
|
||||
<div style={{ fontSize: '12px', color: '#7f8c8d', marginTop: '5px' }}>
|
||||
{formData.role === 'admin' && 'Administratoren haben vollen Zugriff auf alle Funktionen.'}
|
||||
{formData.role === 'instandhalter' && 'Instandhalter können Schichtpläne erstellen und Mitarbeiter verwalten.'}
|
||||
{formData.role === 'user' && 'Mitarbeiter können ihre eigenen Schichten und Verfügbarkeiten einsehen.'}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Telefon */}
|
||||
<div>
|
||||
@@ -267,7 +264,7 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
onChange={handleChange}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
padding: '10px',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px'
|
||||
@@ -293,7 +290,7 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
onChange={handleChange}
|
||||
style={{
|
||||
width: '100%',
|
||||
padding: '10px 12px',
|
||||
padding: '10px',
|
||||
border: '1px solid #ddd',
|
||||
borderRadius: '4px',
|
||||
fontSize: '16px'
|
||||
@@ -302,9 +299,107 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* NEU: Rollen als Checkboxes */}
|
||||
<div>
|
||||
<label style={{
|
||||
display: 'block',
|
||||
marginBottom: '12px',
|
||||
fontWeight: 'bold',
|
||||
color: '#2c3e50'
|
||||
}}>
|
||||
Rolle *
|
||||
</label>
|
||||
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
|
||||
{availableRoles.map(role => (
|
||||
<div
|
||||
key={role.value}
|
||||
style={{
|
||||
display: 'flex',
|
||||
alignItems: 'flex-start',
|
||||
padding: '5px',
|
||||
border: `2px solid ${formData.role === role.value ? '#3498db' : '#e0e0e0'}`,
|
||||
borderRadius: '8px',
|
||||
backgroundColor: formData.role === role.value ? '#f8fafc' : 'white',
|
||||
cursor: 'pointer',
|
||||
transition: 'all 0.2s'
|
||||
}}
|
||||
onClick={() => handleRoleChange(role.value)}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="role"
|
||||
value={role.value}
|
||||
checked={formData.role === role.value}
|
||||
onChange={() => handleRoleChange(role.value)}
|
||||
style={{
|
||||
marginRight: '12px',
|
||||
marginTop: '2px',
|
||||
width: '18px',
|
||||
height: '18px'
|
||||
}}
|
||||
/>
|
||||
<div style={{ flex: 1 }}>
|
||||
<div style={{
|
||||
fontWeight: 'bold',
|
||||
color: '#2c3e50',
|
||||
marginBottom: '4px'
|
||||
}}>
|
||||
{role.label}
|
||||
</div>
|
||||
<div style={{
|
||||
fontSize: '14px',
|
||||
color: '#7f8c8d',
|
||||
lineHeight: '1.4'
|
||||
}}>
|
||||
{role.description}
|
||||
</div>
|
||||
</div>
|
||||
{/* Role Badge */}
|
||||
<div style={{
|
||||
padding: '4px 8px',
|
||||
backgroundColor:
|
||||
role.value === 'admin' ? '#e74c3c' :
|
||||
role.value === 'instandhalter' ? '#3498db' : '#27ae60',
|
||||
color: 'white',
|
||||
borderRadius: '12px',
|
||||
fontSize: '12px',
|
||||
fontWeight: 'bold'
|
||||
}}>
|
||||
{role.value.toUpperCase()}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Info über Berechtigungen */}
|
||||
<div style={{
|
||||
marginTop: '10px',
|
||||
padding: '10px',
|
||||
backgroundColor: '#e8f4fd',
|
||||
border: '1px solid #b6d7e8',
|
||||
borderRadius: '4px',
|
||||
fontSize: '12px',
|
||||
color: '#2c3e50'
|
||||
}}>
|
||||
<strong>Info:</strong> {
|
||||
formData.role === 'admin' ? 'Administratoren haben vollen Zugriff auf alle Funktionen.' :
|
||||
formData.role === 'instandhalter' ? 'Instandhalter können Schichtpläne erstellen und Mitarbeiter verwalten.' :
|
||||
'Mitarbeiter können ihre eigenen Schichten und Verfügbarkeiten einsehen.'
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Aktiv Status (nur beim Bearbeiten) */}
|
||||
{mode === 'edit' && (
|
||||
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
|
||||
<div style={{
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: '10px',
|
||||
padding: '15px',
|
||||
border: '1px solid #e0e0e0',
|
||||
borderRadius: '6px',
|
||||
backgroundColor: '#f8f9fa'
|
||||
}}>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="isActive"
|
||||
@@ -313,9 +408,14 @@ const EmployeeForm: React.FC<EmployeeFormProps> = ({
|
||||
onChange={handleChange}
|
||||
style={{ width: '18px', height: '18px' }}
|
||||
/>
|
||||
<label htmlFor="isActive" style={{ fontWeight: 'bold', color: '#2c3e50' }}>
|
||||
Mitarbeiter ist aktiv
|
||||
</label>
|
||||
<div>
|
||||
<label htmlFor="isActive" style={{ fontWeight: 'bold', color: '#2c3e50', display: 'block' }}>
|
||||
Mitarbeiter ist aktiv
|
||||
</label>
|
||||
<div style={{ fontSize: '12px', color: '#7f8c8d' }}>
|
||||
Inaktive Mitarbeiter können sich nicht anmelden und werden nicht für Schichten eingeplant.
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user