first test
This commit is contained in:
47
middleware/authMiddleware.js
Normal file
47
middleware/authMiddleware.js
Normal file
@ -0,0 +1,47 @@
|
||||
// middleware/authMiddleware.js
|
||||
// Middleware to protect routes by verifying JWT
|
||||
|
||||
const jwt = require('jsonwebtoken');
|
||||
require('dotenv').config();
|
||||
|
||||
const JWT_SECRET = process.env.JWT_SECRET;
|
||||
|
||||
const authenticateToken = (req, res, next) => {
|
||||
// Get token from the 'token' cookie
|
||||
const token = req.cookies.token;
|
||||
|
||||
// If no token is present, deny access
|
||||
if (!token) {
|
||||
// If the request is for an API endpoint, return 401 Unauthorized
|
||||
if (req.path.startsWith('/api/')) {
|
||||
return res.status(401).json({ message: 'Zugriff verweigert. Kein Token vorhanden.' });
|
||||
}
|
||||
// Otherwise, redirect to the login page
|
||||
return res.redirect('/login');
|
||||
}
|
||||
|
||||
// Verify the token
|
||||
jwt.verify(token, JWT_SECRET, (err, user) => {
|
||||
if (err) {
|
||||
console.error('JWT Verification Error:', err.message);
|
||||
// If token is invalid or expired
|
||||
if (req.path.startsWith('/api/')) {
|
||||
// Clear the invalid cookie and return 403 Forbidden for API requests
|
||||
res.clearCookie('token');
|
||||
return res.status(403).json({ message: 'Token ungültig oder abgelaufen.' });
|
||||
}
|
||||
// Clear the invalid cookie and redirect to login for page requests
|
||||
res.clearCookie('token');
|
||||
return res.redirect('/login');
|
||||
}
|
||||
|
||||
// If token is valid, attach the decoded user information (payload) to the request object
|
||||
// The payload typically contains user ID, username, etc. (whatever was put in during login)
|
||||
req.user = user; // Example: user might be { id: 1, username: 'testuser' }
|
||||
|
||||
// Proceed to the next middleware or route handler
|
||||
next();
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = authenticateToken;
|
Reference in New Issue
Block a user