91 lines
2.2 KiB
TypeScript
91 lines
2.2 KiB
TypeScript
import { Response, NextFunction } from 'express';
|
|
import jwt from 'jsonwebtoken';
|
|
import { AuthRequest, JwtPayload } from '../types/index.js';
|
|
|
|
export function authenticate(
|
|
req: AuthRequest,
|
|
res: Response,
|
|
next: NextFunction
|
|
): void {
|
|
const authHeader = req.headers.authorization;
|
|
|
|
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
|
res.status(401).json({ success: false, error: 'Nicht authentifiziert' });
|
|
return;
|
|
}
|
|
|
|
const token = authHeader.split(' ')[1];
|
|
|
|
try {
|
|
const decoded = jwt.verify(
|
|
token,
|
|
process.env.JWT_SECRET || 'fallback-secret'
|
|
) as JwtPayload;
|
|
req.user = decoded;
|
|
next();
|
|
} catch {
|
|
res.status(401).json({ success: false, error: 'Ungültiger Token' });
|
|
}
|
|
}
|
|
|
|
export function requirePermission(...requiredPermissions: string[]) {
|
|
return (req: AuthRequest, res: Response, next: NextFunction): void => {
|
|
if (!req.user) {
|
|
res.status(401).json({ success: false, error: 'Nicht authentifiziert' });
|
|
return;
|
|
}
|
|
|
|
const userPermissions = req.user.permissions || [];
|
|
|
|
// Check if user has any of the required permissions
|
|
const hasPermission = requiredPermissions.some((perm) =>
|
|
userPermissions.includes(perm)
|
|
);
|
|
|
|
if (!hasPermission) {
|
|
res.status(403).json({
|
|
success: false,
|
|
error: 'Keine Berechtigung für diese Aktion',
|
|
});
|
|
return;
|
|
}
|
|
|
|
next();
|
|
};
|
|
}
|
|
|
|
// Middleware to check if user can access specific customer data
|
|
export function requireCustomerAccess(
|
|
req: AuthRequest,
|
|
res: Response,
|
|
next: NextFunction
|
|
): void {
|
|
if (!req.user) {
|
|
res.status(401).json({ success: false, error: 'Nicht authentifiziert' });
|
|
return;
|
|
}
|
|
|
|
const userPermissions = req.user.permissions || [];
|
|
|
|
// Admins and employees can access all customers
|
|
if (
|
|
userPermissions.includes('customers:read') ||
|
|
userPermissions.includes('customers:update')
|
|
) {
|
|
next();
|
|
return;
|
|
}
|
|
|
|
// Customers can only access their own data
|
|
const customerId = parseInt(req.params.customerId || req.params.id);
|
|
if (req.user.customerId && req.user.customerId === customerId) {
|
|
next();
|
|
return;
|
|
}
|
|
|
|
res.status(403).json({
|
|
success: false,
|
|
error: 'Kein Zugriff auf diese Kundendaten',
|
|
});
|
|
}
|