-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.js
More file actions
31 lines (24 loc) · 1.04 KB
/
Copy pathjwt.js
File metadata and controls
31 lines (24 loc) · 1.04 KB
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 jwtAuthMiddleware = (req, res, next) => {
// First check if the request headers have authorization or not
const authorization = req.headers.authorization;
if (!authorization) return res.status(401).json({ error: 'Token not found' });
// Extract the JWT token from the request headers
const token = authorization.split(' ')[1]; // FIXED SPLIT
if (!token) return res.status(401).json({ error: 'Unauthorized' });
try {
// Verify the JWT token
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// Attach user information to the request object
req.user = decoded;
next();
} catch (err) {
console.error("JWT Error: ", err);
res.status(401).json({ error: 'Invalid token' });
}
};
// Function to generate JWT token
const generateToken = (userData) => {
return jwt.sign(userData, process.env.JWT_SECRET, { expiresIn: 30000 }); // Token expires in 30000 seconds
};
module.exports = { jwtAuthMiddleware, generateToken };