-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthenticate.js
More file actions
31 lines (24 loc) · 881 Bytes
/
Copy pathauthenticate.js
File metadata and controls
31 lines (24 loc) · 881 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
const jwt = require('jsonwebtoken');
const authenticate = (req, res, next) => {
const authHeader = req.header('Authorization');
if (!authHeader) {
return res.status(401).json({ message: 'Authorization header missing' });
}
const token = authHeader.replace('Bearer ', '');
if (!token) {
return res.status(401).json({ message: 'Token missing, authorization denied' });
}
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
console.log('Decoded JWT token:', decoded); // Log the decoded JWT token
req.user = decoded;
next();
} catch (error) {
if (error.name === 'TokenExpiredError') {
return res.status(401).json({ message: 'Token expired, please login again' });
}
console.error('Invalid token', error);
res.status(400).json({ message: 'Token is not valid' });
}
};
module.exports = authenticate;