mirror of
https://github.com/donpat1to/Schichtenplaner.git
synced 2025-11-30 22:45:46 +01:00
added init files
This commit is contained in:
40
backend/src/middleware/auth.ts
Normal file
40
backend/src/middleware/auth.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
// backend/src/middleware/auth.ts
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import jwt from 'jsonwebtoken';
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';
|
||||
|
||||
export interface AuthRequest extends Request {
|
||||
user?: {
|
||||
userId: string;
|
||||
email: string;
|
||||
role: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const authMiddleware = (req: AuthRequest, res: Response, next: NextFunction): void => {
|
||||
const token = req.header('Authorization')?.replace('Bearer ', '');
|
||||
|
||||
if (!token) {
|
||||
res.status(401).json({ error: 'Access denied. No token provided.' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded = jwt.verify(token, JWT_SECRET) as any;
|
||||
req.user = decoded;
|
||||
next();
|
||||
} catch (error) {
|
||||
res.status(400).json({ error: 'Invalid token.' });
|
||||
}
|
||||
};
|
||||
|
||||
export const requireRole = (roles: string[]) => {
|
||||
return (req: AuthRequest, res: Response, next: NextFunction): void => {
|
||||
if (!req.user || !roles.includes(req.user.role)) {
|
||||
res.status(403).json({ error: 'Access denied. Insufficient permissions.' });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
};
|
||||
};
|
||||
Reference in New Issue
Block a user