mirror of
https://github.com/donpat1to/Schichtenplaner.git
synced 2025-12-01 06:55:45 +01:00
fixed login
This commit is contained in:
@@ -42,29 +42,38 @@ export const login = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const { email, password } = req.body as LoginRequest;
|
||||
|
||||
console.log('🔐 Login attempt for email:', email);
|
||||
|
||||
if (!email || !password) {
|
||||
console.log('❌ Missing email or password');
|
||||
return res.status(400).json({ error: 'E-Mail und Passwort sind erforderlich' });
|
||||
}
|
||||
|
||||
// Get user from database
|
||||
const user = await db.get<UserWithPassword>(
|
||||
'SELECT id, email, password, name, role, phone, department FROM users WHERE email = ?',
|
||||
'SELECT id, email, password, name, role, phone, department FROM users WHERE email = ? AND is_active = 1',
|
||||
[email]
|
||||
);
|
||||
|
||||
console.log('🔍 User found:', user ? 'Yes' : 'No');
|
||||
|
||||
if (!user) {
|
||||
console.log('❌ No user found with email:', email);
|
||||
return res.status(401).json({ error: 'Ungültige Anmeldedaten' });
|
||||
}
|
||||
|
||||
// Verify password
|
||||
const validPassword = await bcrypt.compare(password, user.password);
|
||||
console.log('🔑 Password valid:', validPassword);
|
||||
|
||||
if (!validPassword) {
|
||||
console.log('❌ Invalid password for user:', email);
|
||||
return res.status(401).json({ error: 'Ungültige Anmeldedaten' });
|
||||
}
|
||||
|
||||
// Create token payload
|
||||
// Create token payload - ID als STRING verwenden
|
||||
const tokenPayload: JWTPayload = {
|
||||
id: user.id.toString(), // ← Sicherstellen dass es string ist
|
||||
id: user.id.toString(), // ← WICHTIG: Als string
|
||||
email: user.email,
|
||||
role: user.role
|
||||
};
|
||||
@@ -79,6 +88,8 @@ export const login = async (req: Request, res: Response) => {
|
||||
// Remove password from user object
|
||||
const { password: _, ...userWithoutPassword } = user;
|
||||
|
||||
console.log('✅ Login successful for:', user.email);
|
||||
|
||||
res.json({
|
||||
user: userWithoutPassword,
|
||||
token
|
||||
@@ -92,19 +103,26 @@ export const login = async (req: Request, res: Response) => {
|
||||
export const getCurrentUser = async (req: Request, res: Response) => {
|
||||
try {
|
||||
const jwtUser = (req as any).user as JWTPayload;
|
||||
console.log('🔍 Getting current user for ID:', jwtUser?.id);
|
||||
|
||||
if (!jwtUser?.id) {
|
||||
console.log('❌ No user ID in JWT');
|
||||
return res.status(401).json({ error: 'Nicht authentifiziert' });
|
||||
}
|
||||
|
||||
const user = await db.get<User>(
|
||||
'SELECT id, email, name, role, phone, department FROM users WHERE id = ?',
|
||||
'SELECT id, email, name, role, phone, department FROM users WHERE id = ? AND is_active = 1',
|
||||
[jwtUser.id]
|
||||
);
|
||||
|
||||
console.log('🔍 User found in database:', user ? 'Yes' : 'No');
|
||||
|
||||
if (!user) {
|
||||
console.log('❌ User not found in database for ID:', jwtUser.id);
|
||||
return res.status(404).json({ error: 'Benutzer nicht gefunden' });
|
||||
}
|
||||
|
||||
console.log('✅ Returning user:', user.email);
|
||||
res.json({ user });
|
||||
} catch (error) {
|
||||
console.error('Get current user error:', error);
|
||||
|
||||
@@ -5,6 +5,25 @@ import bcrypt from 'bcryptjs';
|
||||
import { db } from '../services/databaseService.js';
|
||||
import { AuthRequest } from '../middleware/auth.js';
|
||||
|
||||
export const getEmployees = async (req: AuthRequest, res: Response): Promise<void> => {
|
||||
try {
|
||||
const employees = await db.all<any>(`
|
||||
SELECT
|
||||
id, email, name, role, is_active as isActive,
|
||||
phone, department, created_at as createdAt,
|
||||
last_login as lastLogin
|
||||
FROM users
|
||||
WHERE is_active = 1
|
||||
ORDER BY name
|
||||
`);
|
||||
|
||||
res.json(employees);
|
||||
} catch (error) {
|
||||
console.error('Error fetching employees:', error);
|
||||
res.status(500).json({ error: 'Internal server error' });
|
||||
}
|
||||
};
|
||||
|
||||
export const getEmployee = async (req: AuthRequest, res: Response): Promise<void> => {
|
||||
try {
|
||||
const { id } = req.params;
|
||||
|
||||
@@ -1,18 +1,24 @@
|
||||
// backend/src/controllers/setupController.ts
|
||||
import { Request, Response } from 'express';
|
||||
import bcrypt from 'bcrypt';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { db } from '../services/databaseService.js';
|
||||
|
||||
export const checkSetupStatus = async (req: Request, res: Response): Promise<void> => {
|
||||
try {
|
||||
const adminExists = await db.get<{ 'COUNT(*)': number }>(
|
||||
'SELECT COUNT(*) FROM users WHERE role = ?',
|
||||
'SELECT COUNT(*) FROM users WHERE role = ? AND is_active = 1',
|
||||
['admin']
|
||||
);
|
||||
|
||||
console.log('Admin exists check:', adminExists);
|
||||
|
||||
// Korrekte Rückgabe - needsSetup sollte true sein wenn KEIN Admin existiert
|
||||
const needsSetup = !adminExists || adminExists['COUNT(*)'] === 0;
|
||||
|
||||
res.json({
|
||||
needsSetup: !adminExists || adminExists['COUNT(*)'] === 0
|
||||
needsSetup: needsSetup
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error checking setup status:', error);
|
||||
@@ -26,11 +32,14 @@ export const setupAdmin = async (req: Request, res: Response): Promise<void> =>
|
||||
try {
|
||||
// Check if admin already exists
|
||||
const adminExists = await db.get<{ 'COUNT(*)': number }>(
|
||||
'SELECT COUNT(*) FROM users WHERE role = ?',
|
||||
'SELECT COUNT(*) FROM users WHERE role = ? AND is_active = 1',
|
||||
['admin']
|
||||
);
|
||||
|
||||
console.log('🔍 Admin exists check:', adminExists);
|
||||
|
||||
if (adminExists && adminExists['COUNT(*)'] > 0) {
|
||||
console.log('❌ Admin already exists');
|
||||
res.status(400).json({ error: 'Admin existiert bereits' });
|
||||
return;
|
||||
}
|
||||
@@ -38,6 +47,8 @@ export const setupAdmin = async (req: Request, res: Response): Promise<void> =>
|
||||
const { password, name, phone, department } = req.body;
|
||||
const email = 'admin@instandhaltung.de'; // Fixed admin email
|
||||
|
||||
console.log('👤 Creating admin with data:', { name, email, phone, department });
|
||||
|
||||
// Validation
|
||||
if (!password || !name) {
|
||||
res.status(400).json({ error: 'Passwort und Name sind erforderlich' });
|
||||
@@ -52,29 +63,33 @@ export const setupAdmin = async (req: Request, res: Response): Promise<void> =>
|
||||
|
||||
// Hash password
|
||||
const hashedPassword = await bcrypt.hash(password, 10);
|
||||
const adminId = randomUUID();
|
||||
const adminId = uuidv4();
|
||||
|
||||
console.log('📝 Inserting admin user with ID:', adminId);
|
||||
|
||||
try {
|
||||
// Create admin user
|
||||
await db.run(
|
||||
`INSERT INTO users (id, email, password, name, role, phone, department, is_active)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
[adminId, email, hashedPassword, name, 'admin', phone || null, department || null, true]
|
||||
[adminId, email, hashedPassword, name, 'admin', phone || null, department || null, 1]
|
||||
);
|
||||
|
||||
console.log('✅ Admin user created successfully');
|
||||
|
||||
res.status(201).json({
|
||||
success: true,
|
||||
message: 'Admin erfolgreich erstellt',
|
||||
email: email
|
||||
});
|
||||
} catch (dbError) {
|
||||
console.error('Database error during admin creation:', dbError);
|
||||
console.error('❌ Database error during admin creation:', dbError);
|
||||
res.status(500).json({
|
||||
error: 'Fehler beim Erstellen des Admin-Accounts'
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error in setup:', error);
|
||||
console.error('❌ Error in setup:', error);
|
||||
res.status(500).json({
|
||||
error: 'Ein unerwarteter Fehler ist aufgetreten'
|
||||
});
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
// backend/src/middleware/auth.ts
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { JWTPayload } from '../controllers/authController.js';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
|
||||
|
||||
@@ -14,15 +13,21 @@ export interface AuthRequest extends Request {
|
||||
}
|
||||
|
||||
export const authMiddleware = (req: AuthRequest, res: Response, next: NextFunction): void => {
|
||||
const token = req.header('Authorization')?.replace('Bearer ', '');
|
||||
const authHeader = req.header('Authorization');
|
||||
console.log('🔐 Auth middleware - Authorization header:', authHeader);
|
||||
|
||||
const token = authHeader?.replace('Bearer ', '');
|
||||
|
||||
if (!token) {
|
||||
console.log('❌ No token provided');
|
||||
res.status(401).json({ error: 'Access denied. No token provided.' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET) as JWTPayload;
|
||||
const decoded = jwt.verify(token, JWT_SECRET) as any;
|
||||
console.log('✅ Token valid for user:', decoded.email);
|
||||
|
||||
req.user = {
|
||||
userId: decoded.id,
|
||||
email: decoded.email,
|
||||
@@ -30,6 +35,7 @@ export const authMiddleware = (req: AuthRequest, res: Response, next: NextFuncti
|
||||
};
|
||||
next();
|
||||
} catch (error) {
|
||||
console.error('❌ Invalid token:', error);
|
||||
res.status(400).json({ error: 'Invalid token.' });
|
||||
}
|
||||
};
|
||||
@@ -37,6 +43,7 @@ export const authMiddleware = (req: AuthRequest, res: Response, next: NextFuncti
|
||||
export const requireRole = (roles: string[]) => {
|
||||
return (req: AuthRequest, res: Response, next: NextFunction): void => {
|
||||
if (!req.user || !roles.includes(req.user.role)) {
|
||||
console.log('❌ Insufficient permissions for user:', req.user?.email);
|
||||
res.status(403).json({ error: 'Access denied. Insufficient permissions.' });
|
||||
return;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user