feat: add optional auth middleware
Made-with: Cursor
This commit is contained in:
19
backend/middleware/optional-auth.js
Normal file
19
backend/middleware/optional-auth.js
Normal file
@@ -0,0 +1,19 @@
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { JWT_SECRET } = require('./auth');
|
||||
|
||||
function optionalAuthenticateToken(req, res, next) {
|
||||
const authHeader = req.headers['authorization'];
|
||||
const token = authHeader && authHeader.split(' ')[1];
|
||||
|
||||
if (!token) {
|
||||
req.user = null;
|
||||
return next();
|
||||
}
|
||||
|
||||
jwt.verify(token, JWT_SECRET, (err, user) => {
|
||||
req.user = err ? null : user;
|
||||
next();
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { optionalAuthenticateToken };
|
||||
Reference in New Issue
Block a user